From 6639b30e2468b4054b367a0dbc52b415be479c1c Mon Sep 17 00:00:00 2001 From: FredApps Date: Sun, 8 Nov 2026 22:37:07 +0100 Subject: [PATCH 001/402] fix(naming): remove comparative own-feature wording --- CHANGELOG.md | 8 +- crates/engine/src/cmds_draw.rs | 4 +- crates/engine/src/cmds_frames.rs | 2 +- crates/engine/src/cmds_text.rs | 2 +- crates/engine/src/cmds_timeline.rs | 2 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/tests.rs | 4 +- crates/engine/tests/display_names.rs | 178 ++++++++++++++++++++ docs/adr/0006-platforms-and-edit-latency.md | 2 +- docs/adr/0011-scenes.md | 2 +- docs/feature-names.md | 5 + docs/roadmap.md | 4 +- src/panels.rs | 4 +- src/stage.rs | 2 +- 14 files changed, 202 insertions(+), 19 deletions(-) create mode 100644 crates/engine/tests/display_names.rs create mode 100644 docs/feature-names.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e514bf3..379af7c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -* **Filters** (Properties › Filters, on movie clip and button instances as in Animate): **Drop +* **Filters** (Properties › Filters, on movie clip and button instances): **Drop Shadow**, **Blur**, **Glow** and **Adjust Color**, in any order and combination, with blur X/Y, quality (Low, Medium, High), strength, colour, angle and distance, and inner, knockout and hide object. They show on the stage and in every picture export; SVG export writes @@ -11,7 +11,7 @@ Animate. Animate documents keep their instances' filters (bevel and gradient filters are reported). Headless: `element.set_filters`. -* **Blend modes** (Properties › Blending, on movie clip and button instances as in Animate): +* **Blend modes** (Properties › Blending, on movie clip and button instances): Normal, Layer, Darken, Multiply, Lighten, Screen, Overlay, Hard Light, Add, Subtract, Difference, Invert, Alpha and Erase. The instance is composited on its own and then blended with what is below, on the stage and in every export. SVG export writes the CSS blend modes @@ -72,7 +72,7 @@ (loop, play once, single frame) and **First frame** (`symbol.set_kind`, `element.set_loop`). * **Symbols fade as one.** A symbol instance below full opacity now composites its contents - first and then fades the result, as in Animate, so overlapping parts no longer show through + first and then fades the result, so overlapping parts no longer show through each other. This applies on the stage and in PNG, GIF, sprite sheet and SVG exports (SVG uses ``). Fully opaque instances render exactly as before. @@ -114,7 +114,7 @@ Properties › Kind, and the easing is kept. Animate documents' shape tweens now import as shape tweens. -* **Import to Stage** (File › Import, **Ctrl+R** as in Animate; `file.import`): SVG drawings +* **Import to Stage** (File › Import, **Ctrl+R**; `file.import`): SVG drawings come in as editable shapes on a new layer named after the file, at the playhead, centred and selected, as one undo step. Supported: paths and basic shapes, groups, `use` and symbols, transforms, `viewBox`, inline and attribute styles, opacity, and linear and radial diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 706d4678..eb79d6b2 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -340,7 +340,7 @@ fn set_filters(s: &mut Session, p: &Value) -> Result { } if set == 0 { return Err(EngineError::State(if graphics > 0 { - "filters apply to movie clip and button instances, as in Animate; set the symbol's Type to Movie Clip first".into() + "filters apply to movie clip and button instances; set the symbol's Type to Movie Clip first".into() } else { "select a movie clip or button instance".into() })); @@ -370,7 +370,7 @@ fn set_blend(s: &mut Session, p: &Value) -> Result { } if set == 0 { return Err(EngineError::State(if graphics > 0 { - "blending applies to movie clip and button instances, as in Animate; set the symbol's Type to Movie Clip first".into() + "blending applies to movie clip and button instances; set the symbol's Type to Movie Clip first".into() } else { "select a movie clip or button instance".into() })); diff --git a/crates/engine/src/cmds_frames.rs b/crates/engine/src/cmds_frames.rs index 513253b6..52ff22d6 100644 --- a/crates/engine/src/cmds_frames.rs +++ b/crates/engine/src/cmds_frames.rs @@ -1,7 +1,7 @@ //! Copy, cut and paste frames (Edit › Timeline). //! //! Design notes (principal engineer / senior designer review): -//! * Frames have their own clipboard, separate from copied artwork, as in Animate: copying +//! * Frames have their own clipboard, separate from copied artwork: copying //! frames never replaces copied shapes, and the reverse. //! * A copy is cut exactly at the selection edges by splitting a scratch copy of the layer with //! the same keyframe logic as F6, so a span that starts before the selection, or is diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 354e3c97..71a424dc 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -9,7 +9,7 @@ use anicraft_text::{Align, Fonts}; use serde_json::{Value, json}; use std::sync::Arc; -/// The text style new text gets: the last one used, as in Animate. +/// The text style new text gets: the last one used. #[derive(Clone, Debug, PartialEq)] pub struct TextStyle { pub font: String, diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index d97be25b..aecc4052 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -422,7 +422,7 @@ fn move_keyframes(s: &mut Session, p: &Value) -> Result { } /// Dragging keyframes onto other layers (`layer_by` rows down, negative = up): the frames are -/// lifted out of every source layer first (leaving blank keyframes, as in Animate), then +/// lifted out of every source layer first (leaving blank keyframes), then /// placed on the target layers, replacing what was there; frames after the landing range /// keep their content. Lifting everything before placing anything makes overlapping row /// ranges (dragging two rows down by one) come out right. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e8f2725a..0c54ee9c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -157,7 +157,7 @@ pub struct Session { dl_cache: RefCell>, /// Copied elements (and the symbols they use), outside the document so undo leaves it alone. pub clipboard: cmds_modify::Clipboard, - /// Copied frames (Copy Frames), separate from copied artwork as in Animate. + /// Copied frames (Copy Frames), separate from copied artwork. pub frame_clipboard: cmds_frames::FrameClipboard, } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 732a3dea..c5412685 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1611,7 +1611,7 @@ fn blend_modes_apply_to_movie_clips_and_survive_a_save() { run(&mut s, "layer.new", json!({})); run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000"})); run(&mut s, "modify.convert_to_symbol", json!({"name": "Red"})); - // A graphic can't blend, as in Animate; a movie clip can. + // A graphic can't blend; a movie clip can. assert!(s.execute("element.set_blend", &json!({"mode": "multiply"})).unwrap_err().to_string().contains("movie clip")); run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); assert!(s.execute("element.set_blend", &json!({"mode": "sparkle"})).is_err()); @@ -1662,7 +1662,7 @@ fn filters_render_on_movie_clips_clip_after_masks_and_save() { assert!(crate::cmds_file::frame_svg(&s.doc, 0).contains(" bool { + c.is_alphanumeric() || c == '_' +} + +fn banned_display(text: &str) -> bool { + if ALLOWED.contains(&text) { + return false; + } + BANNED.iter().any(|banned| { + text.match_indices(banned) + .any(|(at, _)| !text[..at].chars().next_back().is_some_and(is_word) && !text[at + banned.len()..].chars().next().is_some_and(is_word)) + }) +} + +// Read ordinary and raw Rust string literals, ignoring comments. No compiler dependency is +// needed, so this guard can also run by itself when a full application build is unavailable. +#[allow(clippy::cognitive_complexity)] // This small test-only lexer keeps raw-string/comment state together. +fn literals(source: &str) -> Vec { + let chars: Vec = source.chars().collect(); + let mut out = Vec::new(); + let mut at = 0; + let mut test_module = false; + let mut test_depth = 0_usize; + while at < chars.len() { + if chars.get(at..at + 12) == Some(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) { + at += 12; + let rest: String = chars[at..].iter().collect(); + if rest.trim_start().starts_with("mod ") { + test_module = true; + } + } else if chars.get(at..at + 2) == Some(&['/', '/']) { + while at < chars.len() && chars[at] != '\n' { + at += 1; + } + } else if chars.get(at..at + 2) == Some(&['/', '*']) { + at += 2; + let mut depth = 1; + while at < chars.len() && depth > 0 { + if chars.get(at..at + 2) == Some(&['/', '*']) { + depth += 1; + at += 2; + } else if chars.get(at..at + 2) == Some(&['*', '/']) { + depth -= 1; + at += 2; + } else { + at += 1; + } + } + } else if chars[at] == 'r' && matches!(chars.get(at + 1), Some('"' | '#')) { + let start = at; + at += 1; + while chars.get(at) == Some(&'#') { + at += 1; + } + let hashes = at - start - 1; + if chars.get(at) != Some(&'"') { + continue; + } + at += 1; + let begin = at; + while at < chars.len() { + if chars[at] == '"' && (1..=hashes).all(|n| chars.get(at + n) == Some(&'#')) { + break; + } + at += 1; + } + if !test_module { + out.push(chars[begin..at].iter().collect()); + } + at += 1 + hashes; + } else if chars[at] == '"' { + at += 1; + let mut text = String::new(); + while at < chars.len() { + let c = chars[at]; + at += 1; + if c == '"' { + break; + } + if c == '\\' && at < chars.len() { + text.push(chars[at]); + at += 1; + } else { + text.push(c); + } + } + if !test_module { + out.push(text); + } + } else if chars[at] == '\'' && chars.get(at + 2) == Some(&'\'') { + at += 3; // A character literal such as '"', not the start of a string. + } else { + if test_module { + match chars[at] { + '{' => test_depth += 1, + '}' => { + test_depth = test_depth.saturating_sub(1); + if test_depth == 0 { + test_module = false; + } + } + ';' if test_depth == 0 => test_module = false, + _ => {} + } + } + at += 1; + } + } + out +} + +fn check_tree(path: &Path, failures: &mut Vec) { + if path.is_dir() { + for entry in std::fs::read_dir(path).expect("source directory") { + let path = entry.expect("source entry").path(); + if path.file_name().is_some_and(|name| name == "tests") { + continue; + } + check_tree(&path, failures); + } + } else if path.extension().is_some_and(|ext| ext == "rs") { + let name = path.file_name().expect("source filename").to_string_lossy(); + if name == "tests.rs" || name.ends_with("_tests.rs") { + return; + } + let source = std::fs::read_to_string(path).expect("UTF-8 Rust source"); + // Skip only inline test modules, not later production following test-only imports. + for text in literals(&source) { + if banned_display(&text) { + failures.push(format!("{}: {text:?}", path.display())); + } + } + } +} + +#[test] +fn production_display_names_stay_neutral() { + let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut failures = Vec::new(); + for root in ROOTS { + let root = base.join(root); + assert!(root.exists(), "missing display source: {}", root.display()); + check_tree(&root, &mut failures); + } + assert!(failures.is_empty(), "Banned display names:\n{}", failures.join("\n")); +} + +#[test] +fn guard_distinguishes_labels_from_identifiers_and_comments() { + for name in BANNED { + assert!(banned_display(name), "{name}"); + } + for name in ALLOWED { + assert!(!banned_display(name), "{name}"); + } + assert!(!banned_display("filter.cameraRaw")); + assert!(!banned_display("tool.guidedUpright")); + assert!(!banned_display("insert.smartArt")); + assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]); + assert_eq!(literals("r#\"raw label\"#"), ["raw label"]); +} + +#[test] +fn guard_scans_production_after_test_only_items() { + let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"live label"#; } + "###; + assert_eq!(literals(source), ["live label"]); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]); +} diff --git a/docs/adr/0006-platforms-and-edit-latency.md b/docs/adr/0006-platforms-and-edit-latency.md index d74ade53..e4c6ed91 100644 --- a/docs/adr/0006-platforms-and-edit-latency.md +++ b/docs/adr/0006-platforms-and-edit-latency.md @@ -31,7 +31,7 @@ The policy is one shell with platform decisions isolated in one module, rather t | Concern | macOS | Windows | Linux / BSD | |---|---|---|---| | Shortcuts | `Ctrl` in the registry = **⌘**; labels use Apple order and glyphs (⇧⌘S), or "Shift+Cmd+S" when the font lacks them (checked at runtime) | Ctrl labels | Ctrl labels | -| Application menu | **AniCraft** menu: About, Settings… (⌘,), Quit (⌘Q) | File › Exit (Ctrl+Q), Edit › Preferences… (Ctrl+U, as in Animate) | as Windows | +| Application menu | **AniCraft** menu: About, Settings… (⌘,), Quit (⌘Q) | File › Exit (Ctrl+Q), Edit › Preferences… (Ctrl+U) | as Windows | | Window chrome | Unified title bar: full-size content view, title hidden, menu row inset for the traffic lights | Native frame | Native frame (X11 or Wayland chosen by winit; app id `anicraft` for window rules and docks) | | File dialogs | Native panels (rfd) | Common dialogs (rfd) | **XDG desktop portal** (rfd). A Preferences switch falls back to a built-in path field on desktops without a portal | | GPU backend | wgpu → Metal | wgpu → DX12/Vulkan | wgpu → Vulkan; **automatic retry with OpenGL** (glow) if wgpu cannot start (VMs, old GPUs, missing drivers); `--renderer gl` / `ANICRAFT_RENDERER` to force | diff --git a/docs/adr/0011-scenes.md b/docs/adr/0011-scenes.md index e6b34f09..4557956e 100644 --- a/docs/adr/0011-scenes.md +++ b/docs/adr/0011-scenes.md @@ -34,5 +34,5 @@ now the importer kept only the first. * Every editing command targets the open scene through `doc.timeline(s.scene)` and `doc.timeline_mut(s.scene)`, the only two ways in. -* Playing in the editor plays the open scene, as in Animate; *Test* is still per scene. A +* Playing in the editor plays the open scene; *Test* is still per scene. A whole-movie test player can come later without changing the model. diff --git a/docs/feature-names.md b/docs/feature-names.md new file mode 100644 index 00000000..248cd034 --- /dev/null +++ b/docs/feature-names.md @@ -0,0 +1,5 @@ +# Feature naming + +Own-feature messages describe which symbol types support filters and blending without the comparative phrase “as in Animate”. Matching comments and explanatory prose use the same direct descriptions. + +File-format interoperability references and required trademark/non-affiliation notices remain intact. Regression tests prevent the retired comparative phrase from returning to production display strings. No version, release workflow, release-stage setting or release hold is changed. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3e268bb8..d3155f9d 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; 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. No GPU path yet. | -| 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), 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, onion skin (±2 frames), looping playback. **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). No motion editor yet; **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) (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 frames, 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), 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, onion skin (±2 frames), looping playback. **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). No motion editor yet; **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), **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. No brush or merge drawing yet. | | 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. | | 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, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop), 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. No text, motion tweens or shape hints from XFL yet; **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; unsupported parts are reported. **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). | @@ -50,7 +50,7 @@ now Subselection, Pen and Pencil on a path-editing model in the engine (points a command and slot, so XFL edge data can map onto it). The Pen's interaction and the Pencil's curve fitter were borrowed from PhotoCraft and reviewed before porting (see `src/pathtools.rs` and `crates/geom/src/fit.rs` for what changed and why). PolyStar no longer -has a key (P is the Pen, as in Animate). +has a key (P is the Pen). Next, in order: diff --git a/src/panels.rs b/src/panels.rs index 72bb54e9..0ff34198 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -324,7 +324,7 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E live(app, "Alpha", "element.set_alpha", json!({"alpha": alpha / 100.0})); } }); - // Blending and filters, on movie clips and buttons as in Animate. + // Blending and filters, on movie clips and buttons. if let ElementKind::Symbol { symbol, filters, .. } = &e.kind && app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic) { @@ -739,7 +739,7 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L fn tool_props(app: &mut App, ui: &mut egui::Ui) { if app.tool == Tool::Text { - // What new text gets (the last style used, as in Animate). + // What new text gets (the last style used). let mut st = app.s.text_style.clone(); if text_style_rows(app, ui, &mut st, None).is_some() { app.s.text_style = st; diff --git a/src/stage.rs b/src/stage.rs index e790f554..5804c708 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -417,7 +417,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": false})); } } - // Double-clicking text with the Selection tool edits it, as in Animate. + // Double-clicking text with the Selection tool edits it. if app.tool == Tool::Select && resp.double_clicked() && let Some(p) = resp.interact_pointer_pos() From 66d8d6deec385dcb2a0b7add7be70f60680131eb Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 18:37:09 -0700 Subject: [PATCH 002/402] docs: reserve ADR 0045 for raw points (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..8ec5d830 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 | +| 0045 | m1/raw-points | Raw points: add, delete, smooth pairs, snapping while drawing, raw shapes inside symbols | From 2571a71cdac483fc1fa34c80c774dcce98f01817 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 18:45:48 -0700 Subject: [PATCH 003/402] feat(engine): add and delete raw anchors, smooth handle pairs, Make Smooth/Corner on raw points, snapping while drawing (M1) --- crates/engine/src/cmds_path.rs | 32 ++- crates/engine/src/cmds_raw.rs | 59 +++- crates/engine/src/cmds_rawpoints.rs | 246 +++++++++++++++++ crates/engine/src/cmds_rawsub.rs | 45 ++- crates/engine/src/lib.rs | 4 + crates/engine/src/rawpoints_tests.rs | 263 ++++++++++++++++++ crates/geom/src/edit.rs | 2 +- crates/geom/src/raw.rs | 396 +++++++++++++++++++++++++++ 8 files changed, 1039 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/cmds_rawpoints.rs create mode 100644 crates/engine/src/rawpoints_tests.rs diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs index fa223743..62e4ba18 100644 --- a/crates/engine/src/cmds_path.rs +++ b/crates/engine/src/cmds_path.rs @@ -9,7 +9,7 @@ use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param, style}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{Element, ElementId, ElementKind, Shape}; -use anicraft_geom::edit::{ANCHOR, polyline_path, simplify}; +use anicraft_geom::edit::{ANCHOR, C1, C2, polyline_path, simplify}; use anicraft_geom::{Affine, Path, PathCmd, Vec2, fit_curve}; use serde_json::{Value, json}; use std::collections::BTreeSet; @@ -28,7 +28,7 @@ pub fn specs() -> Vec { true, draw_freehand, ), - c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy}", true, move_points), + c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy, smooth?: bool} (a handle moved alone at a smooth anchor turns the other one with it, keeping its length, unless smooth is false: Alt breaks the pair)", true, move_points), c("path.add_point", "Add Anchor Point", "", None, "{id, x, y, slop?}", true, add_point), c("path.delete_points", "Delete Anchor Points", "", None, "{id, cmds: [..]}", true, delete_points), c("path.convert_point", "Convert Anchor Point", "", None, "{id, cmd, smooth: bool}", true, convert_point), @@ -149,6 +149,7 @@ fn move_points(s: &mut Session, p: &Value) -> Result { let slot = pair.get(1).and_then(Value::as_u64).filter(|s| *s <= 2).ok_or_else(bad)?; wanted.push((usize::try_from(cmd).unwrap_or(usize::MAX), slot as u8)); } + let smooth = opt_bool(p, "smooth")?.unwrap_or(true); let (sh, m) = shape_mut(s, p)?; let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?; let local = inv.apply_vector(d); @@ -168,15 +169,42 @@ fn move_points(s: &mut Session, p: &Value) -> Result { set.insert((cmd, slot)); } } + // The other handle of a smooth anchor whose handle moves alone (ADR 0045), as it was. + let partners: Vec<(usize, u8, Vec2, Vec2)> = if smooth { set.iter().filter_map(|&(cmd, slot)| partner(path, &set, cmd, slot)).collect() } else { Vec::new() }; for &(cmd, slot) in &set { if let Some(q) = path.point(cmd, slot) { path.set_point(cmd, slot, q + local); } } + for (cmd, slot, anchor, handle) in partners { + if let Some(k) = path.point(cmd, slot) { + path.set_point(cmd, slot, anicraft_geom::raw::turned_opposite(anchor, handle + local, k)); + } + } check_path(path)?; Ok(json!({"moved": set.len()})) } +/// For handle `(cmd, slot)` moving alone: the other handle of its anchor when the anchor is smooth +/// and that handle stays (`(cmd, slot)`), with the anchor and this handle where they are now. +fn partner(path: &Path, moving: &BTreeSet<(usize, u8)>, cmd: usize, slot: u8) -> Option<(usize, u8, Vec2, Vec2)> { + // Slot 2 is the in-handle of anchor `cmd`; slot 1 the out-handle of the anchor before. + let anchor = match slot { + C2 => path.canonical_anchor(cmd), + C1 => path.canonical_anchor(cmd.checked_sub(1)?), + _ => return None, + }; + let (i, o) = path.anchor_segments(anchor); + let other = if slot == C2 { (o?, C1) } else { (i?, C2) }; + if moving.contains(&other) || path.anchor_group(anchor).iter().any(|g| g.1 == ANCHOR && moving.contains(g)) { + return None; + } + let (a, h, k) = (path.point(anchor, ANCHOR)?, path.point(cmd, slot)?, path.point(other.0, other.1)?); + // A quadratic's control is both its ends' handle: turning it would bend the other end. + let cubic = |c: usize| matches!(path.cmds.get(c), Some(PathCmd::CubicTo(..))); + (cubic(other.0) && anicraft_geom::raw::smooth_at(a, h, k)).then_some((other.0, other.1, a, h)) +} + fn add_point(s: &mut Session, p: &Value) -> Result { let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 1000.0); diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index 7b122f1b..e5e16f90 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -158,7 +158,7 @@ fn hit(s: &mut Session, p: &Value) -> Result { } /// Makes the layer of what is at `at` (within `slop`) the active one, as a click does. -fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) { +pub(crate) fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) { if let Some((layer, _)) = s.hit_test(at, slop) && layer != s.layer { @@ -263,6 +263,38 @@ pub(crate) fn edit_edge(s: &mut Session, id: ElementId, cmd: usize, old: &Cubic, Ok(changed) } +/// Changes every copy of the edge `old` (stage space) into `new` (same ends): in every raw shape on +/// the editable keyframe, or only in `only` (a drawing object edits itself alone). Returns the +/// shapes that changed. +pub(crate) fn follow_edge(s: &mut Session, only: Option, old: &Cubic, new: &Cubic) -> Result> { + let area = new.iter().chain(old).fold(Rect::EMPTY, |mut r, q| { + r.include(*q); + r + }); + let kf = s.editable_keyframe()?; + let mut changed = Vec::new(); + for e in kf.elements.iter_mut() { + let take = match only { + Some(id) => e.id == id, + None => mergeable(e).is_some_and(|x| !reach(x, &e.transform).intersect(&area).is_empty()), + }; + if !take { + continue; + } + let (Some(inv), ElementKind::Shape(x)) = (e.transform.inverse(), &e.kind) else { continue }; + let mut edited = (*x.path).clone(); + if rawgeom::follow(&mut edited, &rawgeom::transform(old, &inv), &rawgeom::transform(new, &inv), SNAP / e.transform.mean_scale().max(1e-6)) == 0 { + continue; + } + check_extent(&edited)?; + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(edited); + } + changed.push(e.id); + } + Ok(changed) +} + // ----- moving shared points --------------------------------------------------------------------- fn points_param(p: &Value) -> Result>> { @@ -497,6 +529,31 @@ fn snap_point(els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, snap_to(&t, to, radius).map(|(q, k, _)| (q, k)) } +/// Where a point drawn at `p` snaps (the Line, Rectangle, Oval, PolyStar and Pen tools, ADR +/// 0045): the nearest anchor within `radius`, else the nearest point on a line or fill edge, of +/// what the stage shows near it. +pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo)> { + if !(radius > 0.0 && p.is_finite()) { + return None; + } + let dl = s.display_list(); + let mut t = Targets::default(); + for item in dl.items.iter() { + if t.points.len() + t.segs.len() > MAX_TARGETS { + break; + } + let pad = item.stroke.as_ref().map_or(0.0, |st| st.reach() * item.transform.mean_scale()); + if !item.path.bounds().transformed(&item.transform).inflate(pad + radius).contains(p) { + continue; + } + let mut path = (*item.path).clone(); + path.close_explicitly(); + t.points.extend(path.editable_anchors().into_iter().map(|(_, q)| item.transform.apply(q))); + t.segs.extend((0..path.cmds.len().min(MAX_TARGETS)).filter_map(|k| rawgeom::segment_cubic(&path, k)).map(|c| rawgeom::transform(&c, &item.transform))); + } + snap_to(&t, p, radius).map(|(q, k, _)| (q, k)) +} + /// After the selection moved: the extra move that snaps one of its anchors (the nearest to /// `from` when given, else whichever comes closest) onto an anchor or line of the shapes that /// did not move, within `radius`. diff --git a/crates/engine/src/cmds_rawpoints.rs b/crates/engine/src/cmds_rawpoints.rs new file mode 100644 index 00000000..b4b9bbbe --- /dev/null +++ b/crates/engine/src/cmds_rawpoints.rs @@ -0,0 +1,246 @@ +//! Adding and deleting the anchors of raw drawings, making them smooth or corners, and where a +//! point being drawn snaps (ADR 0045; issue #42 §1 and §3). +//! +//! A layer's merged drawing stores a shared point once in each shape that has it (ADR 0031), so +//! these work on positions, as the Subselection tool shows them (`raw.points`), and change every +//! copy alike: an added point is added to every shape with that edge; a deleted one is joined +//! across in every shape that has it, so the drawing stays connected. + +use crate::cmds_raw::{activate_layer_at, check_extent, follow_edge, positions_param, remerge_in_place, snap_drawn}; +use crate::merge::{mergeable, reach}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ElementId, ElementKind, Keyframe}; +use anicraft_geom::planar::SNAP; +use anicraft_geom::raw::{self as rawgeom, Seg, Sub}; +use anicraft_geom::{Path, Vec2}; +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( + "raw.add_point", + "Add Anchor Point", + "", + None, + "{x, y, slop?} adds an anchor on the raw line or fill edge at (x, y): every raw shape with that edge gets it, and the curve keeps its shape; returns where it is", + true, + add_point as crate::RunFn, + ), + c( + "raw.delete_points", + "Delete Anchor Points", + "", + None, + "{points: [[x, y], ..]} deletes the raw anchors at those positions (as raw.points lists them): every shape that has one is joined across it, so the drawing stays connected; a free end shortens its line; a shape left with nothing is removed; a point where three or more edges meet is kept", + true, + delete_points, + ), + c( + "raw.convert_points", + "Convert Anchor Points", + "", + None, + "{points: [[x, y], ..], smooth: bool} makes the raw anchors at those positions smooth (their handles in one line) or corners (handles drawn in), in every shape that has them", + true, + convert_points, + ), + c( + "draw.snap", + "Snap Point", + "", + None, + "{x, y, snap} where a point drawn at (x, y) snaps while Snap to Objects is on: the nearest anchor within `snap` stage units, else the nearest point on a line or fill edge; returns {x, y, snapped: {x, y, to} | null}", + false, + snap_cmd, + ), + ] +} + +/// Ends of segments this near a position are at it (the copies of a shared point lie within +/// `SNAP` of each other, ADR 0042). +const ENDS: f32 = 1.5 * SNAP; + +/// The raw shapes on `kf` near `at`: index, whether filled, and stage-space subpaths. +fn near(kf: &Keyframe, at: Vec2) -> Vec<(usize, bool, Vec)> { + kf.elements + .iter() + .enumerate() + .filter_map(|(i, e)| { + let sh = mergeable(e)?; + reach(sh, &e.transform).contains(at).then(|| (i, sh.fill.is_some(), rawgeom::subpaths(&sh.path.transformed(&e.transform)))) + }) + .collect() +} + +/// The distinct edges leaving `at` among `shapes`. +fn edges(shapes: &[(usize, bool, Vec)], at: Vec2) -> Vec { + rawgeom::distinct_edges(shapes.iter().flat_map(|(_, _, subs)| rawgeom::edges_at(subs, at, ENDS)), ENDS) +} + +fn points(p: &Value) -> Result> { + let pts = positions_param(p, "points")?; + if pts.is_empty() { + return Err(EngineError::Param("param 'points' is required: the positions of the anchors, as raw.points lists them".into())); + } + Ok(pts) +} + +// ----- adding ------------------------------------------------------------------------------------ + +fn add_point(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 100.0); + activate_layer_at(s, at, slop); + // The nearest raw line or fill edge. + let mut best: Option<(f32, Vec2)> = None; + for e in s.visible_elements() { + let Some(sh) = mergeable(&e) else { continue }; + if !reach(sh, &e.transform).inflate(slop).contains(at) { + continue; + } + let mut path = (*sh.path).clone(); + path.close_explicitly(); + let half = sh.stroke.as_ref().map_or(0.0, |st| st.width * 0.5 * e.transform.mean_scale()); + if let Some((cmd, t, d)) = path.nearest_segment(at, &e.transform) + && d <= slop + half + && best.is_none_or(|b| d < b.0) + && let Some(q) = path.segment_point(cmd, t) + { + best = Some((d, e.transform.apply(q))); + } + } + let (_, q) = best.ok_or_else(|| EngineError::State("no line or fill edge of a merged drawing there".into()))?; + let kf = s.editable_keyframe()?; + if near(kf, q).iter().any(|(_, _, subs)| subs.iter().flat_map(|sb| &sb.segs).any(|g| g.c[0].distance(q) <= 2.0 * SNAP || g.c[3].distance(q) <= 2.0 * SNAP)) { + return Err(EngineError::State("there is a point there already".into())); + } + let mut changed = Vec::new(); + for e in kf.elements.iter_mut() { + let Some(sh) = mergeable(e) else { continue }; + if !reach(sh, &e.transform).contains(q) { + continue; + } + let Some(inv) = e.transform.inverse() else { continue }; + let mut path = (*sh.path).clone(); + path.close_explicitly(); + let len = path.cmds.len(); + // Splits the segment through the point (de Casteljau: the curve is unchanged). + rawgeom::anchors_at(&mut path, inv.apply(q), SNAP / e.transform.mean_scale().max(1e-6)); + if path.cmds.len() == len { + continue; + } + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(path); + } + changed.push(e.id); + } + if changed.is_empty() { + return Err(EngineError::State("cannot add a point there".into())); + } + // Nothing moved, so nothing merges: the point stays until a merge finds it on a straight + // line that it no longer bends (issue #42 §1). + Ok(json!({"x": q.x, "y": q.y, "changed": changed.iter().map(|e| e.0).collect::>()})) +} + +// ----- deleting ---------------------------------------------------------------------------------- + +fn delete_points(s: &mut Session, p: &Value) -> Result { + let pts = points(p)?; + let (mut deleted, mut kept) = (0usize, 0usize); + let mut changed: Vec = Vec::new(); + let mut removed: Vec = Vec::new(); + for at in pts { + let kf = s.editable_keyframe()?; + let shapes = near(kf, at); + let edges = edges(&shapes, at); + let joined = match edges.as_slice() { + [] => continue, + [_] => None, + [a, b] => Some(rawgeom::join(a, b).ok_or_else(|| EngineError::Param("cannot join the lines across that point".into()))?), + _ => { + kept += 1; + continue; + } + }; + let mut gone: Vec = Vec::new(); + let mut any = false; + for (i, filled, mut subs) in shapes { + if !rawgeom::delete_anchor(&mut subs, at, &edges, joined.as_ref(), ENDS) { + continue; + } + rawgeom::tidy(&mut subs, filled); + let Some(e) = kf.elements.get_mut(i) else { continue }; + any = true; + if subs.is_empty() { + gone.push(e.id); + continue; + } + let Some(inv) = e.transform.inverse() else { continue }; + let path: Path = rawgeom::from_subpaths(&subs).transformed(&inv); + check_extent(&path)?; + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(path); + } + if !changed.contains(&e.id) { + changed.push(e.id); + } + } + kf.elements.retain(|e| !gone.contains(&e.id)); + changed.retain(|id| !gone.contains(id)); + removed.extend(gone); + deleted += usize::from(any); + } + if deleted == 0 { + return Err(EngineError::State(if kept > 0 { "a point where three or more lines meet can't be deleted; delete a line there instead".into() } else { "no point of a merged drawing there".into() })); + } + let here = s.layer; + s.selection.retain(|l, id| l != here || !removed.contains(&id)); + // Joined runs and fills merge again with what they touch, as after any edit. + remerge_in_place(s, &changed)?; + Ok(json!({"deleted": deleted, "kept": kept, "removed": removed.iter().map(|e| e.0).collect::>(), "selected": s.selection.id_list()})) +} + +// ----- smooth and corner ------------------------------------------------------------------------- + +fn convert_points(s: &mut Session, p: &Value) -> Result { + let pts = points(p)?; + let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?; + let mut changed: Vec = Vec::new(); + let mut converted = 0usize; + for at in pts { + let kf = s.editable_keyframe()?; + let edges = edges(&near(kf, at), at); + let edits: Vec<(Seg, Seg)> = if smooth { + match edges.as_slice() { + [a, b] => rawgeom::smooth_pair(a, b).map(|(na, nb)| vec![(*a, na), (*b, nb)]).unwrap_or_default(), + _ => Vec::new(), + } + } else { + edges.iter().filter_map(|e| rawgeom::corner(e).map(|n| (*e, n))).collect() + }; + converted += usize::from(!edits.is_empty()); + for (old, new) in edits { + for id in follow_edge(s, None, &old.c, &new.c)? { + if !changed.contains(&id) { + changed.push(id); + } + } + } + } + remerge_in_place(s, &changed)?; + Ok(json!({"converted": converted, "changed": changed.len()})) +} + +// ----- snapping while drawing -------------------------------------------------------------------- + +fn snap_cmd(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0)); + Ok(match snap_drawn(s, at, radius) { + Some((q, kind)) => json!({"x": q.x, "y": q.y, "snapped": {"x": q.x, "y": q.y, "to": kind.key()}}), + None => json!({"x": at.x, "y": at.y, "snapped": null}), + }) +} diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs index 7187da73..b6ba1e86 100644 --- a/crates/engine/src/cmds_rawsub.rs +++ b/crates/engine/src/cmds_rawsub.rs @@ -10,8 +10,8 @@ //! Which anchors are selected is view state, kept by the editor (as for drawing objects): the //! commands here report anchors and handles by stage position, and take positions back. -use crate::cmds_raw::{check_extent, edit_edge, remerge_in_place}; -use crate::merge::mergeable; +use crate::cmds_raw::{check_extent, edit_edge, follow_edge, remerge_in_place}; +use crate::merge::{mergeable, reach}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{Element, ElementId, ElementKind}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Move Handle", "", None, - "{id, cmd, slot: 1|2, dx, dy, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false)", + "{id, cmd, slot: 1|2, dx, dy, smooth?: bool, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false); at a smooth anchor the other handle turns to stay opposite, keeping its length (unless smooth is false: Alt breaks the pair)", true, move_handle, ), @@ -400,6 +400,32 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { // ----- handles ----------------------------------------------------------------------------------- +/// The other curve at the anchor of handle `slot` of `old` (stage space) when the anchor is smooth +/// there: the one edge leaving it whose handle lies opposite this one ([`rawgeom::smooth_at`]), in +/// any raw shape on the layer (or in `el` alone, a drawing object). Oriented from the anchor. +fn opposite_handle(els: &[Arc], el: &Element, raw: bool, old: &Cubic, slot: usize) -> Option { + let (a, h) = if slot == 1 { (old[0], old[1]) } else { (old[3], old[2]) }; + let dragged = rawgeom::Seg { c: if slot == 1 { *old } else { [old[3], old[2], old[1], old[0]] }, line: false }; + let tol = 1.5 * SNAP; + let mut subs = Vec::new(); + let from = |e: &Element| match &e.kind { + ElementKind::Shape(sh) => rawgeom::subpaths(&sh.path.transformed(&e.transform)), + _ => Vec::new(), + }; + if raw { + for e in els.iter().filter(|e| mergeable(e).is_some_and(|sh| reach(sh, &e.transform).contains(a))) { + subs.extend(from(e)); + } + } else { + subs = from(el); + } + let edges = rawgeom::distinct_edges(rawgeom::edges_at(&subs, a, tol), tol); + let mut found = edges.into_iter().filter(|f| !rawgeom::same_edge(f, &dragged, tol) && !f.line && rawgeom::smooth_at(a, h, f.c[1])); + let f = found.next()?; + // Two candidates: a junction, not a smooth pair. + found.next().is_none().then_some(f) +} + fn move_handle(s: &mut Session, p: &Value) -> Result { let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?; @@ -426,7 +452,18 @@ fn move_handle(s: &mut Session, p: &Value) -> Result { bounds.move_to(new[0]).cubic_to(new[1], new[2], new[3]); check_extent(&bounds)?; let raw = mergeable(el).is_some(); - let changed = edit_edge(s, id, cmd, &old, &new, raw)?; + // A smooth anchor's other handle turns with this one (ADR 0045). + let partner = if opt_bool(p, "smooth")?.unwrap_or(true) { opposite_handle(&els, el, raw, &old, slot).map(|f| (f, new[slot])) } else { None }; + let mut changed = edit_edge(s, id, cmd, &old, &new, raw)?; + if let Some((f, h)) = partner { + let a = f.c[0]; + let turned = rawgeom::Seg { c: [a, rawgeom::turned_opposite(a, h, f.c[1]), f.c[2], f.c[3]], line: false }; + for e in follow_edge(s, (!raw).then_some(id), &f.c, &turned.c)? { + if !changed.contains(&e) { + changed.push(e); + } + } + } if raw && merge_after { remerge_in_place(s, &changed)?; } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 753276fc..073dd9ab 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,6 +20,7 @@ mod cmds_paint; mod cmds_path; pub mod cmds_raw; pub mod cmds_rawsub; +mod cmds_rawpoints; mod cmds_recovery; mod cmds_script; pub mod cmds_plugin; @@ -116,6 +117,7 @@ pub fn commands() -> Vec { v.extend(cmds_path::specs()); v.extend(cmds_raw::specs()); v.extend(cmds_rawsub::specs()); + v.extend(cmds_rawpoints::specs()); v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); @@ -902,6 +904,8 @@ mod raw_tests; #[cfg(test)] mod rawsub_tests; #[cfg(test)] +mod rawpoints_tests; +#[cfg(test)] mod brush_tests; #[cfg(test)] mod web_tests; diff --git a/crates/engine/src/rawpoints_tests.rs b/crates/engine/src/rawpoints_tests.rs new file mode 100644 index 00000000..17c94bdf --- /dev/null +++ b/crates/engine/src/rawpoints_tests.rs @@ -0,0 +1,263 @@ +//! Adding and deleting raw anchors, smooth handle pairs, Make Smooth / Corner and snapping while +//! drawing (ADR 0045), through the commands. + +use crate::Session; +use anicraft_doc::{Element, ElementKind}; +use anicraft_geom::raw::{self as rawgeom}; +use anicraft_geom::walk::cubic_point; +use anicraft_geom::Vec2; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn raw_session() -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + s +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn is_fill(e: &Element) -> bool { + matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some()) +} + +fn all_ids(s: &Session) -> Vec { + raw(s).iter().map(|e| e.id).collect() +} + +fn anchors(s: &Session) -> Vec { + s.raw_points(&all_ids(s)).anchors +} + +fn has(points: &[Vec2], p: (f32, f32)) -> bool { + points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3) +} + +fn area(e: &Element) -> f32 { + let ElementKind::Shape(sh) = &e.kind else { return 0.0 }; + sh.path.flatten(&e.transform, 0.01).iter().map(|pl| pl.points.iter().zip(pl.points.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b)).sum::() * 0.5).sum::().abs() +} + +/// Every shape's anchors in stage space. +fn shape_anchors(e: &Element) -> Vec { + match &e.kind { + ElementKind::Shape(sh) => sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q)).collect(), + _ => Vec::new(), + } +} + +/// Largest distance from points of the curve `c` (stage space) to the shape's outline. +fn off_outline(e: &Element, c: &rawgeom::Cubic) -> f32 { + let ElementKind::Shape(sh) = &e.kind else { return f32::INFINITY }; + (0..=20).map(|i| sh.path.distance_to_edge(cubic_point(c, i as f32 / 20.0), &e.transform)).fold(0.0, f32::max) +} + +/// A raw arc (a fill under it and its outline): `M0 100 C0 0 200 0 200 100 Z`. +fn arc(s: &mut Session) -> rawgeom::Cubic { + run(s, "draw.path", json!({"d": "M0 100 C0 0 200 0 200 100 Z", "fill": "#ff0000", "stroke": "#000000"})); + run(s, "edit.deselect", json!({})); + [Vec2::new(0.0, 100.0), Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), Vec2::new(200.0, 100.0)] +} + +#[test] +fn an_added_point_is_shared_by_every_shape_on_the_edge_and_the_curve_keeps_its_shape() { + let mut s = raw_session(); + let c = arc(&mut s); + let before = anchors(&s).len(); + // How far the outlines are from the drawn curve (flattening): adding may not change it. + let was: Vec<(anicraft_doc::ElementId, f32)> = raw(&s).iter().map(|e| (e.id, off_outline(e, &c))).collect(); + let top = cubic_point(&c, 0.5); + let v = run(&mut s, "raw.add_point", json!({"x": top.x, "y": top.y + 1.0, "slop": 4})); + let at = Vec2::new(v["x"].as_f64().unwrap_or(0.0) as f32, v["y"].as_f64().unwrap_or(0.0) as f32); + assert!(at.distance(top) < 0.05, "on the curve: {at:?} vs {top:?}"); + assert_eq!(v["changed"].as_array().map(Vec::len), Some(2), "the fill and its outline: {v}"); + assert_eq!(anchors(&s).len(), before + 1, "listed once"); + let changed: Vec = v["changed"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + for e in raw(&s).into_iter().filter(|e| changed.contains(&e.id.0)) { + assert!(has(&shape_anchors(&e), (at.x, at.y)), "{} lacks the point", e.id.0); + // Analytic: the old curve still lies on every shape's outline, as closely as before. + let w = was.iter().find(|x| x.0 == e.id).map_or(0.0, |x| x.1); + assert!(off_outline(&e, &c) <= w + 1e-3 && w < 0.25, "the curve moved: {} (was {w})", off_outline(&e, &c)); + } + // One undo step; a second point at the same place is refused. + assert!(s.can_undo()); + assert!(s.execute("raw.add_point", &json!({"x": at.x, "y": at.y})).is_err()); + assert!(s.execute("raw.add_point", &json!({"x": 900, "y": 900})).is_err(), "nothing there"); + // Deleting it gives the curve back, in both shapes. + run(&mut s, "raw.delete_points", json!({"points": [[at.x, at.y]]})); + assert_eq!(anchors(&s).len(), before); + let on_curve: Vec> = raw(&s).into_iter().filter(|e| off_outline(e, &c) < 0.3).collect(); + assert_eq!(on_curve.len(), 2, "the fill and the arc's line still follow the curve"); +} + +#[test] +fn deleting_a_corner_rejoins_the_fill_and_its_outline() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + let steps = s.history_len(); + let v = run(&mut s, "raw.delete_points", json!({"points": [[0, 0]]})); + assert_eq!(v["deleted"], json!(1), "{v}"); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + // A triangle of half the area, outlined all round. + let fill: Vec> = raw(&s).into_iter().filter(|e| is_fill(e)).collect(); + assert_eq!(fill.len(), 1); + assert!((area(&fill[0]) - 4000.0).abs() < 1.0, "{}", area(&fill[0])); + let pts = anchors(&s); + assert_eq!(pts.len(), 3, "{pts:?}"); + assert!(!has(&pts, (0.0, 0.0))); + // Connectivity: every shape's anchors are shared with another shape. + let all = raw(&s); + for e in &all { + for p in shape_anchors(e) { + let n = all.iter().filter(|o| o.id != e.id && has(&shape_anchors(o), (p.x, p.y))).count(); + assert!(n >= 1, "{p:?} of {} is on no other shape", e.id.0); + } + } + // The diagonal is stroked: some outline runs from (0, 80) to (100, 0). + let diag = rawgeom::Seg::line(Vec2::new(0.0, 80.0), Vec2::new(100.0, 0.0)).c; + assert!(all.iter().filter(|e| !is_fill(e)).any(|e| off_outline(e, &diag) < 0.05), "no line on the new edge"); + s.undo().unwrap_or_default(); + assert_eq!(anchors(&s).len(), 4); +} + +#[test] +fn deleting_the_last_points_of_a_line_removes_it_and_junctions_stay() { + let mut s = raw_session(); + run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"})); + let v = run(&mut s, "raw.delete_points", json!({"points": [[100, 0]]})); + assert_eq!(v["removed"].as_array().map(Vec::len), Some(1), "a one-segment line goes: {v}"); + assert!(raw(&s).is_empty()); + assert!(s.selection.is_empty(), "nothing selected that is gone"); + // A T: the point where the stem stands on the bar joins three edges. + run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"})); + run(&mut s, "draw.line", json!({"x0": 50, "y0": 0, "x1": 50, "y1": 60, "stroke": "#000000"})); + let n = raw(&s).len(); + let e = s.execute("raw.delete_points", &json!({"points": [[50, 0]]})); + assert!(e.is_err_and(|e| e.to_string().contains("three or more"))); + assert_eq!(raw(&s).len(), n); + // The stem's free end shortens nothing else. + run(&mut s, "raw.delete_points", json!({"points": [[50, 60]]})); + assert!(!has(&anchors(&s), (50.0, 60.0))); + assert!(has(&anchors(&s), (0.0, 0.0)) && has(&anchors(&s), (100.0, 0.0))); + assert!(s.execute("raw.delete_points", &json!({"points": []})).is_err()); + assert!(s.execute("raw.delete_points", &json!({"points": [[500, 500]]})).is_err()); +} + +/// A raw S-curve stroke through (100, 0) with a smooth anchor there. +fn s_curve(s: &mut Session) { + run(s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null})); + run(s, "edit.deselect", json!({})); +} + +/// The handles at `a` listed by `raw.points`. +fn handles_at(s: &Session, a: Vec2) -> Vec { + s.raw_points(&all_ids(s)).handles.into_iter().filter(|h| h.anchor.distance(a) < 0.3).collect() +} + +#[test] +fn dragging_a_smooth_anchors_handle_keeps_the_other_opposite_and_alt_breaks_it() { + let mut s = raw_session(); + s_curve(&mut s); + let a = Vec2::new(100.0, 0.0); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2, "{hs:?}"); + let (h, k) = (hs[0], hs[1]); + let len_k = k.at.distance(a); + run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 0, "dy": 30})); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2); + let (moved, other) = if hs[0].at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5 { (hs[0], hs[1]) } else { (hs[1], hs[0]) }; + assert!(moved.at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5, "{hs:?}"); + // Colinear: on one line through the anchor, opposite, the other's length kept. + assert!(rawgeom::smooth_at(a, moved.at, other.at), "{moved:?} {other:?}"); + assert!((moved.at - a).normalized().cross((other.at - a).normalized()).abs() < 1e-3); + assert!((other.at.distance(a) - len_k).abs() < 0.3); + // Alt (smooth: false) moves the handle alone: a corner. + let before = other.at; + run(&mut s, "raw.move_handle", json!({"id": moved.id.0, "cmd": moved.cmd, "slot": moved.slot, "dx": 30, "dy": 0, "smooth": false})); + let hs = handles_at(&s, a); + assert!(hs.iter().any(|x| x.at.distance(before) < 0.3), "the other stays: {hs:?}"); + assert!(!rawgeom::smooth_at(a, hs[0].at, hs[1].at)); +} + +#[test] +fn make_corner_and_make_smooth_on_raw_anchors() { + let mut s = raw_session(); + s_curve(&mut s); + let a = Vec2::new(100.0, 0.0); + let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": false})); + assert_eq!(v["converted"], json!(1), "{v}"); + assert!(handles_at(&s, a).is_empty(), "the handles are drawn in"); + let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": true})); + assert_eq!(v["converted"], json!(1), "{v}"); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2, "{hs:?}"); + assert!(rawgeom::smooth_at(a, hs[0].at, hs[1].at)); + // Smooth on a fill's corner: the fill and both sides it has there follow. + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "raw.convert_points", json!({"points": [[300, 0]], "smooth": true})); + assert_eq!(v["converted"], json!(1)); + let fill = raw(&s).into_iter().find(|e| is_fill(e)).unwrap_or_else(|| panic!("a fill")); + assert!(area(&fill) > 8000.0, "the corner rounds out: {}", area(&fill)); + for e in raw(&s).iter().filter(|e| !is_fill(e) && e.transform.apply(Vec2::ZERO).x > 250.0) { + let ElementKind::Shape(sh) = &e.kind else { continue }; + let ElementKind::Shape(fs) = &fill.kind else { continue }; + for pl in sh.path.flatten(&e.transform, 0.05) { + for p in pl.points { + assert!(fs.path.distance_to_edge(p, &fill.transform) < 0.3, "{p:?} off the fill's edge"); + } + } + } +} + +#[test] +fn drawing_snaps_to_anchors_then_lines_while_snap_to_objects_is_on() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10})); + assert_eq!(v["snapped"]["to"], json!("point"), "{v}"); + assert_eq!((v["x"].as_f64(), v["y"].as_f64()), (Some(100.0), Some(0.0))); + let v = run(&mut s, "draw.snap", json!({"x": 50, "y": 84, "snap": 10})); + assert_eq!(v["snapped"]["to"], json!("line"), "{v}"); + assert!((v["y"].as_f64().unwrap_or(0.0) - 80.0).abs() < 1e-3 && (v["x"].as_f64().unwrap_or(0.0) - 50.0).abs() < 1e-3); + let v = run(&mut s, "draw.snap", json!({"x": 300, "y": 300, "snap": 10})); + assert!(v["snapped"].is_null()); + // Off, nothing snaps. + run(&mut s, "draw.snap_to_objects", json!({"on": false})); + let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10})); + assert!(v["snapped"].is_null() && v["x"] == json!(104.0)); + // A line drawn from a snapped point shares the rectangle's corner. + run(&mut s, "draw.snap_to_objects", json!({"on": true})); + let a = run(&mut s, "draw.snap", json!({"x": 98, "y": 78, "snap": 10})); + run(&mut s, "draw.line", json!({"x0": a["x"], "y0": a["y"], "x1": 200, "y1": 200, "stroke": "#000000"})); + assert!(has(&anchors(&s), (100.0, 80.0)) && anchors(&s).len() == 5, "{:?}", anchors(&s)); +} + +#[test] +fn an_object_paths_smooth_anchor_keeps_its_handles_opposite() { + let mut s = Session::new(anicraft_doc::Document::default()); + let v = run(&mut s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null})); + let id = v["element"].as_u64().unwrap_or(0); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + let p = sh.path.clone(); + // The in-handle of anchor 1 (C2 of command 1) moves; command 2's C1 turns with it. + run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 0, "dy": 25})); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + let (a, h, k) = (sh.path.point(1, 0), sh.path.point(1, 2), sh.path.point(2, 1)); + let (Some(a), Some(h), Some(k)) = (a, h, k) else { panic!("points") }; + assert!(rawgeom::smooth_at(a, h, k), "{a:?} {h:?} {k:?}"); + assert!((k.distance(a) - p.point(2, 1).map_or(0.0, |q| q.distance(a))).abs() < 1e-3, "length kept"); + run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 30, "dy": 0, "smooth": false})); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + assert_eq!(sh.path.point(2, 1), Some(k), "Alt moves the handle alone"); +} diff --git a/crates/geom/src/edit.rs b/crates/geom/src/edit.rs index 8f0c0a93..ea9ed0ec 100644 --- a/crates/geom/src/edit.rs +++ b/crates/geom/src/edit.rs @@ -383,7 +383,7 @@ fn leaving(cands: [Vec2; 3]) -> Option { } /// One cubic in place of `a` then `b` (see [`Path::merge_at`]). `None` for non-finite input. -fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> { +pub(crate) fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> { use crate::walk::cubic_point; const N: usize = 24; let (p0, p3) = (a[0], b[3]); diff --git a/crates/geom/src/raw.rs b/crates/geom/src/raw.rs index e5f66f93..a16acba5 100644 --- a/crates/geom/src/raw.rs +++ b/crates/geom/src/raw.rs @@ -180,6 +180,298 @@ pub fn anchors_at(path: &mut Path, p: Vec2, tol: f32) -> Vec { } } +// ----- points shared by several shapes (ADR 0045) ------------------------------------------------ + +/// One segment of a subpath: a cubic, and whether it is a straight line (kept a line when the path +/// is written back). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Seg { + pub c: Cubic, + pub line: bool, +} + +impl Seg { + pub fn line(a: Vec2, b: Vec2) -> Seg { + Seg { c: [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b], line: true } + } + /// The same segment run the other way. + pub fn reversed(&self) -> Seg { + Seg { c: [self.c[3], self.c[2], self.c[1], self.c[0]], line: self.line } + } +} + +/// A subpath as its segments, each starting where the one before ends. A closed one ends where +/// it starts. +#[derive(Clone, Debug, PartialEq)] +pub struct Sub { + pub segs: Vec, + pub closed: bool, +} + +/// `path` as subpaths (a `Close` that draws an edge back to the start gets that edge as a line; +/// a lone move is dropped). +pub fn subpaths(path: &Path) -> Vec { + let mut p = path.clone(); + p.close_explicitly(); + let mut out: Vec = Vec::new(); + let mut cur: Option = None; + for k in 0..p.cmds.len().min(MAX_CMDS) { + match p.cmds.get(k) { + Some(PathCmd::MoveTo(_)) => { + out.extend(cur.take().filter(|s| !s.segs.is_empty())); + cur = Some(Sub { segs: Vec::new(), closed: false }); + } + Some(PathCmd::Close) => { + if let Some(mut s) = cur.take().filter(|s| !s.segs.is_empty()) { + s.closed = true; + out.push(s); + } + } + Some(cmd) => { + if let Some(c) = segment_cubic(&p, k) { + let seg = Seg { c, line: matches!(cmd, PathCmd::LineTo(_)) }; + cur.get_or_insert_with(|| Sub { segs: Vec::new(), closed: false }).segs.push(seg); + } + } + None => break, + } + } + out.extend(cur.filter(|s| !s.segs.is_empty())); + out +} + +/// The path of `subs` (lines as lines, everything else as cubics). +pub fn from_subpaths(subs: &[Sub]) -> Path { + let mut p = Path::new(); + for s in subs { + let Some(first) = s.segs.first() else { continue }; + p.move_to(first.c[0]); + for g in &s.segs { + if g.line { + p.line_to(g.c[3]); + } else { + p.cubic_to(g.c[1], g.c[2], g.c[3]); + } + } + if s.closed { + p.close(); + } + } + p +} + +/// The segments of `subs` that start or end at `at` (within `tol`), each as the edge leaving +/// `at` (reversed when it ends there). +pub fn edges_at(subs: &[Sub], at: Vec2, tol: f32) -> Vec { + let mut out = Vec::new(); + for s in subs { + for g in &s.segs { + if g.c[0].distance(at) <= tol { + out.push(*g); + } + if g.c[3].distance(at) <= tol { + out.push(g.reversed()); + } + } + } + out +} + +/// Whether two edges leaving one anchor are the same edge: their far ends and points along them +/// within `tol`. +pub fn same_edge(a: &Seg, b: &Seg, tol: f32) -> bool { + a.c[3].distance(b.c[3]) <= tol && [0.25f32, 0.5, 0.75].iter().all(|&t| cubic_point(&a.c, t).distance(cubic_point(&b.c, t)) <= tol * 2.0) +} + +/// The edges among `edges` that are distinct ([`same_edge`]), in order. +pub fn distinct_edges(edges: impl IntoIterator, tol: f32) -> Vec { + let mut out: Vec = Vec::new(); + for e in edges { + if !out.iter().any(|x| same_edge(x, &e, tol)) { + out.push(e); + } + } + out +} + +/// The one edge in place of the edges `a` and `b` that leave an anchor: from `a`'s far end to +/// `b`'s. Two lines make a line; anything else the cubic that fits both best, keeping the +/// directions they leave their far ends in ([`Path::merge_at`]'s fit). +pub fn join(a: &Seg, b: &Seg) -> Option { + if a.line && b.line { + return Some(Seg::line(a.c[3], b.c[3])); + } + let c = crate::edit::merge_cubics(a.reversed().c, b.c)?; + Some(Seg { c, line: false }) +} + +/// The edges `a` and `b` that leave one anchor, made smooth there: their handles at the anchor on +/// one line, along the direction from `a`'s far end to `b`'s, each a third of its edge's chord +/// long ([`Path::make_smooth`]). `None` when the far ends coincide. +pub fn smooth_pair(a: &Seg, b: &Seg) -> Option<(Seg, Seg)> { + let at = a.c[0]; + let dir = (b.c[3] - a.c[3]).normalized(); + if dir == Vec2::ZERO { + return None; + } + let ha = at - dir * (at.distance(a.c[3]) / 3.0); + let hb = at + dir * (at.distance(b.c[3]) / 3.0); + let (na, nb) = (Seg { c: [at, ha, a.c[2], a.c[3]], line: false }, Seg { c: [at, hb, b.c[2], b.c[3]], line: false }); + (na.c.iter().chain(&nb.c).all(|p| p.is_finite())).then_some((na, nb)) +} + +/// `e` (leaving an anchor) with its handle at the anchor drawn in onto it: a corner there. `None` +/// when it has none to draw in (a line, or a handle already on the anchor). +pub fn corner(e: &Seg) -> Option { + (!e.line && e.c[1].distance(e.c[0]) > 1e-4).then_some(Seg { c: [e.c[0], e.c[0], e.c[2], e.c[3]], line: false }) +} + +/// Handles at one anchor lying on one line, on opposite sides, within this angle's sine (3°): a +/// smooth anchor. +const SMOOTH_SIN: f32 = 0.052; + +/// Whether the handles `h` and `k` of the anchor `a` make it smooth: both off the anchor, on one +/// line through it, on opposite sides. +pub fn smooth_at(a: Vec2, h: Vec2, k: Vec2) -> bool { + let (u, v) = (h - a, k - a); + let (lu, lv) = (u.length(), v.length()); + lu > 1e-4 && lv > 1e-4 && u.dot(v) < 0.0 && (u.cross(v) / (lu * lv)).abs() <= SMOOTH_SIN +} + +/// `k` turned about the anchor `a` so it lies opposite `h`, keeping its length (the other handle +/// of a smooth anchor while `h` is dragged). `k` itself when `h` is on the anchor. +pub fn turned_opposite(a: Vec2, h: Vec2, k: Vec2) -> Vec2 { + let dir = (h - a).normalized(); + if dir == Vec2::ZERO { + return k; + } + a - dir * a.distance(k) +} + +/// Deletes the anchor at `at` (within `tol`) from `subs`, where the drawing has the distinct +/// edges `edges` leaving it. +/// +/// * Two edges: every copy of either becomes `joined` (the edge from the first's far end to the +/// second's, see [`join`]). A run through the anchor takes it once in place of both; a line +/// ending there now runs along the whole new edge, so the drawing stays connected. +/// * One edge (the free end of lines): the segment there goes. +/// +/// Returns whether anything changed. Subpaths may be left empty or flat: see [`tidy`]. +pub fn delete_anchor(subs: &mut [Sub], at: Vec2, edges: &[Seg], joined: Option<&Seg>, tol: f32) -> bool { + let which = |e: &Seg| edges.iter().position(|x| same_edge(x, e, tol)); + let toward = |from: usize| -> Option { + // The new edge leaving the far end of edge `from` (towards the other edge's far end). + let j = joined?; + Some(if from == 0 { *j } else { j.reversed() }) + }; + let mut changed = false; + for s in subs.iter_mut() { + // Each pass takes one vertex at `at`; bounded by the segments there are. + for _ in 0..=s.segs.len() { + let Some(step) = vertex_at(s, at, tol) else { break }; + let done = match step { + Vertex::Through(v) => { + // in: segs[v - 1] arrives, out: segs[v] leaves (v ≥ 1 after rotation). + let (Some(inn), Some(out)) = (s.segs.get(v - 1).copied(), s.segs.get(v).copied()) else { break }; + match (which(&inn.reversed()), which(&out), edges.len()) { + (Some(a), Some(b), 2) if a != b => match toward(a) { + Some(n) => { + s.segs.splice(v - 1..=v, [n]); + true + } + None => false, + }, + _ => false, + } + } + Vertex::Start => match (s.segs.first().and_then(&which), edges.len()) { + // The new first segment ends where the old one did. + (Some(a), 2) => match (toward(1 - a), s.segs.first_mut()) { + (Some(n), Some(first)) => { + *first = n; + true + } + _ => false, + }, + (Some(_), 1) => { + s.segs.remove(0); + true + } + _ => false, + }, + Vertex::End => { + match (s.segs.last().and_then(|g| which(&g.reversed())), edges.len()) { + (Some(a), 2) => match (toward(a), s.segs.last_mut()) { + (Some(n), Some(last)) => { + *last = n; + true + } + _ => false, + }, + (Some(_), 1) => { + s.segs.pop(); + true + } + _ => false, + } + } + }; + if !done { + break; + } + changed = true; + } + } + changed +} + +/// Where a subpath has a vertex at a point. +enum Vertex { + /// Between segments `v - 1` and `v` (a closed subpath is turned so `v ≥ 1`). + Through(usize), + /// An open subpath's start or end. + Start, + End, +} + +fn vertex_at(s: &mut Sub, at: Vec2, tol: f32) -> Option { + let n = s.segs.len(); + if n == 0 { + return None; + } + if s.closed { + let v = s.segs.iter().position(|g| g.c[0].distance(at) <= tol)?; + // Turn the loop so the vertex is not at the seam. + let turn = if v == 0 { n - 1 } else { 0 }; + s.segs.rotate_left(turn); + return Some(Vertex::Through(if v == 0 { 1 } else { v })); + } + if s.segs.first().is_some_and(|g| g.c[0].distance(at) <= tol) { + return Some(Vertex::Start); + } + if s.segs.last().is_some_and(|g| g.c[3].distance(at) <= tol) { + return Some(Vertex::End); + } + (1..n).find(|&v| s.segs.get(v).is_some_and(|g| g.c[0].distance(at) <= tol)).map(Vertex::Through) +} + +/// Drops the subpaths an edit left with nothing to show: no segments, no length, or (when +/// `filled`) a closed outline with no area. +pub fn tidy(subs: &mut Vec, filled: bool) { + subs.retain(|s| { + let pts: Vec = s.segs.iter().flat_map(|g| (0..8).map(move |i| cubic_point(&g.c, i as f32 / 8.0))).chain(s.segs.last().map(|g| g.c[3])).collect(); + let length: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.distance(*b))).sum(); + if s.segs.is_empty() || length <= 1e-3 { + return false; + } + if filled && s.closed { + let area: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.cross(*b))).sum::() * 0.5; + return area.abs() > 1e-3; + } + true + }); +} + #[cfg(test)] mod tests { use super::*; @@ -235,6 +527,110 @@ mod tests { assert!(anchors_at(&mut p, Vec2::new(40.0, 5.0), 0.2).is_empty()); } + fn v(x: f32, y: f32) -> Vec2 { + Vec2::new(x, y) + } + + #[test] + fn subpaths_round_trip() { + let mut p = Path::rect(0.0, 0.0, 10.0, 10.0); + p.move_to(v(20.0, 0.0)).cubic_to(v(20.0, 5.0), v(25.0, 10.0), v(30.0, 10.0)); + let subs = subpaths(&p); + assert_eq!(subs.len(), 2); + assert!(subs[0].closed && subs[0].segs.len() == 4 && subs[0].segs.iter().all(|g| g.line), "the closing edge is written out: {:?}", subs[0]); + assert!(!subs[1].closed && !subs[1].segs[0].line); + let back = subpaths(&from_subpaths(&subs)); + assert_eq!(back, subs); + } + + /// A raw rectangle as merge drawing stores it: the fill and four sides, each its own path. + fn outlined_rect() -> Vec> { + let (a, b, c, d) = (v(0.0, 0.0), v(100.0, 0.0), v(100.0, 80.0), v(0.0, 80.0)); + // The fill starts at the corner deleted below, to cover the seam. + let fill = vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, d), Seg::line(d, a)], closed: true }]; + let side = |p, q| vec![Sub { segs: vec![Seg::line(p, q)], closed: false }]; + vec![fill, side(a, b), side(b, c), side(c, d), side(d, a)] + } + + fn delete(shapes: &mut [Vec], at: Vec2) -> usize { + let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, at, 0.2)), 0.2); + let joined = if edges.len() == 2 { join(&edges[0], &edges[1]) } else { None }; + shapes.iter_mut().map(|s| delete_anchor(s, at, &edges, joined.as_ref(), 0.2)).filter(|c| *c).count() + } + + #[test] + fn deleting_a_corner_keeps_the_drawing_connected() { + let mut shapes = outlined_rect(); + let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, v(0.0, 0.0), 0.2)), 0.2); + assert_eq!(edges.len(), 2, "two edges meet at a corner, each in the fill and a side"); + assert_eq!(delete(&mut shapes, v(0.0, 0.0)), 3, "the fill and both sides there"); + // The fill is a triangle now, cut along the diagonal from (0, 80) to (100, 0). + let fill = &shapes[0][0]; + assert!(fill.closed && fill.segs.len() == 3 && fill.segs.iter().all(|g| g.line), "{fill:?}"); + assert!(fill.segs.iter().all(|g| g.c[0].distance(v(0.0, 0.0)) > 1.0)); + // Both sides that ended there now run along the diagonal: every anchor is shared. + let diag = Seg::line(v(0.0, 80.0), v(100.0, 0.0)); + for s in [&shapes[1], &shapes[4]] { + let g = s[0].segs[0]; + assert!(same_edge(&g, &diag, 0.01) || same_edge(&g.reversed(), &diag, 0.01), "{g:?}"); + } + let anchors: Vec = shapes.iter().flatten().flat_map(|s| s.segs.iter().flat_map(|g| [g.c[0], g.c[3]])).collect(); + for p in &anchors { + assert!(anchors.iter().filter(|q| q.distance(*p) < 1e-3).count() >= 2, "{p:?} is on one shape only"); + } + } + + #[test] + fn deleting_a_point_that_splitting_added_gives_the_curve_back() { + let arc = Seg { c: [v(0.0, 0.0), v(0.0, -60.0), v(100.0, -60.0), v(100.0, 0.0)], line: false }; + let (a, b) = (sub(&arc.c, 0.0, 0.35), sub(&arc.c, 0.35, 1.0)); + let at = a[3]; + // A fill under the arc and the arc's own stroke, both with the point. + let fill = vec![Sub { segs: vec![Seg { c: a, line: false }, Seg { c: b, line: false }, Seg::line(v(100.0, 0.0), v(0.0, 0.0))], closed: true }]; + let stroke = vec![Sub { segs: vec![Seg { c: b, line: false }.reversed(), Seg { c: a, line: false }.reversed()], closed: false }]; + let mut shapes = vec![fill, stroke]; + assert_eq!(delete(&mut shapes, at), 2); + let (f, s) = (shapes[0][0].segs[0], shapes[1][0].segs[0]); + assert_eq!((shapes[0][0].segs.len(), shapes[1][0].segs.len()), (2, 1)); + for t in [0.1f32, 0.3, 0.5, 0.7, 0.9] { + assert!(nearest(&f.c, cubic_point(&arc.c, t)).1 < 0.05, "fill off the old curve at {t}"); + } + assert!(same_edge(&f, &s.reversed(), 1e-3), "the fill and the stroke keep one edge"); + } + + #[test] + fn deleting_a_free_end_shortens_the_line_and_its_last_point_removes_it() { + let mut shapes = vec![vec![Sub { segs: vec![Seg::line(v(0.0, 0.0), v(50.0, 0.0)), Seg::line(v(50.0, 0.0), v(50.0, 50.0))], closed: false }]]; + assert_eq!(delete(&mut shapes, v(50.0, 50.0)), 1); + assert_eq!(shapes[0][0].segs.len(), 1); + assert_eq!(delete(&mut shapes, v(50.0, 0.0)), 1); + tidy(&mut shapes[0], false); + assert!(shapes[0].is_empty()); + // A triangle's fill losing a corner has no area left. + let tri = |a, b, c| vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, a)], closed: true }]; + let mut t = vec![tri(v(0.0, 0.0), v(10.0, 0.0), v(5.0, 9.0))]; + assert_eq!(delete(&mut t, v(5.0, 9.0)), 1); + tidy(&mut t[0], true); + assert!(t[0].is_empty(), "{:?}", t[0]); + } + + #[test] + fn smooth_and_corner_handles() { + let (a, b) = (Seg::line(v(0.0, 0.0), v(-30.0, 10.0)), Seg::line(v(0.0, 0.0), v(40.0, 10.0))); + let Some((sa, sb)) = smooth_pair(&a, &b) else { panic!("no pair") }; + assert!(smooth_at(v(0.0, 0.0), sa.c[1], sb.c[1]), "{sa:?} {sb:?}"); + assert!((sa.c[1].distance(v(0.0, 0.0)) - a.c[3].length() / 3.0).abs() < 1e-3); + assert_eq!((sa.c[3], sb.c[3]), (a.c[3], b.c[3]), "far ends stay"); + let Some(c) = corner(&sa) else { panic!("a curve has a handle") }; + assert_eq!(c.c[1], c.c[0]); + assert!(corner(&a).is_none() && corner(&c).is_none(), "nothing to draw in"); + // Dragging one handle of a smooth anchor turns the other with it, keeping its length. + let k = turned_opposite(v(0.0, 0.0), v(0.0, 10.0), v(20.0, 0.0)); + assert!(k.distance(v(0.0, -20.0)) < 1e-4, "{k:?}"); + assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0)), "a corner"); + assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(20.0, 0.1)), "same side"); + } + #[test] fn nearest_finds_the_closest_point_on_a_curve() { let c = [Vec2::new(0.0, 0.0), Vec2::new(0.0, 50.0), Vec2::new(100.0, 50.0), Vec2::new(100.0, 0.0)]; From 96229c97bab3e30ec8dd1bacf730da2dfc7708f5 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 18:50:08 -0700 Subject: [PATCH 004/402] feat(stage): raw points in the editor: Delete, Make Smooth/Corner, adding with the Pen and Subselection, Alt breaks handle pairs, shape tools snap, Ctrl+Shift+/ (M1) --- crates/engine/src/cmds_draw.rs | 2 +- crates/engine/src/lib.rs | 3 ++ src/app.rs | 4 +- src/pathtools.rs | 95 +++++++++++++++++++++++++++++----- src/stage.rs | 45 +++++++++++++--- 5 files changed, 128 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 79a902f1..7186276a 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -15,7 +15,7 @@ pub fn specs() -> Vec { c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, object?}", true, draw_star), c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line), c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing), - c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", None, "{on?: bool} (default: toggle) dragged points and selections snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point and raw.move_handle do nothing while it is off)", false, snap_to_objects), + c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", Some("Ctrl+Shift+/"), "{on?: bool} (default: toggle) dragged points and selections, and the points the Line, Rectangle, Oval, PolyStar and Pen tools draw, snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point, raw.move_handle and draw.snap do nothing while it is off)", false, snap_to_objects), c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all), c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| { s.selection.clear(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 073dd9ab..daec66e3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -136,6 +136,9 @@ pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[ ("Backspace", "edit.delete"), ("Shift+,", "timeline.first_frame"), ("Shift+.", "timeline.last_frame"), + // Snap to Objects is Animate's Ctrl+Shift+/ (ADR 0045). Where / and ? share a key (US, UK), + // the key arrives as ?, so that spelling is bound too. + ("Ctrl+Shift+?", "draw.snap_to_objects"), ]; pub fn find_command(id: &str) -> Option { diff --git a/src/app.rs b/src/app.rs index 77f89c9d..b4674d72 100644 --- a/src/app.rs +++ b/src/app.rs @@ -121,8 +121,8 @@ impl Tool { pub fn hint(self) -> &'static str { match self { Tool::Select => tr_noop!("Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection."), - Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. On drawing objects, double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."), - Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point. Alt-click a selected shape or a motion path to add a point to it."), + Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it; a smooth point's handles stay in line, Alt moves one alone); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. Double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."), + Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point. Alt-click a selected shape, a merged drawing's line or a motion path to add a point to it. Points snap to points and lines while Snap to Objects is on."), Tool::Text => tr_noop!("Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too."), Tool::Pencil => tr_noop!("Drag to draw freehand. The options bar sets Smooth, Straighten or Ink."), Tool::Brush => tr_noop!("Drag to paint filled shapes in the fill colour (a click paints a dab). [ and ] change the size; the options set the shape, smoothing and paint mode."), diff --git a/src/pathtools.rs b/src/pathtools.rs index 7cfd838e..35f4d934 100644 --- a/src/pathtools.rs +++ b/src/pathtools.rs @@ -106,6 +106,10 @@ pub fn pen_input(app: &mut App, ui: &egui::Ui, resp: &egui::Response, xf: Xf) { commit_pen(app, false); return; } + // A new knot snaps to points, lines and fill edges (ADR 0045); handles never do. + let p = crate::stage::snap_draw(app, pos2(p.x, p.y), xf.zoom); + let p = Vec2::new(p.x, p.y); + let Some(pen) = app.pen.as_mut() else { return }; pen.knots.push([p; 3]); pen.dragging = true; return; @@ -293,13 +297,14 @@ pub fn subselect_drag_start(app: &mut App, press: Pos2, shift: bool, xf: Xf) -> Drag::PointMarquee { start: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) } } -/// Moves the selected points by a stage-space delta (inside the open gesture). -pub fn move_points(app: &mut App, d: Vec2) { +/// Moves the selected points by a stage-space delta (inside the open gesture). A handle moved +/// alone at a smooth anchor turns the other one with it unless `smooth` is false (Alt). +pub fn move_points(app: &mut App, d: Vec2, smooth: bool) { let mut ids: Vec = app.points.iter().map(|p| p.0).collect(); ids.dedup(); for id in ids { let pts: Vec<[u64; 2]> = app.points.iter().filter(|p| p.0 == id).map(|p| [p.1 as u64, u64::from(p.2)]).collect(); - app.run("path.move_points", json!({"id": id.0, "points": pts, "dx": d.x, "dy": d.y})); + app.run("path.move_points", json!({"id": id.0, "points": pts, "dx": d.x, "dy": d.y, "smooth": smooth})); } } @@ -372,7 +377,25 @@ fn add_point_on_selected(app: &mut App, at: Pos2, xf: Xf) -> bool { return true; } } - false + raw_add_point(app, at, xf) +} + +/// Adds a point on the raw line or fill edge at screen point `at` (ADR 0045): every raw shape with +/// that edge gets it, and it shows selected with everything connected to it. False when there +/// is no raw edge there. +fn raw_add_point(app: &mut App, at: Pos2, xf: Xf) -> bool { + let sp = xf.to_stage(at); + let Ok(v) = app.s.execute("raw.add_point", &json!({"x": sp.x, "y": sp.y, "slop": PICK * xf.unit()})) else { return false }; + let q = Vec2::new(v["x"].as_f64().unwrap_or(0.0) as f32, v["y"].as_f64().unwrap_or(0.0) as f32); + // Show the shapes on it, as a Subselection click there would. + if let Some(r) = app.run("raw.subselect", json!({"x": q.x, "y": q.y, "slop": 2.0 * xf.unit()})) { + app.raw_ends = positions(&r["ends"]); + } + app.points.clear(); + app.motion_anchors.clear(); + app.raw_anchors = vec![q]; + app.status_ok(tr!("Added a point. {undo} to undo.", undo = app.undo_key())); + true } /// Anchors in the point selection, grouped per element. @@ -397,6 +420,27 @@ pub fn delete_points(app: &mut App) { app.points.clear(); } +/// Deletes the selected raw anchors (ADR 0045): the shapes that share each are joined across it. +fn raw_delete(app: &mut App) { + let pts: Vec<[f32; 2]> = app.raw_anchors.iter().map(|q| [q.x, q.y]).collect(); + let Some(v) = app.run("raw.delete_points", json!({"points": pts})) else { return }; + app.raw_anchors.clear(); + app.raw_ends.clear(); + let (n, kept) = (v["deleted"].as_u64().unwrap_or(0) as usize, v["kept"].as_u64().unwrap_or(0) as usize); + let undo = app.undo_key(); + app.status_ok(if kept > 0 { + trn!("Deleted {n} point; kept {kept} where three or more lines meet. {undo} to undo.", "Deleted {n} points; kept {kept} where three or more lines meet. {undo} to undo.", n, kept = kept, undo = undo) + } else { + trn!("Deleted {n} point. {undo} to undo.", "Deleted {n} points. {undo} to undo.", n, undo = undo) + }); +} + +/// Makes the selected raw anchors smooth or corners, in every shape that has them. +fn raw_convert(app: &mut App, smooth: bool) { + let pts: Vec<[f32; 2]> = app.raw_anchors.iter().map(|q| [q.x, q.y]).collect(); + app.run("raw.convert_points", json!({"points": pts, "smooth": smooth})); +} + pub fn convert_points(app: &mut App, smooth: bool) { for (id, cmds) in selected_anchors(app) { for cmd in cmds { @@ -405,22 +449,25 @@ pub fn convert_points(app: &mut App, smooth: bool) { } } -/// Right-click menu for selected points; false when no anchor is selected. +/// Right-click menu for selected points (of drawing objects, or raw anchors, ADR 0045); false +/// when no anchor is selected. pub fn point_menu(app: &mut App, ui: &mut egui::Ui) -> bool { - if app.tool != Tool::Subselect || selected_anchors(app).is_empty() { + let raw = !app.raw_anchors.is_empty(); + if app.tool != Tool::Subselect || (!raw && selected_anchors(app).is_empty()) { return false; } if ui.button(tr!("Make Smooth")).clicked() { - convert_points(app, true); + if raw { raw_convert(app, true) } else { convert_points(app, true) } ui.close(); } if ui.button(tr!("Make Corner")).clicked() { - convert_points(app, false); + if raw { raw_convert(app, false) } else { convert_points(app, false) } ui.close(); } ui.separator(); - if ui.button(tr!("Delete Point")).clicked() { - delete_points(app); + let label = if raw { trn!("Delete Point", "Delete Points", app.raw_anchors.len()) } else { tr!("Delete Point").to_string() }; + if ui.button(label).clicked() { + if raw { raw_delete(app) } else { delete_points(app) } ui.close(); } true @@ -668,7 +715,7 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) { } if app.tool == Tool::Subselect && !app.raw_anchors.is_empty() { if take(Key::Delete) || take(Key::Backspace) { - app.status_err(tr!("Points of merged drawings can't be deleted yet. Select the parts with the Selection tool (V) and delete them.")); + raw_delete(app); } if take(Key::Escape) { app.raw_anchors.clear(); @@ -701,7 +748,7 @@ fn move_points_step(app: &mut App, d: Vec2) { if own { app.s.begin_gesture(tr_noop!("Move Points")); } - move_points(app, d); + move_points(app, d, true); if own { app.s.end_gesture(); } @@ -866,6 +913,30 @@ mod tests { assert!(app.s.can_undo()); } + #[test] + fn delete_removes_selected_raw_anchors_and_a_double_click_adds_one() { + let (mut app, ctx) = app_and_ctx(); + subselect_click(&mut app, pos2(50.0, 0.0), false, XF); + subselect_click(&mut app, pos2(0.0, 0.0), false, XF); + assert_eq!(app.raw_anchors.len(), 1); + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::Key { key: Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + let mut out = ctx.run_ui(input, |ui| consume_keys(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.raw_anchors.is_empty()); + let pts = raw_shown(&app); + assert_eq!(pts.anchors.len(), 3, "a triangle: {:?}", pts.anchors); + assert!(!has(&pts.anchors, 0.0, 0.0)); + // A double-click on the right side adds a point there, shared and selected. + subselect_double_click(&mut app, pos2(101.0, 40.0), XF); + assert!(has(&app.raw_anchors, 100.0, 40.0), "{:?}", app.raw_anchors); + assert_eq!(raw_shown(&app).anchors.len(), 4); + // Make Smooth reaches the engine for raw anchors: the corner at (100, 80) rounds. + app.raw_anchors = vec![Vec2::new(100.0, 80.0)]; + raw_convert(&mut app, true); + assert!(!raw_shown(&app).handles.is_empty(), "smooth: handles appear"); + } + #[test] fn a_press_takes_an_anchor_or_moves_everything_connected() { let (mut app, _) = app_and_ctx(); diff --git a/src/stage.rs b/src/stage.rs index c0d81ba7..162725ca 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -424,7 +424,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // With the Faucet on, the eraser deletes on a click instead. Tool::Eraser if !app.eraser.faucet => crate::erasertool::start(app, to_v(sp)), Tool::Pen | Tool::Text | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper | Tool::Eraser => Drag::None, - Tool::Rect | Tool::Oval | Tool::Star | Tool::Line => Drag::Shape { start: sp, cur: sp }, + // The press snaps to points, lines and fill edges (ADR 0045). + Tool::Rect | Tool::Oval | Tool::Star | Tool::Line => { + let start = snap_draw(app, sp, zoom); + Drag::Shape { start, cur: start } + } Tool::Camera => crate::camera_tool::drag_start(app, &cam_geo, press), Tool::Hand => Drag::Pan, Tool::Zoom => Drag::None, @@ -449,7 +453,16 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.drag = d; } if resp.dragged() { - let cur = resp.interact_pointer_pos().map(to_stage); + let mut cur = resp.interact_pointer_pos().map(to_stage); + // A shape's other end snaps too, unless Shift constrains it (ADR 0045). + if let (Drag::Shape { .. }, Some(c)) = (app.drag, cur) { + cur = Some(if shift { + app.snap_ring = None; + c + } else { + snap_draw(app, c, zoom) + }); + } match (&mut app.drag, cur) { (Drag::Pan, _) => app.view.pan += resp.drag_delta(), (Drag::Move { last }, Some(c)) => { @@ -475,7 +488,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Subselection (ADR 0042): the curve changes in every raw shape that has it. let d = c - *last; if d.length_sq() > 0.0 { - let p = json!({"id": id.0, "cmd": *cmd, "slot": *slot, "dx": d.x, "dy": d.y, "merge": false}); + // A smooth anchor's other handle turns with it; Alt breaks the pair (ADR 0045). + let p = json!({"id": id.0, "cmd": *cmd, "slot": *slot, "dx": d.x, "dy": d.y, "smooth": !alt, "merge": false}); *last = c; if let Some(v) = app.run("raw.move_handle", p) { touched(app, &v["changed"]); @@ -514,7 +528,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let d = c - *last; if d.length_sq() > 0.0 { *last = c; - crate::pathtools::move_points(app, Vec2::new(d.x, d.y)); + crate::pathtools::move_points(app, Vec2::new(d.x, d.y), !alt); } } (Drag::PointMarquee { cur: m, .. }, Some(c)) => *m = c, @@ -970,8 +984,18 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Drag::Shape { start, cur } => draw_preview(app, &painter, to_screen(Vec2::new(start.x, start.y)), to_screen(Vec2::new(cur.x, cur.y)), zoom), _ => {} } - // The snap ring where a dragged point or selection snapped (ADR 0041). - if let Some(at) = app.snap_ring.filter(|_| matches!(app.drag, Drag::SnapMove { .. } | Drag::RawPoint { .. })) { + // The drawing tools show where a press would start, snapped (ADR 0045). + let draws = matches!(app.tool, Tool::Line | Tool::Rect | Tool::Oval | Tool::Star | Tool::Pen) && !panning && !paused && app.pen.as_ref().is_none_or(|p| !p.dragging); + if draws && app.drag == Drag::None { + match pointer.filter(|p| canvas.contains(*p) && resp.hovered()) { + Some(p) => { + snap_draw(app, to_stage(p), zoom); + } + None => app.snap_ring = None, + } + } + // The snap ring where a dragged point, selection or drawn point snapped (ADR 0041, 0045). + if let Some(at) = app.snap_ring.filter(|_| matches!(app.drag, Drag::SnapMove { .. } | Drag::RawPoint { .. } | Drag::Shape { .. }) || (draws && app.drag == Drag::None)) { let c = to_screen(at); painter.circle_stroke(c, SNAP_RING + 1.0, Stroke::new(3.0, Color32::WHITE)); painter.circle_stroke(c, SNAP_RING, Stroke::new(2.0, T.selection)); @@ -1033,6 +1057,15 @@ const SNAP_PX: f32 = 10.0; /// The snap ring's radius (screen pixels). const SNAP_RING: f32 = 6.0; +/// Where a point drawn at stage point `p` goes (the Line, Rectangle, Oval, PolyStar and Pen tools, +/// ADR 0045): snapped within 10 screen pixels to an anchor, else a line or fill edge, while Snap +/// to Objects is on. The snap ring shows where it snapped. +pub fn snap_draw(app: &mut App, p: Pos2, zoom: f32) -> Pos2 { + let v = app.s.execute("draw.snap", &json!({"x": p.x, "y": p.y, "snap": SNAP_PX / zoom.max(1e-3)})); + app.snap_ring = v.as_ref().ok().and_then(snapped_at); + app.snap_ring.map_or(p, |q| pos2(q.x, q.y)) +} + /// A Selection-tool move, this frame: one of the selection's corners (the one nearest the /// pointer) snaps within 10 screen pixels. fn snap_move(app: &mut App, c: Pos2, zoom: f32) { From 43f7bff81effd7a74dbba0877b91041ed7e9b374 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:00:39 -0700 Subject: [PATCH 005/402] feat(engine): edit a symbol's timeline in place: every command, merge drawing and the raw tools work inside it (M1) --- crates/doc/src/eval.rs | 9 + crates/doc/src/lib.rs | 2 +- crates/engine/src/cmds_actions.rs | 2 +- crates/engine/src/cmds_bone.rs | 26 +-- crates/engine/src/cmds_camera.rs | 14 +- crates/engine/src/cmds_draw.rs | 13 +- crates/engine/src/cmds_erase.rs | 4 +- crates/engine/src/cmds_file.rs | 4 +- crates/engine/src/cmds_frames.rs | 14 +- crates/engine/src/cmds_hints.rs | 6 +- crates/engine/src/cmds_modify.rs | 15 +- crates/engine/src/cmds_motion.rs | 6 +- crates/engine/src/cmds_plugin.rs | 3 +- crates/engine/src/cmds_raw.rs | 2 +- crates/engine/src/cmds_rawsub.rs | 2 +- crates/engine/src/cmds_scene.rs | 4 +- crates/engine/src/cmds_sound.rs | 2 +- crates/engine/src/cmds_timeline.rs | 36 ++-- crates/engine/src/confirm.rs | 10 +- crates/engine/src/editing.rs | 327 +++++++++++++++++++++++++++++ crates/engine/src/editing_tests.rs | 131 ++++++++++++ crates/engine/src/history.rs | 2 + crates/engine/src/lib.rs | 52 +++-- crates/engine/src/selection.rs | 18 +- crates/engine/src/tests.rs | 20 +- 25 files changed, 620 insertions(+), 104 deletions(-) create mode 100644 crates/engine/src/editing.rs create mode 100644 crates/engine/src/editing_tests.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 501f104a..9fbf3a82 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -127,6 +127,15 @@ pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList { out } +/// A symbol's timeline at its own `frame`, in the symbol's space, as the stage edits it while the +/// symbol is open for editing (ADR 0045): what picking and bounds use then. Its layers are the +/// top-level ones, as a scene's are in [`evaluate_scene`]. +pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList { + let mut out = DisplayList::default(); + eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY), &mut out, None); + out +} + /// Scene `scene` at its own `frame` as the movie shows it: through the scene's camera, each /// layer shifted by its depth, the camera's tint over everything (ADR 0027). Without a camera /// this is [`evaluate_scene`]. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 444d6aa5..be69ff6a 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -30,7 +30,7 @@ pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, Soun pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use camera::Camera; 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, guide_walk, instance_start}; +pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index ce9540f1..f9dc5dff 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -37,7 +37,7 @@ pub(crate) enum Scope { /// A timeline commands address: a scene's (the one being edited) or a library symbol's. fn timeline_mut(s: &mut Session, symbol: Option, scope: Scope) -> Result<&mut Timeline> { match symbol { - None => Ok(s.doc.timeline_mut(s.scene)), + None => Ok(crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)), Some(id) => { let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; if scope == Scope::Runs && sym.kind != SymbolKind::MovieClip { diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index a2d67fd8..d18defb7 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -46,7 +46,7 @@ struct Found { /// Instance `id` on the scene at the playhead (as it shows: tweened, posed). fn find_instance(s: &Session, id: ElementId) -> Option { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); tl.layers.iter().enumerate().find_map(|(index, l)| { let (_, els) = evaluate_layer_elements(l, s.frame)?; let el = els.iter().find(|e| e.id == id)?.clone(); @@ -56,8 +56,8 @@ fn find_instance(s: &Session, id: ElementId) -> Option { /// The armature layer holding bone `id`, and its armature. fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc)> { - s.doc - .timeline(s.scene) + s + .timeline() .layers .iter() .filter(|l| l.kind == LayerKind::Armature) @@ -85,7 +85,7 @@ fn opt_point(p: &Value, key: &str) -> Result> { } fn unlocked(s: &Session, id: LayerId) -> Result<()> { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let l = tl.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; if l.locked || tl.locked_by_folder(id) { return Err(EngineError::State(format!("layer '{}' is locked", l.name))); @@ -105,7 +105,7 @@ fn take_off(s: &mut Session, layer: LayerId, id: ElementId) -> Result<()> { /// A layer name `base_N` no layer of the scene has yet. fn fresh_name(s: &Session, base: &str) -> String { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); (1..).map(|n| format!("{base}{n}")).find(|n| tl.layers.iter().all(|l| &l.name != n)).unwrap_or_else(|| base.to_string()) } @@ -142,7 +142,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } unlocked(s, x.layer)?; } - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default()); let (fa, ta) = (arm_of(&f), arm_of(&t)); match (&fa, &ta) { @@ -186,10 +186,10 @@ fn add(s: &mut Session, p: &Value) -> Result { None => { // The first bone: both instances move to a new armature layer above them, whose one // pose spans from their keyframe to the end of the timeline. - let (start, end) = s.doc.timeline(s.scene).layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); + let (start, end) = s.timeline().layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); let end = end.max(s.frame_count()); take_off(s, f.layer, from)?; - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let lid = LayerId(s.doc.alloc_id()); @@ -203,7 +203,7 @@ fn add(s: &mut Session, p: &Value) -> Result { k.tween = Some(Tween::default()); layer.keyframes = vec![Arc::new(k)]; let index = f.index.min(t.index); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); layer.parent = tl.container_at(index, LayerKind::Armature); tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); tl.repair_masks(); @@ -230,7 +230,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { left.bones.retain(|b| !gone.contains(&b.id)); let dissolve = left.is_empty(); let freed: Vec = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame()); @@ -244,7 +244,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); k.elements = shown; freed_layer.keyframes = vec![Arc::new(k)]; - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); if dissolve { tl.layers.retain(|l| l.id != lid); tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer)); @@ -328,7 +328,7 @@ fn edit_pose(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Ar if frame > MAX_FRAME { return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); } - let arm = s.doc.timeline(s.scene).layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?; + let arm = s.timeline().layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?; // Past the end a pose carries on from the last one (not a blank keyframe). { let l = s.layer_mut(Some(lid))?; @@ -411,7 +411,7 @@ fn solve(s: &mut Session, p: &Value) -> Result { fn info(s: &mut Session, p: &Value) -> Result { let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); let only = opt_u64(p, "layer")?.map(LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let deg = |v: f32| v.to_degrees(); let pt = |v: Vec2| json!([v.x, v.y]); let list: Vec = tl diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index e8fd10a3..91af9403 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { /// The scene's camera layer id. pub(crate) fn camera_layer(s: &Session) -> Option { - s.doc.timeline(s.scene).camera_layer().map(|l| l.id) + s.timeline().camera_layer().map(|l| l.id) } fn no_camera() -> EngineError { @@ -47,7 +47,7 @@ fn add(s: &mut Session, _: &Value) -> Result { s.selection.clear(); return Ok(json!({"layer": id.0, "added": false})); } - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let id = LayerId(s.doc.alloc_id()); @@ -61,7 +61,7 @@ fn add(s: &mut Session, _: &Value) -> Result { let mut k = Keyframe::new(0, frames); k.elements.push(Arc::new(Camera::rest(&s.doc.stage).to_element(el))); layer.keyframes = vec![Arc::new(k)]; - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.insert(0, Arc::new(layer)); tl.repair_masks(); s.layer = id; @@ -71,11 +71,11 @@ fn add(s: &mut Session, _: &Value) -> Result { fn remove(s: &mut Session, _: &Value) -> Result { let id = camera_layer(s).ok_or_else(no_camera)?; - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.retain(|l| l.id != id); tl.repair_masks(); if s.layer == id { - s.layer = s.doc.timeline(s.scene).layers.first().map_or(LayerId(0), |l| l.id); + s.layer = s.timeline().layers.first().map_or(LayerId(0), |l| l.id); s.selection.clear(); } Ok(json!({"removed": id.0})) @@ -187,9 +187,9 @@ fn camera_json(c: &Camera, stage: &anicraft_doc::Stage) -> Value { fn info(s: &mut Session, p: &Value) -> Result { let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); let Some(id) = camera_layer(s) else { return Ok(json!({"camera": false})) }; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let on = tl.camera_layer().is_some_and(|l| l.visible); - let mut v = s.doc.timeline(s.scene).camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage)); + let mut v = s.timeline().camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage)); v["camera"] = json!(true); v["layer"] = json!(id.0); v["on"] = json!(on); diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 7186276a..03944cb7 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -181,7 +181,7 @@ fn object_drawing(s: &mut Session, p: &Value) -> Result { /// Everything on every visible, unlocked layer at the playhead, as Animate's Select All. fn select_all(s: &mut Session, _: &Value) -> Result { - let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let layers: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); let mut sel = Selection::default(); for l in layers.into_iter().filter(|l| s.gathers(*l)) { sel.extend_on(l, s.elements_on(l).iter().map(|e| e.id)); @@ -202,9 +202,9 @@ fn select(s: &mut Session, p: &Value) -> Result { // 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) { - Some(l) if s.doc.timeline(s.scene).layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), + Some(l) if s.timeline().layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), Some(l) => vec![l], - None => std::iter::once(s.layer).chain(s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), + None => std::iter::once(s.layer).chain(s.timeline().layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), }; let mut at: std::collections::HashMap = std::collections::HashMap::new(); for l in order { @@ -218,7 +218,7 @@ fn select(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State(format!("element {} is not on the active layer, or any layer, at this frame", id.0))); }; if !s.selectable(l) { - let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); return Err(EngineError::State(format!("element {} is on layer '{name}', which is locked or hidden", id.0))); } picked.push((l, id)); @@ -662,7 +662,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { let mut inner: Vec> = Vec::with_capacity(layers.len()); for l in layers { let sel = s.selection.on(l); - let source = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let source = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); let picked = s.with_layer(l, |s| -> Result>> { let kf = s.editable_keyframe()?; let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len()); @@ -756,6 +756,9 @@ fn place(s: &mut Session, p: &Value) -> Result { if s.doc.symbol(sym).is_none() { return Err(EngineError::State(format!("no symbol with id {}", sym.0))); } + if crate::editing::would_nest(s, sym) { + return Err(EngineError::State("a symbol can't be placed inside itself".into())); + } 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); let id = ElementId(s.doc.alloc_id()); diff --git a/crates/engine/src/cmds_erase.rs b/crates/engine/src/cmds_erase.rs index 3f3d22f9..1d18a625 100644 --- a/crates/engine/src/cmds_erase.rs +++ b/crates/engine/src/cmds_erase.rs @@ -267,7 +267,7 @@ fn faucet(s: &mut Session, p: &Value) -> Result { /// The layers `draw.erase_all` clears: visible, unlocked layers that hold artwork (not folders, /// not the camera), with the number of elements at the playhead on each. pub(crate) fn erasable_layers(s: &Session) -> Vec<(anicraft_doc::LayerId, usize)> { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); tl.layers .iter() .filter(|l| l.visible && !l.locked && !tl.locked_by_folder(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera)) @@ -283,7 +283,7 @@ fn erase_all(s: &mut Session, _: &Value) -> Result { let (scene, frame) = (s.scene, s.frame); let mut erased = 0; for (id, _) in &layers { - let Some(layer) = s.doc.timeline_mut(scene).layer_mut(*id) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(*id) else { continue }; let Some(i) = layer.keyframe_index_at(frame) else { continue }; let Some(kf) = layer.keyframe_mut(i) else { continue }; erased += kf.elements.len(); diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 2d59059b..5a046c8c 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -298,7 +298,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { // Clips and masks (ADR 0021): a folder named after the file holding, top first, each // run of artwork, with a mask layer over the runs that are masked. let made = layers.len() + masks + 1; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); if tl.layers.len() + made > 1000 { return Err(EngineError::State(format!("importing {} would make {made} layers; a timeline holds at most 1000", path.display()))); } @@ -343,7 +343,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { cl.keyframes = keys(els); stack.push(cl); } - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); for (k, l) in stack.into_iter().enumerate() { tl.layers.insert((at + k).min(tl.layers.len()), Arc::new(l)); } diff --git a/crates/engine/src/cmds_frames.rs b/crates/engine/src/cmds_frames.rs index ac52fa73..b3d0b131 100644 --- a/crates/engine/src/cmds_frames.rs +++ b/crates/engine/src/cmds_frames.rs @@ -83,11 +83,11 @@ fn copy_frames(s: &mut Session, p: &Value) -> Result { let count = count_param(p)?; let mut ids = target_layers(s, p)?; // Top to bottom, whatever order the params gave. - let order: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let order: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); ids.sort_by_key(|id| order.iter().position(|o| o == id)); let mut layers = Vec::with_capacity(ids.len()); for id in ids { - let l = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; layers.push(FrameSlice { name: l.name.clone(), keys: slice(l, frame, count)? }); } let clip = FrameClipboard { layers, count, symbols: Vec::new(), sounds: Vec::new() }; @@ -123,7 +123,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { if frame.saturating_add(clip.count) > MAX_FRAME || s.frame_count().saturating_add(clip.count) > MAX_FRAME { return Err(EngineError::State("the timeline would grow past its maximum length".into())); } - let mut row = s.doc.timeline(s.scene).layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?; + let mut row = s.timeline().layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?; import_symbols(s, &clip.symbols); for x in &clip.sounds { if s.doc.sound(x.id).is_none() { @@ -135,8 +135,8 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { let mut pasted = Vec::new(); for sl in &clip.layers { // Missing layers below are created, named after the copied ones. - if s.doc.timeline(s.scene).layers.get(row).is_none() { - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.get(row).is_none() { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let id = LayerId(s.doc.alloc_id()); @@ -145,7 +145,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { // The pasted keys are its frames (no stray blank frame at 1). l.keyframes.clear(); } - s.doc.timeline_mut(s.scene).layers.push(Arc::new(l)); + crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.push(Arc::new(l)); } let mut keys = Vec::with_capacity(sl.keys.len()); for k in &sl.keys { @@ -161,7 +161,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { } keys.push(Arc::new(k)); } - let Some(layer) = s.doc.timeline_mut(s.scene).layers.get_mut(row).map(Arc::make_mut) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.get_mut(row).map(Arc::make_mut) else { continue }; crate::cmds_camera::keys_fit(layer.kind, keys.iter().map(|k| &**k))?; if layer.keyframe_index_at(frame).is_some() { insert_keyframe_at(layer, frame, true)?; diff --git a/crates/engine/src/cmds_hints.rs b/crates/engine/src/cmds_hints.rs index f9fce628..63f942a4 100644 --- a/crates/engine/src/cmds_hints.rs +++ b/crates/engine/src/cmds_hints.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; let (i, side) = layer.hint_tween_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is not in a shape tween; select the span and use Insert › Create Shape Tween", frame + 1)))?; Ok((lid, i, side)) @@ -36,7 +36,7 @@ fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> { /// The same, for an edit: refuses locked layers. fn find_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Layer, usize, HintSide)> { let (lid, i, side) = find(s, p)?; - if s.doc.timeline(s.scene).locked_by_folder(lid) { + if s.timeline().locked_by_folder(lid) { return Err(EngineError::State("the layer is in a locked folder".into())); } let layer = s.layer_mut(Some(lid))?; @@ -125,7 +125,7 @@ fn clear_hints(s: &mut Session, p: &Value) -> Result { fn list_hints(s: &mut Session, p: &Value) -> Result { let (lid, i, side) = find(s, p)?; - let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?; + let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?; let (Some(a), Some(b)) = (layer.hint_keyframe(i, HintSide::Start), layer.hint_keyframe(i, HintSide::End)) else { return Err(EngineError::State("the keyframe went away".into())) }; let hints: Vec = a .hints diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index 209bf9f7..5455b5a8 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -101,7 +101,7 @@ fn copy(s: &mut Session, _: &Value) -> Result { let mut copied = Vec::with_capacity(layers.len()); for l in layers { let elements: Vec = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect(); - let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); if !elements.is_empty() { copied.push(ClipLayer { layer: l, name, elements }); } @@ -145,7 +145,7 @@ fn paste_targets(s: &mut Session) -> Result> { if n <= 1 { return Ok(vec![s.layer]); } - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature); let home: Vec = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect(); if home.len() == n { @@ -156,17 +156,17 @@ fn paste_targets(s: &mut Session) -> Result> { out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1)); let names: Vec = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect(); for name in names { - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let id = LayerId(s.doc.alloc_id()); - let count = s.doc.timeline(s.scene).layers.len(); + let count = s.timeline().layers.len(); let mut layer = Layer::new(id, name); if let Some(k) = layer.keyframe_mut(0) { k.duration = s.frame_count().max(1); } layer.color = crate::cmds_timeline::layer_color(count + 1); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.push(Arc::new(layer)); tl.repair_masks(); out.push(id); @@ -178,6 +178,11 @@ fn paste_with(s: &mut Session, offset: Vec2) -> Result { if s.clipboard.is_empty() { return Err(EngineError::State("the clipboard is empty".into())); } + // Inside an open symbol, an instance of it (or of one using it) would nest it in itself. + let nests = s.clipboard.layers.iter().flat_map(|c| &c.elements).any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { symbol, .. } if crate::editing::would_nest(s, symbol))); + if nests { + return Err(EngineError::State("a symbol can't be pasted inside itself".into())); + } import_symbols(s, &s.clipboard.symbols.clone()); let targets = paste_targets(s)?; let copied = s.clipboard.layers.clone(); diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 2f7f6cc2..b0d9e750 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -68,7 +68,7 @@ pub(crate) fn begin_edit(layer: LayerId, kf: &mut Keyframe, frame: u32) -> Optio /// the base back. On the span's first frame a property without keys changes the base itself. pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { let scene = s.scene; - let Some(layer) = s.doc.timeline_mut(scene).layer_mut(e.layer) else { return }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(e.layer) else { return }; let Some(kf) = layer.keyframe_starting_at(e.start).and_then(|i| layer.keyframe_mut(i)) else { return }; let Some(idx) = kf.elements.iter().position(|x| x.id == e.target) else { return }; let Some(after) = kf.elements.get(idx).map(|x| (**x).clone()) else { return }; @@ -411,7 +411,7 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); let (start, ids) = { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; if layer.kind == LayerKind::Folder { return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into())); @@ -545,7 +545,7 @@ fn set_ease(s: &mut Session, p: &Value) -> Result { fn info(s: &mut Session, p: &Value) -> Result { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); - let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; + let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; let kf = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; let m = kf.motion.as_ref().ok_or_else(|| EngineError::State(format!("frame {} is not in a motion tween", frame + 1)))?; let base = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 9dd37206..f0d41024 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -75,8 +75,7 @@ impl Host for SessionHost<'_> { fn document_view(s: &Session) -> Value { let st = &s.doc.stage; let layers: Vec = s - .doc - .timeline(s.scene) + .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)})) diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index e5e16f90..699c027c 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -612,7 +612,7 @@ fn select_rect(s: &mut Session, p: &Value) -> Result { // What each layer has under the marquee, from one display list: wholly inside, or (raw // shapes) partly. let mut found: Vec<(LayerId, Vec, Vec)> = Vec::new(); - let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); + let layers: Vec = s.timeline().layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); for l in layers { let (mut picked, mut partial) = (Vec::new(), Vec::new()); for e in s.elements_on(l) { diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs index b6ba1e86..93114ea8 100644 --- a/crates/engine/src/cmds_rawsub.rs +++ b/crates/engine/src/cmds_rawsub.rs @@ -378,7 +378,7 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { if !add { s.selection.clear(); } - let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer); + let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.timeline().locked_by_folder(s.layer); let empty = json!({"selected": s.selection.id_list(), "anchors": []}); if !usable || !(r.width() > 0.0 || r.height() > 0.0) { return Ok(empty); diff --git a/crates/engine/src/cmds_scene.rs b/crates/engine/src/cmds_scene.rs index 4ff21586..e5ff51fb 100644 --- a/crates/engine/src/cmds_scene.rs +++ b/crates/engine/src/cmds_scene.rs @@ -32,9 +32,11 @@ 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) { + // 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)); s.frame = 0; - s.layer = s.doc.timeline(s.scene).layers.first().map_or(LayerId(0), |l| l.id); + s.layer = s.timeline().layers.first().map_or(LayerId(0), |l| l.id); s.selection.clear(); } diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index 7a8d9a31..c87a6522 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -239,7 +239,7 @@ fn set(s: &mut Session, p: &Value) -> Result { // shaped over, which Custom starts from. let (lid, frame) = target(s, p)?; let fps = s.doc.stage.fps; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let place = tl.layer(lid.unwrap_or(s.layer)).and_then(|l| l.keyframe_at(frame)).map(|k| (k.duration, s.doc.frame_count().saturating_sub(s.doc.scene_start(s.scene).saturating_add(k.start)))); let sounds = s.doc.sounds.clone(); let heard = move |fs: &FrameSound| match (sounds.iter().find(|x| x.id == fs.sound), place) { diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index c452ac97..456ddd78 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -54,11 +54,11 @@ pub fn specs() -> Vec { /// mask back into a normal layer (its masked layers become normal too). fn toggle_mask(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let is_mask = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask; + let is_mask = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask; let ty = if is_mask { "normal" } else { "mask" }; set_type(s, id, ty)?; if !is_mask { - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); // The normal layer directly below, in the same folder, becomes masked. let mask_parent = tl.layer(id).and_then(|m| m.parent); if let Some(i) = tl.layers.iter().position(|l| l.id == id) @@ -76,7 +76,7 @@ fn toggle_mask(s: &mut Session, p: &Value) -> Result { /// Draw a line on the guide; the layer's classic tweens travel along it. fn add_motion_guide(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let Some(l) = tl.layers.get(i) else { return Err(EngineError::State("no such layer".into())) }; if l.kind != LayerKind::Normal { @@ -100,7 +100,7 @@ fn add_motion_guide(s: &mut Session, p: &Value) -> Result { if let Some(k) = guide.keyframe_mut(0) { k.duration = s.frame_count().max(1); } - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.insert(i, Arc::new(guide)); if let Some(l) = tl.layers.get_mut(i + 1) { Arc::make_mut(l).parent = Some(gid); @@ -127,7 +127,7 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result { } fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { - let tl = s.doc.timeline_mut(s.scene); + 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) { return Err(EngineError::State("a folder holds layers; it can't become another kind of layer".into())); @@ -162,8 +162,8 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { } fn layer_type_json(s: &Session, id: LayerId) -> Value { - let Some(l) = s.doc.timeline(s.scene).layer(id) else { return json!({}) }; - let tl = s.doc.timeline(s.scene); + 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); let masked_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Mask)); let guided_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Guide)); @@ -200,7 +200,7 @@ pub(crate) fn target_layers(s: &Session, p: &Value) -> Result> { let mut out: Vec = Vec::with_capacity(ids.len()); let mut folders = 0; for id in ids { - let Some(l) = s.doc.timeline(s.scene).layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) }; + let Some(l) = s.timeline().layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) }; // Folders have no frames: a range across a folder row acts on the layers only. if l.kind == LayerKind::Folder { folders += 1; @@ -463,7 +463,7 @@ fn move_keyframes(s: &mut Session, p: &Value) -> Result { /// keep their content. Lifting everything before placing anything makes overlapping row /// ranges (dragging two rows down by one) come out right. fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, layer_by: i64) -> Result { - let order: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let order: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); let mut rows: Vec = target_layers(s, p)?.iter().filter_map(|id| order.iter().position(|o| o == id)).collect(); rows.sort_unstable(); let mut plan = Vec::with_capacity(rows.len()); @@ -661,7 +661,7 @@ pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba { } fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); if tl.layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } @@ -688,7 +688,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { k.duration = s.frame_count().max(1); } layer.color = layer_color(n); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.insert(at, Arc::new(layer)); tl.repair_masks(); s.layer = id; @@ -700,7 +700,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { /// stays where it is, in the mask's folder. fn delete_layer(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let is_folder = tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder); let range = if is_folder { tl.group_range(i) } else { i..i + 1 }; @@ -709,7 +709,7 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State("a document needs at least one layer to draw on".into())); } let up = tl.layers.get(i).and_then(|l| l.parent); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); if !is_folder { for l in tl.layers.iter_mut().filter(|l| l.parent == Some(id)) { Arc::make_mut(l).parent = up; @@ -718,8 +718,8 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result { let removed: Vec = tl.layers.drain(range.clone()).map(|l| l.id).collect(); tl.repair_masks(); if removed.contains(&s.layer) { - let j = range.start.min(s.doc.timeline(s.scene).layers.len().saturating_sub(1)); - s.layer = s.doc.timeline(s.scene).layers.get(j).map_or(LayerId(0), |l| l.id); + let j = range.start.min(s.timeline().layers.len().saturating_sub(1)); + s.layer = s.timeline().layers.get(j).map_or(LayerId(0), |l| l.id); s.selection.clear(); } Ok(json!({"deleted": id.0, "layers": removed.len()})) @@ -747,11 +747,11 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { let id = if let Some(id) = opt_u64(p, "layer")? { LayerId(id) } else if let Some(i) = opt_u64(p, "index")? { - usize::try_from(i).ok().and_then(|i| s.doc.timeline(s.scene).layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))? + usize::try_from(i).ok().and_then(|i| s.timeline().layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))? } else { return Err(EngineError::Param("pass {\"layer\": id} or {\"index\": n}".into())); }; - if s.doc.timeline(s.scene).layer(id).is_none() { + if s.timeline().layer(id).is_none() { return Err(EngineError::State(format!("no layer with id {}", id.0))); } // A click on a layer's name in Animate: the layer becomes active with all of its artwork at @@ -774,7 +774,7 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { /// where it landed: moving it in under a folder or mask puts it inside, moving it out frees it. fn move_layer(s: &mut Session, p: &Value, d: i64) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline_mut(s.scene); + 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)))?; let n = tl.layers.len(); if tl.layers.get(i).is_some_and(|l| matches!(l.kind, LayerKind::Mask | LayerKind::Folder)) { diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 138d0fa0..66410e71 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -40,7 +40,7 @@ fn plural(n: usize, word: &str) -> String { fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> { let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId); - s.doc.timeline(s.scene).layer(id) + s.timeline().layer(id) } fn target_frame(s: &Session, p: &Value) -> u32 { @@ -59,7 +59,7 @@ fn lost_keys(s: &Session, p: &Value, hit: impl Fn(&Keyframe) -> bool) -> Vec<(St None => vec![p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId)], }; ids.iter() - .filter_map(|id| s.doc.timeline(s.scene).layer(*id)) + .filter_map(|id| s.timeline().layer(*id)) .flat_map(|l| l.keyframes.iter().filter(|k| !k.elements.is_empty() && hit(k)).map(|k| (l.name.clone(), k.elements.len()))) .collect() } @@ -155,11 +155,11 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: false, }) } - "camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?), + "camera.remove" => camera_removal(s, s.timeline().camera_layer()?), "bone.remove" => { // The bone's moves in every pose go with it (ADR 0043); one pose loses nothing. let id = anicraft_doc::BoneId(p.get("bone").and_then(Value::as_u64)?); - let l = s.doc.timeline(s.scene).layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; + let l = s.timeline().layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; let arm = l.armature.as_deref()?; let n = crate::cmds_bone::poses(l); let below = arm.subtree(id).len().saturating_sub(1); @@ -184,7 +184,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { } if l.kind == anicraft_doc::LayerKind::Folder { // A folder goes with everything in it. - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|x| x.id == l.id)?; let inner = tl.layers.get(tl.group_range(i))?; let n = inner.len().saturating_sub(1); diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs new file mode 100644 index 00000000..b068e542 --- /dev/null +++ b/crates/engine/src/editing.rs @@ -0,0 +1,327 @@ +//! Editing a symbol's timeline in place (ADR 0045), as Animate's double-click on an instance does. +//! +//! The session keeps a stack of open symbols. While one is open, every command works on its +//! timeline instead of the scene's ([`Session::timeline`]): its layers are the active layers, the +//! playhead is its playhead, and positions are in its own space. So drawing, merge drawing (ADR +//! 0031), the Selection tool (ADR 0041) and Subselection (ADR 0042) behave inside a symbol exactly +//! as on the stage: they are the same commands on another timeline. Which symbol is open is view +//! state, but undo snapshots keep it, so an undo goes back to where its change was made. +//! +//! The stage draws [`Session::stage_picture`]: the open symbol where its instance stands, over the +//! timelines it sits in, dimmed. + +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_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::hash::{Hash, Hasher}; +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( + "symbol.edit", + "Edit Symbols", + "Edit", + Some("Ctrl+E"), + "{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)", + false, + edit as crate::RunFn, + ), + c("symbol.exit", "Edit Document", "Edit", None, "{all?: bool} closes the open symbol (default: one level; all: back to the scene), selecting the instance it was opened from", false, exit), + ] +} + +/// Most symbols open inside each other at once. +const MAX_LEVELS: usize = 32; +/// How much the artwork around an open symbol shows (Animate dims it). +const DIM: f32 = 0.35; + +/// A symbol open for editing, and what to go back to. +#[derive(Clone, Debug, PartialEq)] +pub struct EditLevel { + pub symbol: SymbolId, + /// The instance it was opened from, on the timeline below (none: from the Library). + pub instance: Option<(LayerId, ElementId)>, + /// Stage space from the symbol's space: where the instance stands (through every level). + pub transform: Affine, + /// The timeline below as it was: its active layer, playhead and selection. + pub layer: LayerId, + pub frame: u32, + pub selection: Selection, +} + +/// The timeline being edited: the open symbol's, else the scene's. +pub(crate) fn edited<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> &'a Timeline { + match editing.last().and_then(|l| doc.symbol(l.symbol)) { + Some(sym) => &sym.timeline, + None => doc.timeline(scene), + } +} + +/// [`edited`] ([`Session::timeline`]), copy-on-write. Takes the fields, so a caller can keep using the session's others. +pub(crate) fn edited_mut<'a>(doc: &'a mut Document, scene: usize, editing: &[EditLevel]) -> &'a mut Timeline { + let open = editing.last().and_then(|l| doc.library.iter().position(|s| s.id == l.symbol)); + // (Borrowed only on the branch that returns it.) + match open { + Some(i) if i < doc.library.len() => &mut Arc::make_mut(&mut doc.library[i]).timeline, + _ => doc.timeline_mut(scene), + } +} + +/// How the stage shows the open symbol: its space on the stage is `translate(origin) · +/// scale(scale)`. `in_place` when that is exactly where its instance stands, so the artwork +/// around it shows too. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EditView { + pub origin: Vec2, + pub scale: f32, + pub in_place: bool, +} + +/// What the stage draws: a document, the movie frame of it to render, and a state id for caching +/// the picture (equal ids, equal pictures). +#[derive(Clone)] +pub struct StagePicture { + pub doc: Document, + pub frame: u32, + pub state: StateId, +} + +impl Session { + /// The timeline being edited: the open symbol's (ADR 0045), else the scene's. + pub fn timeline(&self) -> &Timeline { + edited(&self.doc, self.scene, &self.editing) + } + + /// The symbol open for editing, if any. + pub fn editing_symbol(&self) -> Option { + self.editing.last().map(|l| l.symbol) + } + + /// Closes levels whose symbol is gone (an undo, a Library deletion), from the first such. + pub(crate) fn fix_editing(&mut self) { + if let Some(i) = self.editing.iter().position(|l| self.doc.symbol(l.symbol).is_none()) { + while self.editing.len() > i { + self.exit_level(); + } + } + } + + fn enter_level(&mut self, symbol: SymbolId, instance: Option<(LayerId, ElementId)>, transform: Affine, frame: u32) { + self.editing.push(EditLevel { symbol, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection) }); + // The top layer inside, at the frame the instance shows. + self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); + self.frame = frame.min(self.timeline().frame_count().saturating_sub(1)); + self.revision += 1; + self.dl_cache.replace(None); + } + + /// Closes the open symbol; the instance it was opened from is selected again. False when + /// none is open. + pub(crate) fn exit_level(&mut self) -> bool { + let Some(l) = self.editing.pop() else { return false }; + self.layer = l.layer; + self.frame = l.frame; + self.selection = match l.instance { + Some((layer, id)) => Selection::only(layer, [id]), + None => l.selection, + }; + self.revision += 1; + self.dl_cache.replace(None); + true + } + + /// Closes every open symbol (scene changes, opening a document). + pub(crate) fn exit_all(&mut self) { + while self.exit_level() {} + } + + /// How the stage shows the open symbol, `None` on the stage itself. In place when its + /// instance is only moved and scaled evenly (the editor's view can follow that exactly); + /// otherwise upright and at full size, with its registration point where the instance's is. + pub fn edit_view(&self) -> Option { + let l = self.editing.last()?; + let [a, b, c, d, e, f] = l.transform.m; + let origin = Vec2::new(e, f); + let even = b.abs() < 1e-5 && c.abs() < 1e-5 && a > 1e-4 && (a - d).abs() <= 1e-4 * a.max(1.0); + let in_place = even && self.editing.iter().all(|l| l.instance.is_some()); + Some(if in_place { EditView { origin, scale: a, in_place } } else { EditView { origin, scale: 1.0, in_place: false } }) + } + + /// What the stage draws (ADR 0045): the document at the playhead; while a symbol is open, its + /// timeline at its playhead where its instance stands, over the timelines it sits in dimmed. + pub fn stage_picture(&self) -> Arc { + let Some(view) = self.edit_view() else { + return Arc::new(StagePicture { doc: self.doc.clone(), frame: self.doc.scene_start(self.scene).saturating_add(self.frame), state: self.state }); + }; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (self.state, self.scene, self.frame).hash(&mut h); + for l in &self.editing { + (l.symbol, l.instance, l.frame, l.transform.m.map(f32::to_bits)).hash(&mut h); + } + let key = h.finish(); + if let Some((k, pic)) = &*self.picture_cache.borrow() + && *k == key + { + return pic.clone(); + } + let mut doc = self.doc.clone(); + let mut tl = Timeline::default(); + // The open symbol, in front. + let at = Affine::translate(view.origin.x, view.origin.y).mul(&Affine::scale(view.scale, view.scale)); + tl.layers.push(placed(&mut doc, self.timeline().clone(), at, self.frame, 1.0)); + // Around it, dimmed: each timeline below, without the instance opened from it. + if view.in_place { + for (i, l) in self.editing.iter().enumerate().rev() { + let parent = i.checked_sub(1).and_then(|j| self.editing.get(j)); + let below = match parent { + None => self.doc.timeline(self.scene).clone(), + 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)); + } + } + *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 }); + self.picture_cache.replace(Some((key, pic.clone()))); + pic + } +} + +/// 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 { + let symbol = SymbolId(doc.alloc_id()); + doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, timeline })); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { + id: ElementId(doc.alloc_id()), + name: String::new(), + transform, + color: ColorEffect { alpha, ..ColorEffect::default() }, + 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()), ""); + layer.keyframes.push(Arc::new(k)); + Arc::new(layer) +} + +/// Whether an instance of `sym` placed in the open symbol would put a symbol inside itself: `sym` +/// is open, or uses an open one, however deep. +pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool { + if s.editing.is_empty() { + return false; + } + let mut seen: Vec = Vec::new(); + let mut todo = vec![sym]; + while let Some(id) = todo.pop() { + if s.editing.iter().any(|l| l.symbol == id) { + return true; + } + if seen.contains(&id) || seen.len() > 100_000 { + continue; + } + seen.push(id); + let Some(sym) = s.doc.symbol(id) else { continue }; + for k in sym.timeline.layers.iter().flat_map(|l| l.keyframes.iter()) { + todo.extend(k.elements.iter().filter_map(|e| match e.kind { + ElementKind::Symbol { symbol, .. } => Some(symbol), + _ => None, + })); + } + } + false +} + +/// `tl` without the instance `which` (on every keyframe of its layer). +fn without(mut tl: Timeline, which: Option<(LayerId, ElementId)>) -> Timeline { + let Some((layer, id)) = which else { return tl }; + if let Some(l) = tl.layer_mut(layer) { + for k in &mut l.keyframes { + if k.elements.iter().any(|e| e.id == id) { + Arc::make_mut(k).elements.retain(|e| e.id != id); + } + } + } + tl +} + +/// The instance `id` on a layer at the playhead of the timeline being edited, and its layer. +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 { + if s.editing.len() >= MAX_LEVELS { + return Err(EngineError::State(format!("at most {MAX_LEVELS} symbols can be open inside each other"))); + } + // From the Library: alone, its registration point at the stage's centre. + if let Some(sym) = opt_u64(p, "symbol")? { + let symbol = SymbolId(sym); + if s.doc.symbol(symbol).is_none() { + return Err(EngineError::State(format!("no symbol {sym} in the Library"))); + } + if s.editing.iter().any(|l| l.symbol == symbol) { + return Err(EngineError::State("that symbol is open already".into())); + } + let c = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5); + s.enter_level(symbol, None, Affine::translate(c.x, c.y), 0); + return Ok(editing_json(s)); + } + let id = match opt_u64(p, "id")? { + Some(i) => ElementId(i), + None => { + let picked: Vec = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| matches!(e.kind, ElementKind::Symbol { .. }))).collect(); + match picked.as_slice() { + [one] => *one, + // Nothing to open: Ctrl+E goes back to the document, as in Animate. + [] if !s.editing.is_empty() => { + s.exit_all(); + return Ok(editing_json(s)); + } + [] => return Err(EngineError::State("select a symbol instance to edit it (or double-click it)".into())), + _ => return Err(EngineError::State("select one symbol instance to edit".into())), + } + } + }; + let (layer, el) = instance(s, id).ok_or_else(|| EngineError::State(format!("element {} is not on a layer here at this frame", id.0)))?; + if !s.selectable(layer) { + return Err(EngineError::State("that instance's layer is locked or hidden".into())); + } + let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance".into())) }; + let sym = s.doc.symbol(symbol).ok_or_else(|| EngineError::State("that instance's symbol is missing from the Library".into()))?; + if s.editing.iter().any(|l| l.symbol == symbol) { + return Err(EngineError::State("that symbol is open already".into())); + } + // A graphic opens at the frame the instance shows; movie clips and buttons at their first. + let len = sym.timeline.frame_count(); + let start = s.timeline().layer(layer).and_then(|l| l.keyframe_at(s.frame)).map_or(s.frame, |k| k.start); + let frame = if sym.kind == SymbolKind::Graphic { loop_mode.local_frame(s.frame.saturating_sub(start), first_frame, len) } else { 0 }; + let below = s.editing.last().map_or(Affine::IDENTITY, |l| l.transform); + s.enter_level(symbol, Some((layer, id)), below.mul(&el.transform), frame); + Ok(editing_json(s)) +} + +fn exit(s: &mut Session, p: &Value) -> Result { + if s.editing.is_empty() { + return Err(EngineError::State("no symbol is open for editing".into())); + } + if opt_bool(p, "all")?.unwrap_or(false) { + s.exit_all(); + } else { + s.exit_level(); + } + Ok(editing_json(s)) +} + +/// The open symbols, outermost first. +pub(crate) fn editing_json(s: &Session) -> Value { + let list: Vec = s.editing.iter().map(|l| json!({"symbol": l.symbol.0, "name": s.doc.symbol(l.symbol).map(|x| x.name.clone()), "instance": l.instance.map(|(_, e)| e.0)})).collect(); + json!({"editing": list, "layer": s.layer.0, "frame": s.frame, "selected": s.selection.id_list()}) +} diff --git a/crates/engine/src/editing_tests.rs b/crates/engine/src/editing_tests.rs new file mode 100644 index 00000000..18b6a459 --- /dev/null +++ b/crates/engine/src/editing_tests.rs @@ -0,0 +1,131 @@ +//! Editing a symbol's timeline in place, with raw drawings inside it (ADR 0045). + +use crate::Session; +use anicraft_doc::{Element, ElementId, ElementKind, SymbolId}; +use anicraft_geom::Vec2; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn has(points: &[Vec2], p: (f32, f32)) -> bool { + points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3) +} + +/// A raw outlined rectangle (100 × 80) turned into a symbol, its instance moved to stand at +/// (250, 140): the symbol's space runs from (−50, −40) to (50, 40). +fn boxed() -> (Session, ElementId, SymbolId) { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let (inst, sym) = (ElementId(v["instance"].as_u64().unwrap_or(0)), SymbolId(v["symbol"].as_u64().unwrap_or(0))); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 100})); + (s, inst, sym) +} + +#[test] +fn raw_shapes_inside_a_symbol_merge_and_take_the_selection_and_subselection_tools() { + let (mut s, inst, sym) = boxed(); + let steps = s.history_len(); + let v = run(&mut s, "symbol.edit", json!({})); + assert_eq!(v["editing"][0]["symbol"], json!(sym.0), "{v}"); + assert_eq!(s.history_len(), steps, "opening is not an edit"); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(view.in_place && view.origin.distance(Vec2::new(250.0, 140.0)) < 1e-3 && (view.scale - 1.0).abs() < 1e-6, "{view:?}"); + // Inside: the symbol's own layer, its raw drawing of five shapes, in its space. + assert_eq!(s.timeline().layers.len(), 1); + assert_eq!(raw(&s).len(), 5); + assert!(s.hit_test(Vec2::new(0.0, 0.0), 1.0).is_some(), "picking is in the symbol's space"); + // Subselection: everything connected shows its four corners. + let v = run(&mut s, "raw.subselect", json!({"x": 0, "y": -40})); + assert_eq!(v["anchors"].as_array().map(Vec::len), Some(4), "{v}"); + // The Selection tool: a corner moves with every shape on it. + run(&mut s, "raw.move_point", json!({"x": 50, "y": -40, "to_x": 60, "to_y": -50})); + assert!(has(&s.raw_points(&raw(&s).iter().map(|e| e.id).collect::>()).anchors, (60.0, -50.0))); + // Merge drawing: a line right across cuts the fill in two. + run(&mut s, "draw.line", json!({"x0": -70, "y0": 0, "x1": 70, "y1": 0, "stroke": "#000000"})); + let fills = raw(&s).into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(); + assert_eq!(fills, 2); + // Points: added and deleted inside, shared as on the stage. + run(&mut s, "raw.add_point", json!({"x": -50, "y": 20})); + run(&mut s, "raw.delete_points", json!({"points": [[-50, 20]]})); + // Back on the stage: the instance is selected and shows the edits where it stands. + run(&mut s, "symbol.exit", json!({})); + assert!(s.editing.is_empty()); + assert_eq!(s.selection.ids().collect::>(), vec![inst]); + let b = s.element_bounds(inst); + assert!(b.max.x > 309.0 && b.min.y < 91.0, "the moved corner at (310, 90): {b:?}"); +} + +#[test] +fn undo_goes_back_into_the_symbol_where_the_change_was_made() { + let (mut s, _, sym) = boxed(); + run(&mut s, "symbol.edit", json!({})); + run(&mut s, "raw.delete_points", json!({"points": [[-50, -40]]})); + assert_eq!(raw(&s).iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(), 1); + run(&mut s, "symbol.exit", json!({})); + assert!(s.undo().is_ok()); + assert_eq!(s.editing_symbol(), Some(sym), "undo opens the symbol again"); + assert_eq!(s.raw_points(&raw(&s).iter().map(|e| e.id).collect::>()).anchors.len(), 4, "with the corner back"); + // Undoing the conversion takes the symbol away: editing closes. + while s.undo().is_ok() {} + assert!(s.editing.is_empty() && s.doc.library.is_empty()); +} + +#[test] +fn opening_from_the_library_and_guards() { + let (mut s, inst, sym) = boxed(); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("symbol.edit", &json!({})).is_err(), "nothing selected to open"); + assert!(s.execute("symbol.exit", &json!({})).is_err(), "nothing open"); + run(&mut s, "symbol.edit", json!({"symbol": sym.0})); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + let centre = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5); + assert!(!view.in_place && view.origin == centre, "alone, at the stage's centre: {view:?}"); + assert!(s.execute("library.place", &json!({"symbol": sym.0})).is_err(), "not inside itself"); + assert!(s.execute("symbol.edit", &json!({"symbol": sym.0})).is_err(), "open already"); + // Ctrl+E with nothing to open goes back to the document. + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "symbol.edit", json!({})); + assert!(s.editing.is_empty()); + // A rotated instance opens upright where it stands, the artwork around it hidden. + run(&mut s, "element.select", json!({"ids": [inst.0]})); + run(&mut s, "modify.transform", json!({"a": 0.0, "b": 1.0, "c": -1.0, "d": 0.0, "e": 0.0, "f": 0.0})); + run(&mut s, "symbol.edit", json!({"id": inst.0})); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(!view.in_place && (view.scale - 1.0).abs() < 1e-6, "{view:?}"); + // A scene change closes it. + run(&mut s, "scene.new", json!({})); + assert!(s.editing.is_empty()); +} + +#[test] +fn the_stage_shows_the_open_symbol_in_place_over_the_dimmed_stage() { + let (mut s, _, _) = boxed(); + // Something else on the stage, beside the instance. + run(&mut s, "draw.rect", json!({"x": 400, "y": 300, "w": 50, "h": 50, "fill": "#0000ff", "stroke": null, "object": true})); + run(&mut s, "element.pick", json!({"x": 250, "y": 140})); + run(&mut s, "symbol.edit", json!({})); + let pic = s.stage_picture(); + assert_eq!(pic.state, s.stage_picture().state, "the same picture twice"); + let px = anicraft_render::render_frame(&pic.doc, pic.frame, 1.0).unwrap_or_else(|e| panic!("{e}")); + let at = |x: u32, y: u32| px.pixel(x, y).unwrap_or_else(|| panic!("in the picture")); + // The symbol's fill in full red where its instance stands... + let red = at(250, 140); + assert!(red[0] > 0.95 && red[1] < 0.05 && red[2] < 0.05, "{red:?}"); + // ...and the stage around it dimmed (blue at about a third over white). + let blue = at(425, 325); + assert!(blue[2] > 0.95 && blue[0] > 0.5 && blue[0] < 0.8, "{blue:?}"); + // The document itself is untouched by the picture. + assert_eq!(s.doc.library.len(), 1); + // Back on the stage, the picture is the document. + run(&mut s, "symbol.exit", json!({})); + assert_eq!(s.stage_picture().state, s.state); +} diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 25294358..bc77a119 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -28,6 +28,8 @@ pub struct Snapshot { pub doc: Document, pub state: StateId, pub scene: usize, + /// The symbols open for editing (ADR 0045). + pub editing: Vec, pub frame: u32, pub layer: LayerId, pub selection: crate::Selection, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index daec66e3..122e0d96 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod cmds_text; mod cmds_timeline; mod cmds_width; pub mod confirm; +pub mod editing; pub mod format; pub mod history; mod merge; @@ -118,6 +119,7 @@ pub fn commands() -> Vec { v.extend(cmds_raw::specs()); v.extend(cmds_rawsub::specs()); v.extend(cmds_rawpoints::specs()); + v.extend(editing::specs()); v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); @@ -207,14 +209,17 @@ impl ToolStyle { } /// An open document plus everything the editor tracks about it. -/// A display list and the `(state, scene, frame)` it was evaluated for. -type CachedList = (StateId, usize, u32, Arc); +/// A display list and the `(state, scene, frame, open symbol)` it was evaluated for. +type CachedList = (StateId, usize, u32, Option, Arc); pub struct Session { /// The document: a persistent tree, so cloning it (undo, render thread) is cheap. pub doc: Document, /// The scene being edited (index into `doc.scenes`). pub scene: usize, + /// Symbols open for editing, outermost first (ADR 0045). While one is open, commands work on + /// its timeline: `frame`, `layer` and `selection` are its. + pub editing: Vec, /// Playhead within the scene (0-based). pub frame: u32, /// Active layer. @@ -254,6 +259,8 @@ 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, + /// The last picture of an open symbol in place, by its key (ADR 0045). + picture_cache: RefCell)>>, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -297,6 +304,7 @@ impl Session { Session { doc, scene: 0, + editing: Vec::new(), frame: 0, layer, selection: Selection::default(), @@ -317,6 +325,7 @@ impl Session { provisional: None, pending_cut: None, gesture_cut: None, + picture_cache: RefCell::new(None), } } @@ -591,20 +600,22 @@ impl Session { if g.doc == self.doc && g.selection == self.selection { return; } - let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; + let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; self.restore(back); self.revision += 1; self.fix_selection(); } fn snapshot(&self, label: &str) -> Snapshot { - Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } + Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } } fn restore(&mut self, s: Snapshot) { self.doc = s.doc; self.state = s.state; self.scene = s.scene; + // Where the change was made: an undo inside a symbol opens it again (ADR 0045). + self.editing = s.editing; self.frame = s.frame; self.layer = s.layer; self.selection = s.selection; @@ -665,28 +676,34 @@ impl Session { // ----- queries --------------------------------------------------------------------------- pub fn frame_count(&self) -> u32 { - self.doc.timeline(self.scene).frame_count() + self.timeline().frame_count() } pub fn active_layer(&self) -> Option<&Layer> { - self.doc.timeline(self.scene).layer(self.layer) + self.timeline().layer(self.layer) } pub fn active_layer_index(&self) -> Option { - self.doc.timeline(self.scene).layers.iter().position(|l| l.id == self.layer) + self.timeline().layers.iter().position(|l| l.id == self.layer) } /// The current scene evaluated at the playhead, cached per `(state, scene, frame)`. pub fn display_list(&self) -> Arc { - if let Some((s, sc, f, dl)) = &*self.dl_cache.borrow() + let open = self.editing_symbol(); + if let Some((s, sc, f, o, dl)) = &*self.dl_cache.borrow() && *s == self.state && *sc == self.scene && *f == self.frame + && *o == open { return dl.clone(); } - let dl = Arc::new(evaluate_scene(&self.doc, self.scene, self.frame)); - self.dl_cache.replace(Some((self.state, self.scene, self.frame, dl.clone()))); + // An open symbol is edited in its own space (ADR 0045). + let dl = Arc::new(match open.and_then(|id| self.doc.symbol(id)) { + Some(sym) => anicraft_doc::evaluate_timeline(&self.doc, &sym.timeline, self.frame), + None => evaluate_scene(&self.doc, self.scene, self.frame), + }); + self.dl_cache.replace(Some((self.state, self.scene, self.frame, open, dl.clone()))); dl } @@ -706,7 +723,7 @@ impl Session { if !bounds.contains(p) { continue; } - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); let Some(layer) = tl.layer(item.layer) else { continue }; if layer.locked || tl.locked_by_folder(layer.id) { continue; @@ -742,7 +759,7 @@ impl Session { pub(crate) fn layer_mut(&mut self, id: Option) -> Result<&mut Layer> { let id = id.unwrap_or(self.layer); - self.doc.timeline_mut(self.scene).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) + crate::editing::edited_mut(&mut self.doc, self.scene, &self.editing).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) } /// The keyframe on the active layer that edits at the playhead should change. Creates a @@ -756,7 +773,7 @@ impl Session { /// refused there. pub(crate) fn editable_keyframe_in(&mut self, what: KeyEdit) -> Result<&mut Keyframe> { let frame = self.frame; - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); if let Some(l) = tl.layer(self.layer) { if l.kind == LayerKind::Folder { return Err(EngineError::State(format!("'{}' is a folder; pick a layer inside it to draw on", l.name))); @@ -773,7 +790,7 @@ impl Session { } // Through the fields, not `layer_mut`, so `motion_edit` can be set below. let (scene, active) = (self.scene, self.layer); - let layer = self.doc.timeline_mut(scene).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; + let layer = crate::editing::edited_mut(&mut self.doc, scene, &self.editing).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; if layer.locked { return Err(EngineError::State(format!("layer '{}' is locked", layer.name))); } @@ -813,8 +830,7 @@ impl Session { /// JSON summary used by `doc.info` and the CLI. pub fn info(&self) -> Value { let layers: Vec = self - .doc - .timeline(self.scene) + .timeline() .layers .iter() .map(|l| { @@ -836,6 +852,8 @@ impl Session { "layer": self.layer.0, "selection": self.selection.id_list(), "selection_layers": self.selected_layers().iter().map(|l| l.0).collect::>(), + // The symbols open for editing, outermost first (ADR 0045); `layers` are the open one's. + "editing": editing::editing_json(self)["editing"], "layers": layers, "library": symbols, "sounds": sounds, @@ -909,6 +927,8 @@ mod rawsub_tests; #[cfg(test)] mod rawpoints_tests; #[cfg(test)] +mod editing_tests; +#[cfg(test)] mod brush_tests; #[cfg(test)] mod web_tests; diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 964cfa78..8d727b37 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -184,13 +184,13 @@ fn merge_results(results: Vec<(LayerId, Value)>) -> Value { impl Session { /// The elements on `layer` at the playhead (tweens applied). pub fn elements_on(&self, layer: LayerId) -> Vec> { - self.doc.timeline(self.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() + self.timeline().layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() } /// Whether artwork on `layer` can be selected: it is in this scene, shown and unlocked /// (folders included), and not a folder. pub fn selectable(&self, layer: LayerId) -> bool { - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return false }; tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder) && !tl.locked_by_folder(layer) && !tl.hidden_by_folder(i) } @@ -199,14 +199,14 @@ impl Session { /// artwork on it. The camera layer holds only the camera, and an armature layer's /// instances are posed by their bones, so they are gathered only while active. pub fn gathers(&self, layer: LayerId) -> bool { - let kind = self.doc.timeline(self.scene).layer(layer).map(|l| l.kind); + let kind = self.timeline().layer(layer).map(|l| l.kind); self.selectable(layer) && (layer == self.layer || !matches!(kind, Some(LayerKind::Camera | LayerKind::Armature))) } /// The layers with selected items, top to bottom. pub fn selected_layers(&self) -> Vec { let mine = self.selection.layers(); - self.doc.timeline(self.scene).layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() + self.timeline().layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() } /// Every selected element as it looks at the playhead, with its layer: layers top to @@ -249,8 +249,10 @@ impl Session { /// locked (a locked or hidden layer is never selected), and keeps the active layer valid. pub fn fix_selection(&mut self) { self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); - if self.doc.timeline(self.scene).layer(self.layer).is_none() { - self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id); + // A symbol that is gone closes (ADR 0045). + self.fix_editing(); + if self.timeline().layer(self.layer).is_none() { + self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); } if self.selection.is_empty() { return; @@ -321,7 +323,7 @@ impl Session { } } } - if self.doc.timeline(self.scene).layer(active).is_some() { + if self.timeline().layer(active).is_some() { self.layer = active; } self.selection = after; @@ -341,7 +343,7 @@ impl Session { crate::cmds_motion::finish_edit(self, edit); } self.dl_cache.replace(None); - if self.doc.timeline(self.scene).layer(active).is_some() { + if self.timeline().layer(active).is_some() { self.layer = active; } r diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 49287701..fae1f477 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -665,7 +665,21 @@ fn panic_hunt_every_command() { layered.execute(id, &p).unwrap(); } assert_eq!(layered.selected_layers().len(), 2, "the fuzz starts with a selection on two layers"); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered] { + // Raw drawings inside a symbol open for editing in place (ADR 0045), with a point added. + let mut in_symbol = Session::default(); + in_symbol.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("modify.convert_to_symbol", json!({"name": "Inner"})), + ("element.translate", json!({"dx": 30, "dy": 15})), + ("symbol.edit", json!({})), + ("draw.rect", json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"})), + ("raw.add_point", json!({"x": 45, "y": 90})), + ] { + in_symbol.execute(id, &p).unwrap(); + } + assert_eq!(in_symbol.editing.len(), 1, "the fuzz starts inside a symbol"); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -677,10 +691,12 @@ fn panic_hunt_every_command() { let _ = s.execute(spec.id, p); } } - // The document must still evaluate and render. + // The document must still evaluate and render, and so must what the stage shows. for f in [0, 1, 5, 47, 1000] { let _ = anicraft_render::render_frame(&s.doc, f, 0.1); } + let pic = s.stage_picture(); + 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); let mut out = vec![0.0; 2 * 4096]; From 02908914680d9d8f4cadc11d30dcda0780c94991 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:07:18 -0700 Subject: [PATCH 006/402] feat(stage): edit symbols in place: double-click an instance, Ctrl+E, the edit bar's path back; Library Edit Symbol (M1) --- crates/engine/src/cmds_camera.rs | 4 ++ src/actions_panel.rs | 4 +- src/app.rs | 51 ++++++++++++++++++-- src/bone_tool.rs | 12 ++--- src/camera_tool.rs | 8 ++-- src/main.rs | 2 +- src/menus.rs | 7 ++- src/motion_path.rs | 2 +- src/panels.rs | 44 ++++++++++++++--- src/stage.rs | 81 +++++++++++++++++++++++--------- src/timeline.rs | 18 +++---- 11 files changed, 174 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index 91af9403..a5b64bbe 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -42,6 +42,10 @@ fn no_camera() -> EngineError { } fn add(s: &mut Session, _: &Value) -> Result { + // A scene has the camera, not a symbol (ADR 0027, 0045). + if !s.editing.is_empty() { + return Err(EngineError::State("the camera belongs to a scene: close the symbol you are editing first (Edit › Edit Document)".into())); + } if let Some(id) = camera_layer(s) { s.layer = id; s.selection.clear(); diff --git a/src/actions_panel.rs b/src/actions_panel.rs index 106087c5..28c7a5b7 100644 --- a/src/actions_panel.rs +++ b/src/actions_panel.rs @@ -444,7 +444,7 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S fn frame_target(app: &mut App, ui: &mut egui::Ui, doc: &Document) -> Option { match app.actions.symbol { None => { - let tl = doc.timeline(app.s.scene); + let tl = app.s.timeline().clone(); let layer = tl.layer(app.s.layer)?; let frame = app.s.frame; form_row(ui, FORM_LABEL_DOCK, tr!("Keyframe"), |ui| { @@ -581,7 +581,7 @@ fn instance_tab(app: &mut App, ui: &mut egui::Ui, e: &Element) { ui.label(text(Type::Caption, tr!("Name it to address it from actions (letters, digits and _). Its events work without a name."))); } let ElementKind::Symbol { events, .. } = &e.kind else { return }; - let tl = doc.timeline(app.s.scene).clone(); + let tl = app.s.timeline().clone(); let cx = Choices::new(&doc, &tl, true); ui.add_space(4.0); ui.label(text(Type::Caption, tr!("Its actions run on the timeline it is on: “this” is the main timeline."))); diff --git a/src/app.rs b/src/app.rs index b4674d72..9545c415 100644 --- a/src/app.rs +++ b/src/app.rs @@ -568,7 +568,7 @@ impl App { /// through, so it says how to add one. pub fn toggle_camera_preview(&mut self) { self.camera_preview = !self.camera_preview; - if self.camera_preview && self.s.doc.timeline(self.s.scene).camera_layer().is_none() { + if self.camera_preview && self.s.timeline().camera_layer().is_none() { self.status_ok(tr!("Preview through camera is on; add a camera (the camera button on the timeline, or the Camera tool) to look through it.")); } } @@ -949,6 +949,49 @@ impl App { self.drag = Drag::RawHandle { id: h.id, cmd: h.cmd, slot: h.slot, last: egui::pos2(h.at.x + 40.0, h.at.y + 10.0) }; } } + Some("rawpoints") => { + // Raw points (ADR 0045) on a new layer: an outlined square whose top-left corner + // was deleted (the fill and its outline joined across the diagonal), and a point + // added on its right side, pulled out and made smooth, selected with its handle + // pair showing. + self.run("layer.new", json!({})); + self.run("draw.rect", json!({"x": 240, "y": 140, "w": 320, "h": 260, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("draw.ellipse", json!({"x": 640, "y": 170, "w": 240, "h": 200, "fill": "#3d8bfd", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("edit.deselect", json!({})); + self.run("raw.delete_points", json!({"points": [[240, 140]]})); + self.run("raw.add_point", json!({"x": 560, "y": 270})); + self.run("raw.move_point", json!({"x": 560, "y": 270, "to_x": 620, "to_y": 270})); + self.run("raw.convert_points", json!({"points": [[620, 270]], "smooth": true})); + self.tool = Tool::Subselect; + self.run("raw.subselect", json!({"x": 400, "y": 400, "slop": 4})); + self.raw_ends = Vec::new(); + self.raw_anchors = vec![anicraft_engine::geom::Vec2::new(620.0, 270.0)]; + } + Some("rawsnap") => { + // Snapping while drawing (ADR 0045): a line being drawn from a corner of a raw + // square, its end snapping onto the square's other corner (the ring). + self.run("layer.new", json!({})); + self.run("draw.rect", json!({"x": 240, "y": 140, "w": 320, "h": 260, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("edit.deselect", json!({})); + self.tool = Tool::Line; + self.drag = Drag::Shape { start: egui::pos2(240.0, 400.0), cur: egui::pos2(560.0, 140.0) }; + self.snap_ring = Some(anicraft_engine::geom::Vec2::new(560.0, 140.0)); + } + Some("symboledit") => { + // A symbol open for editing in place (ADR 0045): a raw drawing inside it, merged + // with a line drawn across it there, its connected points showing under the + // Subselection tool; the stage around it dimmed, the way back above. + self.run("layer.new", json!({})); + self.run("draw.rect", json!({"x": 260, "y": 160, "w": 300, "h": 220, "fill": "#e8553b", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("modify.convert_to_symbol", json!({"name": "Badge"})); + self.run("symbol.edit", json!({})); + self.run("draw.line", json!({"x0": -190, "y0": 40, "x1": 190, "y1": -40, "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("draw.ellipse", json!({"x": 60, "y": -150, "w": 140, "h": 140, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("edit.deselect", json!({})); + self.tool = Tool::Subselect; + self.run("raw.subselect", json!({"x": 0, "y": 60, "slop": 4})); + self.raw_ends = Vec::new(); + } 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 @@ -1016,7 +1059,7 @@ impl App { Some("frames") => { // Frames 8–20 selected on the top three layers, with a keyframe drag in progress: // 6 frames later and one layer down. - let layers = &self.s.doc.timeline(self.s.scene).layers; + let layers = &self.s.timeline().layers; if let (Some(a), Some(b)) = (layers.first(), layers.get(2)) { self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 7), head: (b.id, 19) }); self.tl_drag = timeline::TlDrag::Move { grab: 10, by: 6, grab_row: 0, rows_by: 1 }; @@ -1129,7 +1172,7 @@ impl App { } Some("span") => { // Stretching the Star layer's span by its end, with the length readout. - if let Some(l) = self.s.doc.timeline(self.s.scene).layers.get(1) + if let Some(l) = self.s.timeline().layers.get(1) && let Some(k) = l.keyframes.first() { self.tl_drag = timeline::TlDrag::Span { layer: l.id, start: k.start, end: k.end(), to: k.end() + 6 }; @@ -1728,7 +1771,7 @@ impl App { self.status_ok(if self.align_to_stage { tr!("Align: to stage") } else { tr!("Align: to the selection") }); } "view.select_all_frames" => { - let layers = &self.s.doc.timeline(self.s.scene).layers; + let layers = &self.s.timeline().layers; if let (Some(a), Some(b)) = (layers.first(), layers.last()) { let last = self.s.frame_count().saturating_sub(1); self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 0), head: (b.id, last) }); diff --git a/src/bone_tool.rs b/src/bone_tool.rs index fff28374..d9a59e03 100644 --- a/src/bone_tool.rs +++ b/src/bone_tool.rs @@ -35,7 +35,7 @@ pub struct Shown { /// Every visible armature on the scene at the playhead, bottom layer first. pub fn shown(app: &App) -> Vec { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); tl.layers .iter() .enumerate() @@ -85,7 +85,7 @@ fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 { /// its layer and id. fn instance_at(app: &App, sp: Vec2, slop: f32, skip: Option) -> Option<(LayerId, ElementId)> { let dl = app.s.display_list(); - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); for item in dl.items.iter().rev() { if Some(item.element) == skip || item.guide || item.masks.is_some() { continue; @@ -120,7 +120,7 @@ pub fn select(app: &mut App, layer: LayerId, bone: Option) { pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag { let sp = xf.to_stage(press); if let Some((layer, id, Part::End)) = hit(app, xf, press) - && let Some(child) = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(id)).map(|b| b.child) + && let Some(child) = app.s.timeline().layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(id)).map(|b| b.child) && let Some(b) = shown(app).into_iter().find(|s| s.layer == layer).and_then(|s| s.bones.into_iter().find(|b| b.id == id)) { // A chain joins end to start. @@ -163,7 +163,7 @@ pub fn click(app: &mut App, xf: Xf, p: Pos2) { /// isn't on an armature. pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option { let sp = xf.to_stage(press); - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let (layer, bone, local) = match hit(app, xf, press) { Some((layer, id, _)) => (layer, Some(id), None), None => { @@ -178,7 +178,7 @@ pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option { match bone { Some(id) => { select(app, layer, Some(id)); - let arm = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.clone())?; + let arm = app.s.timeline().layer(layer).and_then(|l| l.armature.clone())?; if armature::movable_chain(&arm, id).is_empty() { app.status_ok(tr!("That bone is pinned (or hangs from a pinned bone): unpin it in Properties to drag it.")); return Some(Drag::None); @@ -231,7 +231,7 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) { /// Drops a selected bone that no longer exists. pub fn upkeep(app: &mut App) { if let Some(id) = app.bone_sel { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); if !tl.layers.iter().any(|l| l.kind == LayerKind::Armature && l.armature.as_ref().is_some_and(|a| a.bone(id).is_some())) { app.bone_sel = None; } diff --git a/src/camera_tool.rs b/src/camera_tool.rs index fb322a87..f83d79b0 100644 --- a/src/camera_tool.rs +++ b/src/camera_tool.rs @@ -37,18 +37,18 @@ impl Geo { /// The scene's camera at the playhead (the rest camera on a blank camera keyframe). pub fn camera(app: &App) -> Option { - app.s.doc.timeline(app.s.scene).camera_state_at(app.s.frame, &app.s.doc.stage) + app.s.timeline().camera_state_at(app.s.frame, &app.s.doc.stage) } /// Whether the stage shows the movie through the camera this frame. pub fn previewing(app: &App) -> bool { - app.camera_preview && app.s.doc.timeline(app.s.scene).camera_layer().is_some() + app.camera_preview && app.s.timeline().camera_layer().is_some() } /// Picking the Camera tool adds a camera when the scene has none (as Animate does), once per /// pick: undoing the add leaves the tool in hand without adding it again. pub fn on_tool_change(app: &mut App) { - if app.tool == Tool::Camera && app.last_tool != Tool::Camera && app.s.doc.timeline(app.s.scene).camera_layer().is_none() && app.run("camera.add", json!({})).is_some() { + if app.tool == Tool::Camera && app.last_tool != Tool::Camera && app.s.timeline().camera_layer().is_none() && app.run("camera.add", json!({})).is_some() { app.status_ok(tr!("Added a camera. Drag on the stage to pan it, turn it with the round handle, zoom with the wheel. {undo} to undo.", undo = app.undo_key())); } app.last_tool = app.tool; @@ -150,7 +150,7 @@ pub fn tick(app: &mut App, ctx: &egui::Context, now: f64) { /// The camera frame (editing) or the camera-view marks (previewing), and the Camera tool's /// handles. pub fn draw(app: &App, painter: &egui::Painter, g: &Geo, hot: Option) { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let Some(layer) = tl.camera_layer() else { return }; let Some(cam) = camera(app) else { return }; let color = to_color32(layer.color); diff --git a/src/main.rs b/src/main.rs index 7afe4600..6406039e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -175,7 +175,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|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope]\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|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope]\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 997d2c6a..720d6ee9 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -46,12 +46,15 @@ fn enabled(app: &App, id: &str) -> bool { "edit.undo" => app.s.can_undo(), "edit.redo" => app.s.can_redo(), "edit.delete" | "edit.duplicate" | "modify.convert_to_symbol" | "modify.break_apart" | "arrange.bring_to_front" | "arrange.send_to_back" => !app.s.selection.is_empty(), - "layer.delete" => app.s.doc.timeline(app.s.scene).layers.len() > 1, + "layer.delete" => app.s.timeline().layers.len() > 1, "scene.delete" => app.s.doc.scenes.len() > 1, + // Ctrl+E opens the selected instance, or goes back to the document (ADR 0045). + "symbol.exit" => !app.s.editing.is_empty(), + "symbol.edit" => !app.s.editing.is_empty() || app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { .. })), "scene.prev" | "scene.move_up" => app.s.scene > 0, "scene.next" | "scene.move_down" => app.s.scene + 1 < app.s.doc.scenes.len(), "timeline.clear_keyframe" => match app.frame_sel { - Some(sel) => sel.has_keys(&app.s.doc.timeline(app.s.scene).layers), + Some(sel) => sel.has_keys(&app.s.timeline().layers), None => app.s.active_layer().is_some_and(|l| l.keyframe_starting_at(app.s.frame).is_some()), }, "timeline.paste_frames" => !app.s.frame_clipboard.is_empty(), diff --git a/src/motion_path.rs b/src/motion_path.rs index a9d40f66..60acc37d 100644 --- a/src/motion_path.rs +++ b/src/motion_path.rs @@ -59,7 +59,7 @@ pub struct Shown { /// The motion path of the active layer's motion tween at the playhead, when its object or a /// frame of its span is selected and it moves at all. pub fn shown(app: &App) -> Option { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let layer = app.s.active_layer().filter(|l| l.visible && l.kind == anicraft_engine::doc::LayerKind::Normal)?; let k = layer.keyframe_at(app.s.frame)?; let m = k.motion.as_ref()?; diff --git a/src/panels.rs b/src/panels.rs index 7d713209..a572d2eb 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -139,6 +139,11 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { app.playing = false; app.frame_sel = None; app.run("scene.select", serde_json::json!({"scene": i})); + } else if r.inner.clicked() && !app.s.editing.is_empty() { + // The scene itself, from inside a symbol: back to it (ADR 0045). + app.playing = false; + app.frame_sel = None; + app.run("symbol.exit", serde_json::json!({"all": true})); } } ui.separator(); @@ -148,6 +153,22 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { }) .response .set_name(tr!("Scene")); + // The symbols open for editing (ADR 0045), as in Animate's edit bar: a click on one + // goes back to it; the last is the one being edited. + let open: Vec = app.s.editing.iter().map(|l| app.s.doc.symbol(l.symbol).map_or_else(String::new, |s| s.name.clone())).collect(); + let mut back: Option = None; + for (i, name) in open.iter().enumerate() { + ui.label(text(Type::Caption, "›")); + if i + 1 == open.len() { + ui.label(text(Type::Body, name.clone()).strong()); + } else if ui.link(text(Type::Body, name.clone())).on_hover_text(tr!("Back to this symbol")).clicked() { + back = Some(i + 1); + } + } + if let Some(keep) = back { + app.playing = false; + while app.s.editing.len() > keep && app.run("symbol.exit", serde_json::json!({})).is_some() {} + } ui.label(text(Type::Caption, "›")); let layer = app.s.active_layer().map_or("—".to_string(), |l| l.name.clone()); ui.label(text(Type::Body, layer).color(T.text_dim)); @@ -384,13 +405,13 @@ fn properties(app: &mut App, ui: &mut egui::Ui) { }); } // ---- the camera, with the Camera tool or its layer active (ADR 0027) ---- - let camera_layer = app.s.doc.timeline(app.s.scene).camera_layer().map(|l| l.id); + let camera_layer = app.s.timeline().camera_layer().map(|l| l.id); if camera_layer.is_some() && (app.tool == Tool::Camera || camera_layer == Some(app.s.layer)) { section(ui, "prop_camera", Section::Rule, tr!("Camera"), None, |ui| camera_props(app, ui)); } // ---- the bone picked on the stage (ADR 0043) ---- if let Some(id) = app.bone_sel { - let name = app.s.doc.timeline(app.s.scene).layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| b.name.clone())); + let name = app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| b.name.clone())); if let Some(name) = name { let title = if name.is_empty() { tr!("Bone").to_string() } else { tr!("Bone: {name}", name = name) }; section(ui, "prop_bone", Section::Rule, &title, None, |ui| bone_props(app, ui, id)); @@ -1142,14 +1163,14 @@ fn camera_props(app: &mut App, ui: &mut egui::Ui) { app.run("camera.set", json!({"reset": true})); } }); - let hidden = app.s.doc.timeline(app.s.scene).camera_layer().is_some_and(|l| !l.visible); + let hidden = app.s.timeline().camera_layer().is_some_and(|l| !l.visible); ui.label(text(Type::Caption, if hidden { tr!("The camera layer is hidden: the movie shows the stage as it is.") } else { tr!("The movie shows what the frame on the stage shows. Layer depth (in Frame, per layer) moves far layers less.") })); } /// The selected bone: its joint angle at the playhead (editing it keys the pose), the joint's /// limits, the pin, and removal. fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId) { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let Some((layer, bone)) = tl.layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| (l.clone(), b.clone()))) else { return }; let pose = anicraft_engine::doc::armature::pose_at(&layer, app.s.frame).unwrap_or_default(); let mut angle = bone.allow(pose.angle(id)).to_degrees(); @@ -1223,14 +1244,14 @@ fn document_props(app: &mut App, ui: &mut egui::Ui) { fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::Layer, frame: u32) { if layer.kind == anicraft_engine::doc::LayerKind::Folder { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let n = tl.layers.iter().position(|l| l.id == layer.id).map_or(0, |i| tl.group_range(i).len().saturating_sub(1)); ui.label(text(Type::Label, trn!("Folder · {n} layer", "Folder · {n} layers", n))); ui.label(text(Type::Caption, tr!("Folders hold layers, not frames. Hiding or locking the folder hides or locks everything in it; move layers in under it with Up and Down."))); return; } // Layer depth matters once the scene has a camera: deeper layers move less as it pans. - if layer.kind != anicraft_engine::doc::LayerKind::Camera && app.s.doc.timeline(app.s.scene).camera_layer().is_some() { + if layer.kind != anicraft_engine::doc::LayerKind::Camera && app.s.timeline().camera_layer().is_some() { let mut depth = layer.depth; let (lo, hi) = (anicraft_engine::doc::camera::MIN_DEPTH, anicraft_engine::doc::camera::MAX_DEPTH); row(ui, tr!("Depth"), |ui| { @@ -1351,7 +1372,7 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L .set_name(tr!("Tween kind")); }); // On a layer a motion guide steers: turn with the path. - let guided = layer.parent.is_some_and(|p| app.s.doc.timeline(app.s.scene).layer(p).is_some_and(|g| g.kind == anicraft_engine::doc::LayerKind::Guide)); + let guided = layer.parent.is_some_and(|p| app.s.timeline().layer(p).is_some_and(|g| g.kind == anicraft_engine::doc::LayerKind::Guide)); if guided { let mut orient = t.orient; if crate::theme::checkbox(ui, &mut orient, tr!("Orient to path")).on_hover_text(tr!("Turn with the motion guide as it bends")).changed() { @@ -1792,6 +1813,15 @@ fn library(app: &mut App, ui: &mut egui::Ui) { if resp.double_clicked() { place(app, row.item); } + // Opens it alone, its registration point at the stage's centre (ADR 0045). + if let LibraryItem::Symbol(id) = row.item { + resp.context_menu(|ui| { + if ui.button(tr!("Edit Symbol")).clicked() { + ui.close(); + app.run("symbol.edit", json!({"symbol": id.0})); + } + }); + } if let LibraryItem::Sound(id) = row.item { resp.context_menu(|ui| { if ui.button(tr!("Delete Sound")).clicked() { diff --git a/src/stage.rs b/src/stage.rs index 162725ca..9333b993 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -241,19 +241,27 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } - let zoom = app.view.zoom; + let st_zoom = app.view.zoom; // Snap the stage origin to whole device pixels: tile edges then land exactly on screen // pixels, so texture filtering can't show seams between tiles. - let raw = canvas.center() + app.view.pan - size * zoom * 0.5; - let origin = pos2((raw.x * ppp).round() / ppp, (raw.y * ppp).round() / ppp); + let raw = canvas.center() + app.view.pan - size * st_zoom * 0.5; + let st_origin = pos2((raw.x * ppp).round() / ppp, (raw.y * ppp).round() / ppp); + let st_screen = |p: Vec2| pos2(st_origin.x + p.x * st_zoom, st_origin.y + p.y * st_zoom); + let stage_rect = Rect::from_min_size(st_origin, size * st_zoom); + // While a symbol is open (ADR 0045), tools and overlays work in its space, which the stage + // shows moved and scaled where its instance stands. + let edit_view = app.s.edit_view(); + let (origin, zoom) = match edit_view { + Some(v) => (st_origin + vec2(v.origin.x, v.origin.y) * st_zoom, st_zoom * v.scale), + None => (st_origin, st_zoom), + }; let to_screen = |p: Vec2| pos2(origin.x + p.x * zoom, origin.y + p.y * zoom); let to_stage = |p: Pos2| pos2((p.x - origin.x) / zoom, (p.y - origin.y) / zoom); - let stage_rect = Rect::from_min_size(origin, size * zoom); let painter = ui.painter_at(canvas); // View > Preview Through Camera: the stage shows the movie's picture (ADR 0027). Artwork // tools pause meanwhile (what they'd edit is in stage space, not where it shows). let preview = crate::camera_tool::previewing(app); - let cam_geo = crate::camera_tool::Geo { origin, zoom, stage_rect, preview }; + let cam_geo = crate::camera_tool::Geo { origin: st_origin, zoom: st_zoom, stage_rect, preview }; // ---- tools ---------------------------------------------------------------------------- @@ -664,9 +672,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { commit_text(app); let sp = to_stage(p); - // Raw artwork (ADR 0031): a stroke and the strokes joined to it, or a fill and its outline. - if !open_text_at(app, sp, 3.0 / zoom.max(1e-3)) { - app.run("element.select_connected", json!({"x": sp.x, "y": sp.y, "add": shift, "slop": 3.0 / zoom.max(1e-3)})); + let slop = 3.0 / zoom.max(1e-3); + if !open_text_at(app, sp, slop) { + match app.s.hit_test(to_v(sp), slop) { + // A symbol instance opens for editing in place (ADR 0045). + Some((layer, id)) if app.s.elements_on(layer).iter().any(|e| e.id == id && matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { .. })) => { + app.run("symbol.edit", json!({"id": id.0})); + } + // Raw artwork (ADR 0031): a stroke and the strokes joined to it, or a fill and + // its outline. + Some(_) => { + app.run("element.select_connected", json!({"x": sp.x, "y": sp.y, "add": shift, "slop": slop})); + } + // Empty space inside a symbol goes back up a level, as in Animate. + None if !app.s.editing.is_empty() => { + app.run("symbol.exit", json!({})); + } + None => {} + } } } if app.tool == Tool::Subselect @@ -738,18 +761,21 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } // Jobs are keyed by who draws them, so a renderer switch re-renders (old tiles stand in). let raster = app.stage_cache.service.as_ref().map_or(0, RenderService::raster_id); - // Tiles on a device-pixel grid at this zoom (ADR 0007). - let z = zoom * ppp; + // Tiles on a device-pixel grid at this zoom (ADR 0007), of what the stage shows: the + // document, or an open symbol in place (ADR 0045). + let z = st_zoom * ppp; let bg = app.s.doc.stage.background; let stage_px = ((size.x * z).ceil().max(1.0) as u32, (size.y * z).ceil().max(1.0) as u32); - let px = [(vis.min.x - origin.x) * ppp, (vis.min.y - origin.y) * ppp, (vis.max.x - origin.x) * ppp, (vis.max.y - origin.y) * ppp]; + let px = [(vis.min.x - st_origin.x) * ppp, (vis.min.y - st_origin.y) * ppp, (vis.max.x - st_origin.x) * ppp, (vis.max.y - st_origin.y) * ppp]; let visible = tiles_for(z, stage_px, px, 0, bg); - let onion = app.onion && !app.playing; - let state = app.s.state; + let pic = app.s.stage_picture(); + let editing = edit_view.is_some(); + let onion = app.onion && !app.playing && !editing; + let state = pic.state; // Render jobs take movie frames: the current scene starts at `start`. let start = app.s.doc.scene_start(app.s.scene); let frame = app.s.frame; - let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &app.s.doc, start + frame, t.view, onion).through_camera(preview); (t, j) }).collect(); + let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview); (t, j) }).collect(); let keys: Vec = jobs.iter().map(|(_, j)| j.key).collect(); let missing: Vec = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect(); @@ -810,33 +836,33 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // during playback, the next frames' visible tiles. if let Some(svc) = &app.stage_cache.service { let mut ahead: Vec = Vec::new(); - if app.playing { + if app.playing && !editing { let n = app.s.frame_count().max(1); for d in 1..=LOOKAHEAD.min(n - 1) { let f = (frame + d) % n; ahead.extend(jobs.iter().map(|(t, _)| make_job_for(raster, state, &app.s.doc, start + f, t.view, false).through_camera(preview))); } } else { - ahead.extend(tiles_for(z, stage_px, px, 1, bg).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job_for(raster, state, &app.s.doc, start + frame, t.view, onion).through_camera(preview))); + ahead.extend(tiles_for(z, stage_px, px, 1, bg).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview))); } svc.prefetch(ahead); } // Draw: tiles from earlier zooms/states that cover the view go first (scaled, as a // placeholder), then the current tiles on top. - let view_rect = [(vis.min.x - origin.x) / zoom, (vis.min.y - origin.y) / zoom, (vis.max.x - origin.x) / zoom, (vis.max.y - origin.y) / zoom]; + let view_rect = [(vis.min.x - st_origin.x) / st_zoom, (vis.min.y - st_origin.y) / st_zoom, (vis.max.x - st_origin.x) / st_zoom, (vis.max.y - st_origin.y) / st_zoom]; let overlaps = |r: &[f32; 4]| r[0] < view_rect[2] && r[2] > view_rect[0] && r[1] < view_rect[3] && r[3] > view_rect[1]; let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); let mut stale: Vec<&TileTex> = app.stage_cache.tiles.iter().filter(|t| !keys.contains(&t.key) && overlaps(&t.rect)).collect(); if ready < keys.len() { stale.sort_by_key(|t| t.used); for t in stale.iter().rev().take(96).rev() { - let r = Rect::from_min_max(to_screen(Vec2::new(t.rect[0], t.rect[1])), to_screen(Vec2::new(t.rect[2], t.rect[3]))); + let r = Rect::from_min_max(st_screen(Vec2::new(t.rect[0], t.rect[1])), st_screen(Vec2::new(t.rect[2], t.rect[3]))); painter.image(t.tex.id(), r, uv, Color32::WHITE); } } for t in app.stage_cache.tiles.iter().filter(|t| keys.contains(&t.key)) { - let r = Rect::from_min_max(to_screen(Vec2::new(t.rect[0], t.rect[1])), to_screen(Vec2::new(t.rect[2], t.rect[3]))); + let r = Rect::from_min_max(st_screen(Vec2::new(t.rect[0], t.rect[1])), st_screen(Vec2::new(t.rect[2], t.rect[3]))); painter.image(t.tex.id(), r, uv, Color32::WHITE); } @@ -863,7 +889,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if preview { // The movie's picture: stage-space overlays don't belong on it. painter.text(stage_rect.left_top() + vec2(0.0, -6.0), egui::Align2::LEFT_BOTTOM, tr!("Camera view"), crate::theme::font(crate::theme::Type::Caption), T.text_dim); - let badge = format!("{:.0}%", zoom * 100.0); + let badge = format!("{:.0}%", st_zoom * 100.0); painter.text(canvas.right_bottom() + vec2(-10.0, -8.0), egui::Align2::RIGHT_BOTTOM, badge, crate::theme::font(crate::theme::Type::Data), T.text_dim); crate::a11y::surface(ui, &resp, &tr!("Stage · previewing through the camera · {tool} tool · frame {frame}", tool = crate::i18n::t(app.tool.label()), frame = app.s.frame + 1)); return; @@ -876,7 +902,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); let dl = app.s.display_list(); for item in dl.items.iter().filter(|i| i.masks.is_some() || i.guide).take(2_000) { - let Some(layer) = app.s.doc.timeline(app.s.scene).layer(item.layer).filter(|l| item.guide || !l.locked) else { continue }; + let Some(layer) = app.s.timeline().layer(item.layer).filter(|l| item.guide || !l.locked) else { continue }; let stroke = Stroke::new(if item.guide { 2.0 } else { 1.5 }, to_color32(layer.color)); for pl in item.path.flatten(&to_px.mul(&item.transform), 0.5) { let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); @@ -1023,8 +1049,17 @@ 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: its registration point (ADR 0045; the way back is in the edit bar). + if edit_view.is_some() { + let c = to_screen(Vec2::ZERO); + for (a, b) in [(vec2(-8.0, 0.0), vec2(8.0, 0.0)), (vec2(0.0, -8.0), vec2(0.0, 8.0))] { + painter.line_segment([c + a, c + b], Stroke::new(3.0, Color32::WHITE)); + painter.line_segment([c + a, c + b], Stroke::new(1.0, T.ink)); + } + } + // zoom badge - let badge = format!("{:.0}%", zoom * 100.0); + let badge = format!("{:.0}%", st_zoom * 100.0); painter.text(canvas.right_bottom() + vec2(-10.0, -8.0), egui::Align2::RIGHT_BOTTOM, badge, crate::theme::font(crate::theme::Type::Data), T.text_dim); // Last, so the focus ring is drawn over the artwork. let selected = app.s.selection.len(); @@ -1143,7 +1178,7 @@ fn grab_mark(painter: &egui::Painter, p: Pos2, grab: Grab) { /// The raw shapes (parts of the layer's merged drawing) on the active layer. /// The raw shapes at the playhead, on every layer, with their layers. fn raw_ids(app: &App) -> std::collections::HashSet<(anicraft_engine::doc::LayerId, anicraft_engine::doc::ElementId)> { - let layers: Vec<_> = app.s.doc.timeline(app.s.scene).layers.iter().map(|l| l.id).collect(); + let layers: Vec<_> = app.s.timeline().layers.iter().map(|l| l.id).collect(); layers.into_iter().flat_map(|l| app.s.elements_on(l).into_iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).map(move |e| (l, e.id))).collect() } diff --git a/src/timeline.rs b/src/timeline.rs index 98376422..7ee59944 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -94,7 +94,7 @@ pub enum TlDrag { /// Range params for the frame commands when frames are selected: `{layers, frame, count}`. pub fn range_params(app: &App) -> Option { let sel = app.frame_sel?; - let layers = sel.layers(&app.s.doc.timeline(app.s.scene).layers); + let layers = sel.layers(&app.s.timeline().layers); if layers.is_empty() { return None; } @@ -109,7 +109,7 @@ pub const RANGE_COMMANDS: [&str; 7] = ["timeline.insert_frame", "timeline.remove /// Params for Paste Frames: the selection's top layer and first frame. pub fn paste_params(app: &App) -> Option { let sel = app.frame_sel?; - let top = *sel.layers(&app.s.doc.timeline(app.s.scene).layers).first()?; + let top = *sel.layers(&app.s.timeline().layers).first()?; Some(json!({"layer": top.0, "frame": sel.frames().0})) } @@ -157,7 +157,7 @@ fn transport(app: &mut App, ui: &mut egui::Ui) { } // Add Camera, as Animate has it on the timeline: on while the scene has a camera; a click // then takes it away (asking first when the camera moves; undoable). - let has = app.s.doc.timeline(app.s.scene).camera_layer().is_some(); + let has = app.s.timeline().camera_layer().is_some(); if icon_button(ui, if has { tr!("Remove camera") } else { tr!("Add camera") }, Some(has), Icon::Camera).clicked() { if has { app.request("camera.remove", json!({})); @@ -195,7 +195,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // A frame selection lives while the playhead is inside it and its layers exist. if let Some(sel) = app.frame_sel { let (f0, f1) = sel.frames(); - let gone = sel.layers(&app.s.doc.timeline(app.s.scene).layers).is_empty(); + let gone = sel.layers(&app.s.timeline().layers).is_empty(); if gone || app.playing || (app.tl_drag == TlDrag::None && !(f0..=f1).contains(&app.s.frame)) { app.frame_sel = None; } @@ -242,7 +242,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // rows and columns are painted, so cost is independent of document size. // Rows are the layers not inside a closed folder (`rows[r]` is row r's layer index). let rows: Vec = { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); (0..tl.layers.len()).filter(|&i| !app.tl_collapsed.iter().any(|f| tl.is_inside(i, *f))).collect() }; let n_layers = rows.len(); @@ -315,14 +315,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } // rows - let layers = app.s.doc.timeline(app.s.scene).layers.clone(); + let layers = app.s.timeline().layers.clone(); let active = app.s.layer; // Layers with selected artwork show a square in their colour after the name, as in // Animate: a selection can span layers (ADR 0044). let holding = app.s.selection.layers(); let rows_top = ruler.bottom(); let rows_bottom = body.bottom() - FOOTER_H; - let tl_now = app.s.doc.timeline(app.s.scene).clone(); + let tl_now = app.s.timeline().clone(); 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; @@ -501,7 +501,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if menus::check_item(ui, tr!("Mask"), layer.kind == LayerKind::Mask, !is_folder) { app.run("layer.toggle_mask", json!({"layer": layer.id.0})); } - let can_mask = layer.kind == LayerKind::Normal && app.s.doc.timeline(app.s.scene).mask_above(i).is_some(); + let can_mask = layer.kind == LayerKind::Normal && app.s.timeline().mask_above(i).is_some(); if menus::check_item(ui, tr!("Masked"), masked, can_mask || masked) { let ty = if masked { "normal" } else { "masked" }; app.run("layer.set_type", json!({"layer": layer.id.0, "type": ty})); @@ -511,7 +511,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let ty = if layer.kind == LayerKind::Guide { "normal" } else { "guide" }; app.run("layer.set_type", json!({"layer": layer.id.0, "type": ty})); } - let can_guide = layer.kind == LayerKind::Normal && app.s.doc.timeline(app.s.scene).guide_above(i).is_some(); + let can_guide = layer.kind == LayerKind::Normal && app.s.timeline().guide_above(i).is_some(); if menus::check_item(ui, tr!("Guided"), guided, can_guide || guided) { let ty = if guided { "normal" } else { "guided" }; app.run("layer.set_type", json!({"layer": layer.id.0, "type": ty})); From b30b7a445302a2c36462c61a645e6ed1d9ce266c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:08:32 -0700 Subject: [PATCH 007/402] test(engine): raw points and symbol editing timings (M1) --- crates/engine/src/rawpoints_tests.rs | 50 ++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/engine/src/rawpoints_tests.rs b/crates/engine/src/rawpoints_tests.rs index 17c94bdf..8c5d34ef 100644 --- a/crates/engine/src/rawpoints_tests.rs +++ b/crates/engine/src/rawpoints_tests.rs @@ -261,3 +261,53 @@ fn an_object_paths_smooth_anchor_keeps_its_handles_opposite() { let ElementKind::Shape(sh) = &el.kind else { panic!() }; assert_eq!(sh.path.point(2, 1), Some(k), "Alt moves the handle alone"); } + +#[test] +fn raw_points_timings() { + // ADR 0042's drawing: 12 × 12 outlined, rounded squares and a line across every row. + let mut s = raw_session(); + for i in 0..12 { + for j in 0..12 { + run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000", "radius": 6})); + } + run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"})); + } + run(&mut s, "edit.deselect", json!({})); + let n = s.visible_elements().len(); + let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let v = run(&mut s, "raw.add_point", json!({"x": 320, "y": 300})); + let add = ms(t); + let at = [v["x"].as_f64().unwrap_or(0.0), v["y"].as_f64().unwrap_or(0.0)]; + let t = std::time::Instant::now(); + run(&mut s, "raw.delete_points", json!({"points": [at]})); + let delete = ms(t); + let t = std::time::Instant::now(); + run(&mut s, "raw.convert_points", json!({"points": [[306, 300]], "smooth": true})); + let smooth = ms(t); + let h = handles_at(&s, Vec2::new(306.0, 300.0)).first().copied().unwrap_or_else(|| panic!("handles after Make Smooth")); + s.begin_gesture("Move Handle"); + let t = std::time::Instant::now(); + run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 1, "dy": 1, "merge": false})); + let pair = ms(t); + s.end_gesture(); + let t = std::time::Instant::now(); + for k in 0..100 { + let _ = s.execute("draw.snap", &json!({"x": 3 + k * 6, "y": 303, "snap": 10})); + } + let snap = ms(t) / 100.0; + // Inside a symbol: the whole drawing converted, opened in place, and its stage picture. + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Grid"})); + let t = std::time::Instant::now(); + run(&mut s, "symbol.edit", json!({})); + let open = ms(t); + let t = std::time::Instant::now(); + let pic = s.stage_picture(); + let picture = ms(t); + let a = anchors(&s).first().copied().unwrap_or_else(|| panic!("anchors inside")); + let t = std::time::Instant::now(); + run(&mut s, "raw.move_point", json!({"x": a.x, "y": a.y, "to_x": a.x - 5.0, "to_y": a.y})); + let inside = ms(t); + eprintln!("{n} raw shapes; add point {add:.2} ms, delete point {delete:.2} ms, make smooth {smooth:.2} ms, smooth handle frame {pair:.2} ms, draw snap {snap:.3} ms; inside a symbol: open {open:.2} ms, stage picture {picture:.2} ms (frame {}), point move {inside:.2} ms", pic.frame); +} From 37583e588170465a43219749bdff9ee2c0fd71d3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:09:46 -0700 Subject: [PATCH 008/402] docs: ADR 0045 raw points and symbols in place; ADR 0041/0042 lists, roadmap, changelog; issue #42 (M1) --- CHANGELOG.md | 20 +++ .../0041-selection-tool-on-raw-drawings.md | 4 +- ...042-subselection-and-merging-everywhere.md | 14 +- ...aw-points-and-raw-shapes-inside-symbols.md | 157 ++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 15 +- 6 files changed, 198 insertions(+), 13 deletions(-) create mode 100644 docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 78f03c88..6d783472 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ ## Unreleased +* **Raw points, snapping while drawing, and symbols edited in place** (ADR 0045, issue #42, M1). + * **Add a point** on a merged drawing's line or fill edge with the Pen's Alt-click or a + Subselection double-click: every shape on that edge gets it, and the curve keeps its shape. + * **Delete points** with Delete (or the right-click menu): the shapes that share each point are + joined across it, so a fill and its outline stay together; deleting a line's last points + removes it. A point where three or more lines meet is kept, and the status bar says so. + * **Make Smooth / Make Corner** on raw points. Dragging a handle of a smooth point keeps the + other handle in line (on drawing objects too); **Alt** moves it alone. + * The **Line, Rectangle, Oval, PolyStar and Pen** tools snap their points to points, lines and + fill edges within 10 screen pixels, with a ring where they will snap. **Snap to Objects** is + now Ctrl+Shift+/, as in Animate. + * **Double-click a symbol instance** (or press Ctrl+E, or right-click it in the Library › Edit + Symbol) to edit it in place: the rest of the stage dims, the timeline shows the symbol's + layers, and merge drawing, the Selection and Subselection tools and every other tool work + inside it as on the stage. The edit bar shows `Scene 1 › Symbol`; click the scene, press + Ctrl+E or double-click empty stage to go back. Undo returns to the symbol where a change was + made. Rotated instances open upright. + * 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`; `doc.info` lists + the open symbols. * **ActionScript that controls the timeline now runs** (ADR 0013 tier 2). Frame scripts in Animate documents, and ones you type in the Actions panel, play in Test Movie and in the HTML canvas export when they use the ActionScript 3.0 most animation and e-learning files diff --git a/docs/adr/0041-selection-tool-on-raw-drawings.md b/docs/adr/0041-selection-tool-on-raw-drawings.md index 8093ca7d..2eeb622e 100644 --- a/docs/adr/0041-selection-tool-on-raw-drawings.md +++ b/docs/adr/0041-selection-tool-on-raw-drawings.md @@ -125,8 +125,8 @@ was copied. won). The move is at most 0.2, and merging again changes nothing (tested). * Not in this slice: * ~~selecting across layers~~ (ADR 0044); - * snapping while drawing with the shape tools; + * ~~snapping while drawing with the shape tools~~ (ADR 0045); * ~~a Snap to Objects switch~~ (ADR 0042); * ~~Subselection anchors and handles of connected raw shapes~~ (ADR 0042); - * bending or moving points of raw shapes inside symbols; + * ~~bending or moving points of raw shapes inside symbols~~ (ADR 0045); * the Free Transform tool's handles on raw parts. diff --git a/docs/adr/0042-subselection-and-merging-everywhere.md b/docs/adr/0042-subselection-and-merging-everywhere.md index 747ceb49..dd93c451 100644 --- a/docs/adr/0042-subselection-and-merging-everywhere.md +++ b/docs/adr/0042-subselection-and-merging-everywhere.md @@ -150,11 +150,11 @@ nothing was copied. * A Paint Bucket fill in merge drawing lies exactly along its lines. Deleting a line later joins fills of one colour, as in Animate. * Not in this slice: - * deleting raw anchors (Delete says so), and adding them; - * Make Smooth and Make Corner on raw anchors; - * smooth handle pairs (a handle moves alone, as on drawing objects); + * ~~deleting raw anchors (Delete says so), and adding them~~ (ADR 0045); + * ~~Make Smooth and Make Corner on raw anchors~~ (ADR 0045); + * ~~smooth handle pairs (a handle moves alone, as on drawing objects)~~ (ADR 0045); * width profiles in the merge; - * Subselection inside symbols; - * a default shortcut for Snap to Objects; - * snapping while drawing with the shape tools; - * a marquee across layers (ADR 0041). + * ~~Subselection inside symbols~~ (ADR 0045: symbols open for editing in place); + * ~~a default shortcut for Snap to Objects~~ (ADR 0045: Ctrl+Shift+/); + * ~~snapping while drawing with the shape tools~~ (ADR 0045); + * ~~a marquee across layers~~ (ADR 0044, for the Selection tool). diff --git a/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md b/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md new file mode 100644 index 00000000..e3d7d6b1 --- /dev/null +++ b/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md @@ -0,0 +1,157 @@ +# ADR 0045: Raw points, snapping while drawing, and raw shapes inside symbols + +* Status: accepted (2026-11-10) +* Relates to: ADR 0031 (merge drawing), ADR 0041 (Selection tool on raw drawings), ADR 0042 + (Subselection and merging everywhere), ADR 0044 (selection across layers), ADR 0004 + (destructive actions), ADR 0001 (undo snapshots), issue #42 (sections 1 and 3) + +## Context + +ADR 0042 left these out of its slice: + +* adding and deleting raw anchors (Delete only said it could not); +* Make Smooth and Make Corner on raw anchors, and smooth handle pairs (a handle moved alone); +* snapping while drawing with the shape tools; +* a default shortcut for Snap to Objects; +* Subselection (and, from ADR 0041, the Selection tool) inside symbols. + +The last one needed more than the raw tools: AniCraft had no way to edit a symbol's timeline at +all. In Animate a double-click on an instance opens the symbol **in place**: the rest of the +stage dims, the timeline shows the symbol's layers, every tool works inside it, and the edit bar +says where you are (`Scene 1 › Badge`). + +Behaviour was learned from the issue, Adobe's public help pages and watching the program; +nothing was copied. + +## Decision + +1. **Points are positions, as in ADR 0042.** A shared point is stored once in each raw shape + that has it, so each command finds every copy near the position (within 1.5 × `SNAP`) and + changes them alike. The pure parts are in `anicraft_geom::raw`: a path as subpaths of + segments (`subpaths`, `from_subpaths`), the edges leaving a point (`edges_at`, + `distinct_edges`), and the edits below. + +2. **Adding a point** (`raw.add_point {x, y, slop?}`, the Pen's Alt-click and the Subselection + double-click on a raw line or fill edge) splits the segment there in every raw shape that has + that edge (de Casteljau, so the curve is unchanged; tested analytically). Nothing moved, so + nothing merges. A point added on a **straight** line lasts while it is used: once a merge + finds it still on a straight run (it was never moved), it is simplified away, as issue #42's + continuous simplification asks. On a curve it stays. + +3. **Deleting points** (`raw.delete_points {points}`, Delete or Backspace with Subselection, + the point menu) works on the drawing's edges at each point, not on one shape: + * **Two edges** (a corner, or a point along a line): they become one edge from the far end of + one to the far end of the other: two lines a line, anything else the cubic that fits both + best, keeping the directions they leave their far ends in (`join`, the fit `Path::merge_at` + uses; deleting a point that adding made gives the curve back). **Every copy** of either + edge becomes the new one: a fill's outline loses the corner, and a stroke that ended there + now runs along the whole new edge. The drawing stays connected; the merge that follows + joins the strokes that now overlap. + * **One edge** (the free end of lines): the segment there goes. + * **Three or more** (where lines cross or a line stands on another): the point is kept and + the editor says why. Joining three edges into one has no single right answer. + * What is left with nothing to show is removed: a subpath with no segments or no length, a + filled outline with no area; a shape with no subpaths. So deleting a line's last points + removes it. + * One command, so one undo step (ADR 0004: undoable, no confirmation), merged again + (`remerge_in_place`) like every raw edit. + + *Rejected:* deleting the point from each shape on its own (`Path::remove_anchor` per copy). + Each shape would fit its own curve, and a fill and its outline would part. + +4. **Make Smooth and Make Corner** (`raw.convert_points {points, smooth}`, the point menu): + smooth turns a point with two edges into one whose handles lie on one line, along the + direction between the far ends, a third of each chord long (`Path::make_smooth`'s rule); + corner draws every curve's handle there in onto the point. Each changed edge changes in + every shape (`follow_edge`, built on ADR 0041's `follow`). A smooth point on a straight line + is simplified away by the merge, as in point 2. + +5. **Smooth handle pairs.** Dragging one handle of a smooth point (its two handles on one line, + opposite, within 3°) turns the other to stay opposite, keeping its length: `raw.move_handle` + and `path.move_points` take `smooth?: bool` (default true); **Alt** breaks the pair. The + other handle is found among the edges at the point: exactly one other curve whose handle is + opposite (a junction has no pair). Drawing objects behave the same, so both kinds of shape + edit alike. + +6. **Snapping while drawing.** `draw.snap {x, y, snap}` (no undo step) says where a point drawn + at (x, y) goes: the nearest anchor within `snap`, else the nearest point on a line or fill + edge, of what the stage shows near it (display-list items whose bounds reach the point, so it + costs nothing far away). The Line, Rectangle, Oval, PolyStar and Pen tools snap their start + and end (the Pen its knots, never its handles) within 10 screen pixels, and show the snap + ring as you hover, where a press would start. Shift's constraint wins over snapping. Off when + Snap to Objects is off (`ToolStyle::snap_radius`). Scripts pass exact coordinates; the query + is there for them too. + +7. **Snap to Objects is Ctrl+Shift+/**, Animate's chord. Where `/` and `?` share a key (US, UK + layouts), the key arrives as `?`, so `Ctrl+Shift+?` is bound too (an engine alias). Neither + clashed with a default (the keymap's clash test). ADR 0042's worry was the layout: on layouts + where `/` needs Shift (German: Shift+7), Ctrl+Shift+that key arrives as `/`, which the first + binding catches. + +8. **Editing a symbol in place** (`crates/engine/src/editing.rs`): + * The session keeps a stack of open symbols (`Session::editing`). While one is open, + **every command works on its timeline** (`Session::timeline`; the 86 places that read + the scene's timeline now read this): the active layer, the playhead and the selection are + its, positions are in its space, the display list (picking, bounds, snapping) is its + timeline evaluated alone (`anicraft_doc::evaluate_timeline`). So merge drawing, the + Selection tool, Subselection, raw points, the Paint Bucket and the rest behave inside a + symbol exactly as on the stage: they are the same commands. + * `symbol.edit {id?, symbol?}` (Edit › Edit Symbols, **Ctrl+E**, a **double-click** on an + instance with the Selection tool) opens the selected or given instance where it stands, at + the frame a graphic shows (a movie clip or button at its first); `{symbol}` (the Library's + Edit Symbol) opens one alone at the stage's centre. Ctrl+E with no instance selected goes + back to the document, as in Animate. `symbol.exit {all?}` (Edit › Edit Document, a + double-click on empty stage, the edit bar's path) closes one level or all, selecting the + instance again. + * Which symbol is open is view state, but **undo snapshots keep it**, so undoing a change + made inside a symbol opens it again: the layer, frame and selection in the step belong to + that timeline. A symbol that goes away (an undo, a deletion) closes. Changing scene closes + every symbol. Placing or pasting a symbol inside itself (or inside a symbol it uses) is + refused; a camera can't be added inside a symbol. + * **What the stage draws** (`Session::stage_picture`): a picture document whose scene holds + the open timeline at its playhead where the instance stands, over each timeline below it + (without the instance it was opened from) at 35 % opacity. They are graphic instances of + copies of those timelines, so the oracle and the GPU stage draw them unchanged, and the + render cache keys them by a hash of the state and the open levels. + * **The editor's view follows the instance** when it is only moved and scaled evenly: the + stage's screen mapping becomes `origin + zoom · (t + k · p)`, which the shell's existing + origin-and-zoom mapping holds exactly, so every tool, overlay and snap radius works + unchanged. A rotated, skewed or flipped instance opens upright and unscaled at its + registration point, with the artwork around it hidden (a picture that did not line up with + the tools would mislead). + * The edit bar shows `Scene 1 › Badge › Layer 1`; a click on a symbol goes back to it, the + scene's menu goes back to the scene. A crosshair marks the registration point. + + *Rejected:* a full affine view mapping in the shell (rotated in-place editing). Every tool's + screen-space overlay assumes an axis-aligned mapping (selection boxes, Free Transform + handles, marquees); bending them all is a slice of its own. *Rejected:* addressing a symbol's + timeline through a `symbol` param on each command (as the Actions panel's commands do): + every command and tool would need it, and the tools would still need a view of the symbol. + +## Consequences + +* Issue #42's Subselection (§3) is complete on raw drawings, inside symbols too. The drawing + tools snap as the issue's §1 describes. +* Measured on 744 raw shapes (12 × 12 outlined, rounded squares and 12 lines; optimised debug + build, `raw_points_timings`): + + | Operation | Time | + |---|---| + | Add a point | 0.29 ms | + | Delete a point (joined, merged again) | 0.30 ms | + | Make Smooth | 0.34 ms | + | Smooth handle pair drag frame | 0.14 ms | + | Drawing snap (every frame while hovering) | 0.02 ms | + | Open a symbol of all 744 shapes | 0.04 ms | + | Its stage picture | 0.01 ms | + | A point move inside it | 0.52 ms | + +* `panic_hunt_every_command` also starts inside an open symbol with raw drawings, and renders + the stage picture. +* Not in this slice: + * in-place editing of rotated, skewed or flipped instances (they open upright, alone); + * the parent symbol's frame moving with the open one (a nested graphic shows the frame it + was opened at), and onion skin while a symbol is open; + * deleting a point where three or more edges meet; + * width profiles in the merge (ADR 0042); + * a marquee across layers with the Subselection tool (Animate keeps it on one layer too). diff --git a/docs/adr/README.md b/docs/adr/README.md index 8ec5d830..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 | -| 0045 | m1/raw-points | Raw points: add, delete, smooth pairs, snapping while drawing, raw shapes inside symbols | diff --git a/docs/roadmap.md b/docs/roadmap.md index 8dcbfdfe..8a12ac6b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -11,7 +11,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). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, 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, onion skin (±2 frames), looping playback. **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. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path`). Not yet: anchors tied to frames (spatial keys, a model change: ADR 0038), 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. **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: a marquee across several layers, snapping while drawing, width profiles in the merge, deleting or adding raw anchors, smooth handle pairs. **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. | +| 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. **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 the Library's Edit Symbol) 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 inside a symbol. **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. | | 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. | @@ -100,8 +100,17 @@ Next, in order: segment or fill moves what is connected, arrow keys; Snap to Objects (View › Snapping, the magnet); the Paint Bucket's fills (exact, up to the lines) and pasted raw shapes merge; raw shapes from Animate files come in raw; gradients take part in the merge. Not yet: - width profiles in the merge, deleting or adding raw anchors, smooth handle pairs, a - default Snap to Objects shortcut. + width profiles in the merge. + * ~~**Raw points and raw shapes inside symbols** (ADR 0045)~~ ✅: add a point on a raw line + or fill edge (Pen Alt-click, Subselection double-click), shared by every shape on the edge; + delete raw points (the shapes on them joined across, the drawing kept connected; a line's + last points remove it); Make Smooth / Corner on raw points; smooth handle pairs (Alt breaks + them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap while + drawing; Snap to Objects is Ctrl+Shift+/; **symbols open for editing in place** + (double-click, Ctrl+E, the Library's Edit Symbol; the edit bar's path back), where merge + drawing, Selection and Subselection work as on the stage. Not yet: in-place editing of + rotated instances (they open upright), deleting a point where three edges meet, onion skin + inside a symbol. 1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, ~~shape tweens~~ ✅, ~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), ~~text~~ ✅ (one style per line; per-character styles with the text model), motion tweens, and ~~a larger self-authored From c67a6c80d44655fbab8ab925719d17b0cb5a33ec Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:09:51 -0700 Subject: [PATCH 009/402] docs: credit the curve fit raw point deletion uses (M1) --- ATTRIBUTION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 654ef16d..3481b5bd 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -103,7 +103,7 @@ OR Apache-2.0) is noted in the table. | Exact clipping of filled paths by a convex polygon | `crates/geom/src/clip.rs` | I. E. Sutherland and G. W. Hodgman, "Reentrant Polygon Clipping", CACM 17(1), 1974, extended to Bézier segments (de Casteljau subdivision, roots bracketed by critical points) | Published algorithm; no code taken. | | Shape morphing (cubic normalization, subdivision to equal segment counts, winding and start-point alignment) | `crates/geom/src/morph.rs` | Standard curve-blending techniques from the public computer-graphics literature (de Casteljau subdivision, exact degree elevation) | | | Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | | -| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. | +| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`; deleting a raw drawing's point joins its edges, `raw::join`, ADR 0045) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs`, `crates/geom/src/raw.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. | | Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). | | Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. | | Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. | From 6586de30bd6afd34534beab0c8dc6ae25dc664c9 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:23:52 -0700 Subject: [PATCH 010/402] fix(geom): pass the edge matcher by value, for newer clippy (M1) --- crates/geom/src/raw.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/geom/src/raw.rs b/crates/geom/src/raw.rs index a16acba5..b1f7a057 100644 --- a/crates/geom/src/raw.rs +++ b/crates/geom/src/raw.rs @@ -384,7 +384,7 @@ pub fn delete_anchor(subs: &mut [Sub], at: Vec2, edges: &[Seg], joined: Option<& _ => false, } } - Vertex::Start => match (s.segs.first().and_then(&which), edges.len()) { + Vertex::Start => match (s.segs.first().and_then(which), edges.len()) { // The new first segment ends where the old one did. (Some(a), 2) => match (toward(1 - a), s.segs.first_mut()) { (Some(n), Some(first)) => { From 272e1f49043bcbe7422f30e3f848b8991b251eab Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:37:21 -0700 Subject: [PATCH 011/402] docs(adr): reserve ADR 0049 for motion path anchors pinned to frames (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..332df53a 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 | +| 0049 | m2/path-pins | Motion path anchors pinned to frames | From 5c9e4e0f6ff67273577f369ebbd2ff7ba19ebd5c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:44:37 -0700 Subject: [PATCH 012/402] feat(doc): motion path anchors pinned to frames, timed leg by leg (M2) --- crates/doc/src/lib.rs | 2 +- crates/doc/src/motion.rs | 615 +++++++++++++++++++++++++++++++++++++-- crates/geom/src/walk.rs | 19 ++ 3 files changed, 606 insertions(+), 30 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 97f0d8e4..bfdfaf64 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -26,7 +26,7 @@ pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; pub use easing::Easing; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; -pub use motion::{MotionTween, OnPath, Property, PropertyKey, Props, Track, motion_path}; +pub use motion::{MotionTween, OnPath, 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}; diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 60123b4b..1c36ab2f 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -13,8 +13,16 @@ //! *when* it gets where: the share of the way along the path at a frame is the share of the //! distance the X/Y curves have covered by then. With *orient to path* the object also turns //! as the path turns. Without a path the X/Y curves place the object, as before. +//! +//! Anchors of the path may be *pinned* to frames (ADR 0049): the object passes a pinned anchor +//! exactly on its frame, and the X/Y keys there hold the anchor's place. The ends are always +//! pinned, to the first and last position keys. Pins cut the motion into legs; on each leg the +//! X/Y curves time the object along the stretch of path between its two pinned anchors, as they +//! 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 anicraft_geom::edit::ANCHOR; use anicraft_geom::walk::CurveWalk; use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2}; use serde::{Deserialize, Serialize}; @@ -258,6 +266,36 @@ impl Track { } } +/// A motion path anchor pinned to a frame (ADR 0049): the object passes the anchor exactly +/// then. Only anchors between the ends are stored; the ends are pinned to the first and last +/// position keys. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Pin { + /// Frames from the span's first frame. + pub frame: u32, + /// The anchor: path command `anchor` (0 is the start). + pub anchor: u32, +} + +/// Why an anchor can't be pinned (or a pin added) where asked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PinError { + /// The tween has no motion path. + NoPath, + /// No such anchor on the path. + NoAnchor, + /// An end: always pinned to the first or last position key. + End, + /// The frame isn't strictly between the first and last position keys (these frames). + Outside(u32, u32), + /// Pins keep the path's order (a later frame on a later anchor); this one is in the way. + Order(Pin), + /// The object is off the path at that frame (an ease overshooting an end). + OffPath, + /// The path holds as many segments as it may. + Full, +} + /// A motion tween on a keyframe span (see the module docs). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MotionTween { @@ -275,6 +313,10 @@ pub struct MotionTween { /// Orient to path: the object turns as the path turns (relative to its turn at the start). #[serde(default, skip_serializing_if = "is_false")] pub orient: bool, + /// Anchors between the ends pinned to frames (ADR 0049), by frame; both frames and anchors + /// increase. Files from before pins have none: only the ends are pinned. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pins: Vec, } fn is_false(b: &bool) -> bool { @@ -350,6 +392,9 @@ pub struct OnPath<'a> { keys: Vec<(f32, Vec2)>, /// `cum[i]`: chord length from the first position key to key `i`. cum: Vec, + /// Where the legs start and end: the first position key, each pin and the last position key, + /// as an index into `keys` and the distance along the path of the anchor pinned there. + stations: Vec<(usize, f32)>, /// Direction of travel at the start, radians. start_angle: f32, } @@ -359,34 +404,46 @@ impl OnPath<'_> { &self.walk } - /// The share of the path covered `frame` frames into the span: 0 up to the first position - /// key (and without two), 1 from the last; an overshooting ease may leave 0..1 in between. - /// Where the chords add up to nothing (a path back to its start) the object keeps an even - /// pace between the first and last position keys. + /// The share of the path covered `frame` frames into the span (see [`OnPath::distance`]). pub fn progress(&self, frame: f32) -> f32 { + let l = self.walk.length(); + if l > 0.0 { self.distance(frame) / l } else { 0.0 } + } + + /// Distance along the path at `frame`: 0 up to the first position key (and without two), the + /// whole length from the last; an overshooting ease may go beyond in between. + /// + /// The pins cut the span into legs, each from one pinned anchor to the next. On a leg, the + /// position keys inside it split it again; on each of those pieces the X/Y curves run from + /// one key's position to the next, and how far along that chord they are (signed) is how far + /// along the piece's share of the leg's stretch of path the object is, the shares being the + /// chords' lengths. Where a leg's chords add up to nothing (a loop) the object keeps an even + /// pace across it. With only the ends pinned this is ADR 0030's timing, number for number. + pub fn distance(&self, frame: f32) -> f32 { + let l = self.walk.length(); let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return 0.0 }; if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 { return 0.0; } if frame >= last.0 { - return 1.0; - } - let total = self.cum.last().copied().unwrap_or(0.0); - if total <= 1e-4 { - return (frame - first.0) / (last.0 - first.0); + return l; } let i = self.keys.partition_point(|k| k.0 <= frame).saturating_sub(1); - let (Some(a), Some(b)) = (self.keys.get(i), self.keys.get(i + 1)) else { return 1.0 }; - let chord = b.1 - a.1; - let len = chord.length(); - let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 }; - let p = (self.cum.get(i).copied().unwrap_or(0.0) + along) / total; - if p.is_finite() { p } else { 0.0 } - } - - /// Distance along the path at `frame` (beyond the ends while an ease overshoots them). - pub fn distance(&self, frame: f32) -> f32 { - self.progress(frame) * self.walk.length() + let leg = self.stations.partition_point(|st| st.0 <= i).saturating_sub(1); + let (Some(&(ka, sa)), Some(&(kb, sb))) = (self.stations.get(leg), self.stations.get(leg + 1)) else { return l }; + let (Some(a), Some(b), Some(fa), Some(fb)) = (self.keys.get(i), self.keys.get(i + 1), self.keys.get(ka), self.keys.get(kb)) else { return l }; + let c0 = self.cum.get(ka).copied().unwrap_or(0.0); + let total = self.cum.get(kb).copied().unwrap_or(0.0) - c0; + let p = if total <= 1e-4 { + (frame - fa.0) / (fb.0 - fa.0) + } else { + let chord = b.1 - a.1; + let len = chord.length(); + let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 }; + (self.cum.get(i).copied().unwrap_or(0.0) - c0 + along) / total + }; + let p = if p.is_finite() { p } else { 0.0 }; + sa + p * (sb - sa) } /// The registration point at `frame`. Overshooting an end carries on along the path's @@ -414,7 +471,7 @@ impl OnPath<'_> { impl MotionTween { pub fn new(target: ElementId) -> MotionTween { - MotionTween { target, tracks: Vec::new(), path: None, orient: false } + MotionTween { target, tracks: Vec::new(), path: None, orient: false, pins: Vec::new() } } /// The first and last frames holding an X or Y key. @@ -433,18 +490,32 @@ impl MotionTween { /// path. pub fn on_path(&self, base: &Props) -> Option> { let walk = CurveWalk::new(self.path.as_ref()?)?; + let pins = self.live_pins(); let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); + // A pin's frame holds X/Y keys (commands see to it); a leg ends there all the same. + frames.extend(pins.iter().map(|p| p.frame)); frames.sort_unstable(); frames.dedup(); - let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, self.trace_at(base, f as f32))).collect(); + let keys: Vec<(f32, Vec2)> = frames.iter().map(|&f| (f as f32, self.trace_at(base, f as f32))).collect(); let mut cum = Vec::with_capacity(keys.len()); let mut d = 0.0f32; for (i, k) in keys.iter().enumerate() { d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1)); cum.push(d); } + let mut stations = vec![(0usize, 0.0f32)]; + for pin in &pins { + if let (Ok(i), Some(s)) = (frames.binary_search(&pin.frame), walk.anchor_distance(pin.anchor as usize)) + && stations.last().is_some_and(|l| l.0 < i) + { + stations.push((i, s)); + } + } + if keys.len() > 1 { + stations.push((keys.len() - 1, walk.length())); + } let t = walk.tangent(0.0); - Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum }) + Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum, stations }) } /// The registration point on each of the span's first `frames` frames (at most a day of @@ -460,13 +531,21 @@ impl MotionTween { /// A motion path through the X/Y curves' positions at their keys, as straight segments: /// the path a tween without one shows, made editable. `None` when the object doesn't move. pub fn path_from_tracks(&self, base: &Props) -> Option { + self.path_and_pins_from_tracks(base).map(|(p, _)| p) + } + + /// [`MotionTween::path_from_tracks`] with the position keys between the ends pinned to the + /// anchors they made (the first key at a place, where the object holds still a while). + pub fn path_and_pins_from_tracks(&self, base: &Props) -> Option<(Path, Vec)> { let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); frames.sort_unstable(); frames.dedup(); let mut pts: Vec = Vec::new(); + let mut pins = Vec::new(); for f in frames.into_iter().take(MAX_PATH_SEGMENTS + 1) { let q = self.trace_at(base, f as f32); if pts.last().is_none_or(|l| l.distance(q) > 1e-3) { + pins.push(Pin { frame: f, anchor: pts.len() as u32 }); pts.push(q); } } @@ -476,16 +555,64 @@ impl MotionTween { for q in rest { p.line_to(*q); } - motion_path(&p) + let path = motion_path(&p)?; + let n = path.cmds.len(); + pins.retain(|p| p.anchor > 0 && (p.anchor as usize) + 1 < n); + Some((path, pins)) + } + + /// The pins in force: between the ends in both frame and anchor, frames and anchors + /// increasing. Others are ignored (and dropped when a file is loaded). + pub fn live_pins(&self) -> Vec { + let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return Vec::new() }; + let n = path.cmds.len(); + let mut out: Vec = Vec::new(); + for p in &self.pins { + let inside = p.frame > f0 && p.frame < f1 && p.anchor > 0 && (p.anchor as usize).saturating_add(1) < n; + if inside && out.last().is_none_or(|q| q.frame < p.frame && q.anchor < p.anchor) { + out.push(*p); + } + } + out + } + + /// Every anchor tied to a frame, in order: the start at the first position key, the pins, + /// and the end at the last. A tween without a path of its own gives those of the straight + /// path its X/Y curves trace. Empty while the object doesn't move. + pub fn pinned_anchors(&self, base: &Props) -> Vec { + let Some((f0, f1)) = self.position_range().filter(|(a, b)| b > a) else { return Vec::new() }; + let (n, pins) = match &self.path { + Some(p) => (p.cmds.len(), self.live_pins()), + None => match self.path_and_pins_from_tracks(base) { + Some((p, pins)) => (p.cmds.len(), pins), + None => return Vec::new(), + }, + }; + let mut v = Vec::with_capacity(pins.len() + 2); + v.push(Pin { frame: f0, anchor: 0 }); + v.extend(pins); + v.push(Pin { frame: f1, anchor: n.saturating_sub(1) as u32 }); + v } /// Gives the tween motion path `path` (made a [`motion_path`]; false when nothing usable /// is left). Its ends become the X/Y keys at the first and last position keys, or at the /// span's first frame and frame `last` when there are none, so the curves start and end - /// where the path does. + /// where the path does; each pinned anchor's place becomes the X/Y keys on its frame. + /// + /// A tween without a path of its own shows the straight one through its position keys, + /// which are pinned to its anchors: a path with as many anchors is that one edited, and + /// keeps them pinned. Pins on anchors the new path doesn't have are let go, with their keys. pub fn set_path(&mut self, path: &Path, base: &Props, last: u32) -> bool { let Some(p) = motion_path(path) else { return false }; let Some((a, b)) = path_ends(&p) else { return false }; + if self.path.is_none() + && self.pins.is_empty() + && let Some((implied, pins)) = self.path_and_pins_from_tracks(base) + && implied.cmds.len() == p.cmds.len() + { + self.pins = pins; + } let (f0, f1) = match self.position_range() { Some((f0, f1)) if f1 > f0 => (f0, f1), _ if last > 0 => (0, last), @@ -501,7 +628,156 @@ impl MotionTween { self.set_key(prop, f1, v1, base.get(prop)); } } + let n = p.cmds.len(); self.path = Some(p); + let (keep, gone): (Vec, Vec) = self.pins.iter().partition(|q| q.anchor > 0 && (q.anchor as usize).saturating_add(1) < n); + self.pins = keep; + for q in gone { + self.remove_pin_keys(q.frame); + } + self.sync_pins(base); + true + } + + /// Writes each pinned anchor's place as the X/Y keys on its frame (leaving keys alone that + /// already hold it, so editing elsewhere keeps the timing exactly). + fn sync_pins(&mut self, base: &Props) { + let Some(path) = self.path.clone() else { return }; + for pin in self.live_pins() { + let Some(q) = path.point(pin.anchor as usize, ANCHOR) else { continue }; + for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] { + let holds = self.track(prop).and_then(|t| t.key_at(pin.frame).and_then(|i| t.keys.get(i))).is_some_and(|k| k.value == v); + if !holds { + self.set_key(prop, pin.frame, v, base.get(prop)); + } + } + } + } + + /// Removes the X/Y keys a pin held on `frame`, unless that frame is an end's. + fn remove_pin_keys(&mut self, frame: u32) { + if self.position_range().is_some_and(|(f0, f1)| f0 < frame && frame < f1) { + self.remove_track_key(Property::X, frame); + self.remove_track_key(Property::Y, frame); + } + } + + /// Pins anchor `anchor` to `frame`: the object passes it exactly then, and the X/Y keys on + /// that frame hold its place. A pin already on that frame, or that anchor's pin on another + /// frame, gives way. + pub fn pin(&mut self, anchor: usize, frame: u32, base: &Props) -> Result<(), PinError> { + let Some(path) = &self.path else { return Err(PinError::NoPath) }; + let n = path.cmds.len(); + if anchor >= n { + return Err(PinError::NoAnchor); + } + if anchor == 0 || anchor + 1 == n { + return Err(PinError::End); + } + let (f0, f1) = self.position_range().unwrap_or((0, 0)); + if !(f0 < frame && frame < f1) { + return Err(PinError::Outside(f0, f1)); + } + let Some(q) = path.point(anchor, ANCHOR) else { return Err(PinError::NoAnchor) }; + let a = anchor as u32; + let live = self.live_pins(); + if let Some(p) = live.iter().find(|p| p.frame != frame && p.anchor != a && (p.frame < frame) != (p.anchor < a)) { + return Err(PinError::Order(*p)); + } + self.pins = live; + if let Some(old) = self.pins.iter().find(|p| p.anchor == a && p.frame != frame).copied() { + self.unpin(old.frame); + } + self.pins.retain(|p| p.frame != frame); + let i = self.pins.partition_point(|p| p.frame < frame); + self.pins.insert(i, Pin { frame, anchor: a }); + for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] { + self.set_key(prop, frame, v, base.get(prop)); + } + Ok(()) + } + + /// Pins the path where the object is on `frame`: on the anchor there, or on a new one (the + /// path's shape unchanged). The anchor pinned. + pub fn pin_here(&mut self, frame: u32, base: &Props) -> Result { + if self.path.is_none() { + return Err(PinError::NoPath); + } + let (f0, f1) = self.position_range().unwrap_or((0, 0)); + if !(f0 < frame && frame < f1) { + return Err(PinError::Outside(f0, f1)); + } + if let Some(p) = self.live_pins().into_iter().find(|p| p.frame == frame) { + return Ok(p.anchor as usize); + } + let (s, l, (cmd, t)) = { + let op = self.on_path(base).ok_or(PinError::NoPath)?; + let s = op.distance(frame as f32); + (s, op.walk().length(), op.walk().locate(s)) + }; + if !(0.0..=l).contains(&s) { + return Err(PinError::OffPath); + } + let mut trial = self.clone(); + let anchor = if t <= 1e-3 { + cmd.saturating_sub(1) + } else if t >= 1.0 - 1e-3 { + cmd + } else { + let Some(path) = trial.path.as_mut() else { return Err(PinError::NoPath) }; + if path.cmds.len() > MAX_PATH_SEGMENTS { + return Err(PinError::Full); + } + if !path.split_segment(cmd, t) { + return Err(PinError::OffPath); + } + // The new anchor ends the first half; the anchors after it move up one. + for p in &mut trial.pins { + if p.anchor as usize >= cmd { + p.anchor += 1; + } + } + cmd + }; + trial.pin(anchor, frame, base)?; + *self = trial; + Ok(anchor) + } + + /// Lets the pin on `frame` go: its X/Y keys go with it and its anchor shapes the path only + /// (ADR 0038's behaviour). The pin, if there was one. + pub fn unpin(&mut self, frame: u32) -> Option { + let i = self.pins.iter().position(|p| p.frame == frame)?; + let pin = self.pins.remove(i); + self.remove_pin_keys(frame); + Some(pin) + } + + /// Moves anchor `anchor` (its handles with it) by `d`; an end or a pin takes its keys along. + pub fn move_anchor(&mut self, anchor: usize, d: Vec2, base: &Props, last: u32) -> bool { + let Some(mut path) = self.path.clone() else { return false }; + path.move_anchor(anchor, d) && self.set_path(&path, base, last) + } + + /// Carries the path on from its end to `to`, reached on `frame` after the last position key: + /// the old end stays pinned to its frame and the new straight stretch ends the motion. False + /// (nothing changed) when the path is full or `frame` isn't after the last position key. + pub fn extend_to(&mut self, frame: u32, to: Vec2, base: &Props) -> bool { + let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return false }; + if frame <= f1 || f1 <= f0 || path.cmds.len() > MAX_PATH_SEGMENTS { + return false; + } + let n = path.cmds.len(); + let mut longer = path.clone(); + longer.line_to(to); + let Some(longer) = motion_path(&longer).filter(|p| p.cmds.len() == n + 1) else { return false }; + let mut pins = self.live_pins(); + pins.push(Pin { frame: f1, anchor: (n - 1) as u32 }); + self.set_key(Property::X, frame, to.x, base.get(Property::X)); + self.set_key(Property::Y, frame, to.y, base.get(Property::Y)); + self.path = Some(longer); + self.pins = pins; + self.sync_pins(base); true } @@ -614,8 +890,17 @@ impl MotionTween { } /// Removes property `p`'s key at `frame`; a track left with no keys goes. Whether a key was - /// there. + /// there. Removing the X or Y key of a pinned frame lets the pin go (with both keys). pub fn remove_key(&mut self, p: Property, frame: u32) -> bool { + if matches!(p, Property::X | Property::Y) && self.pins.iter().any(|q| q.frame == frame) { + let had = self.track(p).is_some_and(|t| t.key_at(frame).is_some()); + self.unpin(frame); + return had; + } + self.remove_track_key(p, frame) + } + + fn remove_track_key(&mut self, p: Property, frame: u32) -> bool { let Some(t) = self.track_mut(p) else { return false }; let Some(i) = t.key_at(frame) else { return false }; t.keys.remove(i); @@ -647,12 +932,17 @@ impl MotionTween { Some(Track { property: t.property, keys }) }) .collect(); - let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient }; + let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new() }; let Some(op) = self.on_path(base) else { return tail }; let f = frame as f32; match op.walk().tail(op.distance(f)) { - // The cut path starts where the object is; the X/Y keys go on timing it. - Some(p) => tail.path = Some(p), + // The cut path starts where the object is; the X/Y keys go on timing it, and the + // pins after the cut stay on their anchors (the cut segment's end is anchor 1). + Some(p) => { + let (cmd, _) = op.walk().locate(op.distance(f)); + tail.pins = self.live_pins().into_iter().filter(|q| q.frame > frame && q.anchor as usize >= cmd).map(|q| Pin { frame: q.frame - frame, anchor: q.anchor + 1 - cmd as u32 }).collect(); + tail.path = Some(p); + } // Past the path's end: the object holds where the path ended. None => { let p = op.point(f); @@ -677,6 +967,7 @@ impl MotionTween { /// duplicate or empty tracks). pub fn is_sane(&self) -> bool { self.path.as_ref().is_none_or(|p| motion_path(p).as_ref() == Some(p)) + && self.pins == self.live_pins() && self.tracks.iter().all(|t| !t.keys.is_empty() && t.is_sane()) && self.tracks.windows(2).all(|w| matches!(w, [a, b] if a.property.index() < b.property.index())) } @@ -689,6 +980,10 @@ impl MotionTween { self.tracks.retain(|t| !t.keys.is_empty()); self.tracks.sort_by_key(|t| t.property.index()); self.tracks.dedup_by_key(|t| t.property); + self.pins.truncate(MAX_PATH_SEGMENTS); + self.pins.sort_by_key(|p| p.frame); + self.pins.dedup_by_key(|p| p.frame); + self.pins = self.live_pins(); } } @@ -1051,4 +1346,266 @@ mod tests { m.sanitize(); assert!(m.path.is_none()); } + + // ----- anchors pinned to frames (ADR 0049) ---------------------------------------------- + + /// An S through three anchors: (0, 0), (100, 0) and (200, 0), over a hump and under a dip. + fn s_path() -> Path { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(40.0, -60.0), Vec2::new(60.0, -60.0), Vec2::new(100.0, 0.0)).cubic_to(Vec2::new(140.0, 60.0), Vec2::new(160.0, 60.0), Vec2::new(200.0, 0.0)); + p + } + + /// X 0 → 200 over frames 0..20 with `ease`, Y still: the S travelled left to right. + fn along_s(ease: Easing) -> (MotionTween, Element) { + let base = el(1, 0.0, 0.0); + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, ease), (20, 200.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (20, 0.0, Easing::Linear)])]; + assert!(m.set_path(&s_path(), &Props::of(&base), 20)); + (m, base) + } + + fn anchor_at(m: &MotionTween, i: usize) -> Vec2 { + m.path.as_ref().and_then(|p| p.point(i, ANCHOR)).unwrap() + } + + #[test] + fn the_object_passes_each_pinned_anchor_on_its_frame() { + let (mut m, base) = along_s(Easing::QuadIn); + let props = Props::of(&base); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) > 10.0, "unpinned, the middle anchor is passed when the timing says"); + assert_eq!(m.pin(1, 6, &props), Ok(())); + assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }]); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "{:?}", at(&m, &base, 6.0)); + assert!(at(&m, &base, 0.0).distance(Vec2::ZERO) < 1e-3 && at(&m, &base, 20.0).distance(Vec2::new(200.0, 0.0)) < 1e-3, "the ends stay pinned"); + // Pinning where the object is adds an anchor there and moves nothing on that frame. + let was = at(&m, &base, 14.0); + assert_eq!(m.pin_here(14, &props), Ok(2)); + assert_eq!(m.path.as_ref().map(|p| p.cmds.len()), Some(4)); + assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }, Pin { frame: 14, anchor: 2 }]); + assert!(at(&m, &base, 14.0).distance(was) < 0.01, "{:?} vs {was:?}", at(&m, &base, 14.0)); + assert_eq!(m.pin_here(14, &props), Ok(2), "already pinned there"); + // Moving a pinned anchor takes the object with it on that frame, and its keys follow. + assert!(m.move_anchor(2, Vec2::new(0.0, 50.0), &props, 20)); + let a2 = anchor_at(&m, 2); + assert!(at(&m, &base, 14.0).distance(a2) < 1e-3); + assert_eq!(m.track(Property::Y).and_then(|t| t.key_at(14).map(|i| t.keys[i].value)), Some(a2.y)); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "the other pin holds"); + // What can't be pinned says why, and changes nothing. + let before = m.clone(); + assert_eq!(m.pin(1, 16, &props), Err(PinError::Order(Pin { frame: 14, anchor: 2 }))); + assert_eq!(m.pin(0, 5, &props), Err(PinError::End)); + assert_eq!(m.pin(3, 5, &props), Err(PinError::End)); + assert_eq!(m.pin(9, 5, &props), Err(PinError::NoAnchor)); + assert_eq!(m.pin(1, 25, &props), Err(PinError::Outside(0, 20))); + assert_eq!(m.pin_here(0, &props), Err(PinError::Outside(0, 20))); + assert_eq!(m, before); + // Re-pinning an anchor to another frame retimes it. + assert_eq!(m.pin(1, 4, &props), Ok(())); + assert_eq!(m.pins, vec![Pin { frame: 4, anchor: 1 }, Pin { frame: 14, anchor: 2 }]); + assert!(at(&m, &base, 4.0).distance(Vec2::new(100.0, 0.0)) < 1e-3); + assert!(m.track(Property::X).is_some_and(|t| t.key_at(6).is_none()), "the old frame's keys went with the pin"); + assert!(m.is_sane()); + } + + #[test] + fn between_pins_the_eases_time_the_object_as_before() { + // A straight path with an anchor at x = 30 pinned to frame 10: it reproduces the X curve + // exactly, eases and overshoot included, on both legs. + let base = el(1, 0.0, 0.0); + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(30.0, 0.0)).line_to(Vec2::new(100.0, 0.0)); + for second in [Easing::QuadIn, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3)] { + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::QuadIn), (20, 100.0, Easing::Linear)])]; + assert!(m.set_path(&p, &Props::of(&base), 20)); + assert_eq!(m.pin(1, 10, &Props::of(&base)), Ok(())); + if let Some(t) = m.track_mut(Property::X) { + t.keys[1].ease = second; + } + let x = m.track(Property::X).cloned().unwrap(); + for i in 0..=80 { + let f = i as f32 / 4.0; + let q = at(&m, &base, f); + assert!((q.x - x.value_at(f).unwrap()).abs() < 2e-3 && q.y.abs() < 1e-3, "{second:?} frame {f}: {q:?} vs {:?}", x.value_at(f)); + } + } + } + + #[test] + fn unpinning_gives_back_the_unpinned_motion() { + let (m, base) = along_s(Easing::CubicOut); + let props = Props::of(&base); + let mut pinned = m.clone(); + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(at(&pinned, &base, 5.0).distance(at(&m, &base, 5.0)) > 1.0, "pinning retimes"); + assert_eq!(pinned.unpin(8), Some(Pin { frame: 8, anchor: 1 })); + assert_eq!(pinned, m, "pin then unpin: the same tween, keys and all"); + assert_eq!(pinned.unpin(8), None); + // A pin added where the object was leaves its anchor behind, shaping only: the motion + // is ADR 0038's again (the split curve is the same curve). + let mut here = m.clone(); + assert!(here.pin_here(12, &props).is_ok()); + assert!(here.unpin(12).is_some()); + assert_eq!(here.path.as_ref().map(|p| p.cmds.len()), Some(4)); + for f in 0..=20 { + assert!(at(&here, &base, f as f32).distance(at(&m, &base, f as f32)) < 0.01, "frame {f}"); + } + // Removing the X (or Y) key of a pinned frame lets the pin go, with both keys. + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(pinned.remove_key(Property::X, 8)); + assert!(pinned.pins.is_empty() && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_none())); + assert_eq!(pinned, m); + } + + /// ADR 0030's timing as it was before pins: what files without pins must still give. + fn legacy_point(m: &MotionTween, base: &Props, frame: f32) -> Vec2 { + let walk = CurveWalk::new(m.path.as_ref().unwrap()).unwrap(); + let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| m.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); + frames.sort_unstable(); + frames.dedup(); + let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, m.trace_at(base, f as f32))).collect(); + let mut cum = Vec::new(); + let mut d = 0.0f32; + for (i, k) in keys.iter().enumerate() { + d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1)); + cum.push(d); + } + let progress = (|| { + let (first, last) = (keys.first()?, keys.last()?); + if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 { + return Some(0.0); + } + if frame >= last.0 { + return Some(1.0); + } + let total = *cum.last()?; + if total <= 1e-4 { + return Some((frame - first.0) / (last.0 - first.0)); + } + let i = keys.partition_point(|k| k.0 <= frame).saturating_sub(1); + let (a, b) = (keys.get(i)?, keys.get(i + 1)?); + let chord = b.1 - a.1; + let len = chord.length(); + let along = if len > 1e-6 { (m.trace_at(base, frame) - a.1).dot(chord) / len } else { 0.0 }; + let p = (cum[i] + along) / total; + Some(if p.is_finite() { p } else { 0.0 }) + })() + .unwrap_or(1.0); + let (s, l) = (progress * walk.length(), walk.length()); + if s < 0.0 { + walk.at(0.0) + walk.tangent(0.0) * s + } else if s > l { + walk.at(l) + walk.tangent(l) * (s - l) + } else { + walk.at(s) + } + } + + #[test] + fn tweens_without_pins_evaluate_exactly_as_before() { + let base = el(1, 0.0, 0.0); + let props = Props::of(&base); + let mut cases = Vec::new(); + for ease in [Easing::Linear, Easing::QuadOut, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3), Easing::CubicBezier(0.5, -0.6, 0.5, 1.6)] { + let mut m = diagonal(ease); + assert!(m.set_path(&quarter(100.0), &props, 20)); + cases.push(m.clone()); + // Position keys in the middle are timing keys, not pins, in ADR 0030 files. + m.set_key(Property::Y, 8, 30.0, 0.0); + m.set_key(Property::X, 13, 70.0, 0.0); + cases.push(m.clone()); + let mut s = along_s(ease).0; + s.set_key(Property::X, 5, 20.0, 0.0); + cases.push(s); + } + let mut ring = Path::new(); + ring.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(40.0, 0.0)).line_to(Vec2::new(40.0, 40.0)).line_to(Vec2::new(0.0, 40.0)).close(); + let mut l = MotionTween::new(ElementId(1)); + assert!(l.set_path(&ring, &props, 16)); + cases.push(l); + for m in &cases { + assert!(m.pins.is_empty() && m.is_sane()); + let op = m.on_path(&props).unwrap(); + for i in -4..=120 { + let f = i as f32 / 4.0; + assert_eq!(op.point(f), legacy_point(m, &props, f), "frame {f}"); + } + let json = serde_json::to_string(m).unwrap(); + assert!(!json.contains("pins"), "nothing new is written for them"); + } + } + + #[test] + fn a_path_made_from_the_tracks_keeps_their_keys_pinned() { + // Right 100 over 10 frames, then down 100: no path yet, but an anchor at the corner. + let base = el(1, 0.0, 0.0); + let props = Props::of(&base); + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::Linear), (10, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (10, 0.0, Easing::Linear), (20, 100.0, Easing::Linear)])]; + let (mut path, pins) = m.path_and_pins_from_tracks(&props).unwrap(); + assert_eq!(pins, vec![Pin { frame: 10, anchor: 1 }]); + assert_eq!(m.pinned_anchors(&props), vec![Pin { frame: 0, anchor: 0 }, Pin { frame: 10, anchor: 1 }, Pin { frame: 20, anchor: 2 }], "shown pinned before it is a path"); + // Dragging the corner up edits that path: the corner stays pinned to frame 10. + assert!(path.move_anchor(1, Vec2::new(0.0, -40.0))); + assert!(m.set_path(&path, &props, 20)); + assert_eq!(m.pins, pins); + assert!(at(&m, &base, 10.0).distance(Vec2::new(100.0, -40.0)) < 1e-3); + // A path of another shape is a new path: only its ends are pinned. + let mut fresh = m.clone(); + fresh.path = None; + fresh.pins.clear(); + assert!(fresh.set_path(&line((0.0, 0.0), (100.0, 100.0)), &props, 20)); + assert!(fresh.pins.is_empty()); + } + + #[test] + fn splitting_keeps_the_pins_after_the_cut() { + let (mut m, base) = along_s(Easing::Linear); + let props = Props::of(&base); + assert_eq!(m.pin(1, 6, &props), Ok(())); + for cut in [3u32, 6, 10] { + let tail = m.split_at(&props, cut); + let tail_base = m.apply(&base, cut as f32); + assert_eq!(tail.pins.len(), usize::from(cut < 6), "cut {cut}"); + for f in cut..=24 { + let (a, b) = (at(&m, &base, f as f32), at(&tail, &tail_base, (f - cut) as f32)); + assert!(a.distance(b) < 0.05, "cut {cut} frame {f}: {a:?} vs {b:?}"); + } + } + } + + #[test] + fn moving_on_past_the_end_carries_the_path_on() { + let (mut m, base) = along_s(Easing::Linear); + let props = Props::of(&base); + let before: Vec = (0..=20).map(|f| at(&m, &base, f as f32)).collect(); + assert!(!m.extend_to(20, Vec2::new(250.0, 50.0), &props), "only after the last position key"); + assert!(m.extend_to(28, Vec2::new(250.0, 50.0), &props)); + assert_eq!(m.position_range(), Some((0, 28))); + assert_eq!(m.pins, vec![Pin { frame: 20, anchor: 2 }], "the old end stays pinned to its frame"); + assert!(at(&m, &base, 28.0).distance(Vec2::new(250.0, 50.0)) < 1e-3); + assert!(at(&m, &base, 24.0).distance(Vec2::new(225.0, 25.0)) < 1e-2, "on to the new end in a straight line"); + for (f, b) in before.iter().enumerate() { + assert!(at(&m, &base, f as f32).distance(*b) < 1e-2, "frame {f}: as it was"); + } + } + + #[test] + fn loading_drops_pins_that_cannot_hold() { + let (mut m, _) = along_s(Easing::Linear); + m.pins = vec![Pin { frame: 5, anchor: 9 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 25, anchor: 1 }, Pin { frame: 0, anchor: 1 }]; + assert!(!m.is_sane()); + m.sanitize(); + assert!(m.is_sane()); + assert_eq!(m.pins, vec![Pin { frame: 3, anchor: 1 }]); + let json = serde_json::to_string(&m).unwrap(); + assert!(json.contains("\"pins\"")); + assert_eq!(serde_json::from_str::(&json).unwrap(), m); + // Without a path nothing is pinned. + m.path = None; + assert!(!m.is_sane()); + m.sanitize(); + assert!(m.pins.is_empty()); + } } diff --git a/crates/geom/src/walk.rs b/crates/geom/src/walk.rs index 2c86818f..c310ec23 100644 --- a/crates/geom/src/walk.rs +++ b/crates/geom/src/walk.rs @@ -108,6 +108,19 @@ impl CurveWalk { (b.seg as usize, ta + (b.t - ta) * f) } + /// The distance along the path to the anchor that ends path command `cmd`, or 0 for the + /// start (a command before the first segment). `None` when `cmd` ends no segment the walk + /// measured. + pub fn anchor_distance(&self, cmd: usize) -> Option { + if self.segs.first().is_some_and(|(c, _)| cmd < *c) { + return Some(0.0); + } + let k = self.segs.binary_search_by_key(&cmd, |(c, _)| *c).ok()?; + // Segment k's samples end with its anchor (t = 1). + let j = self.samples.partition_point(|x| x.seg as usize <= k); + self.samples.get(j.checked_sub(1)?).map(|x| x.s) + } + /// The path command and curve parameter at distance `s`: where to split or bend the path. pub fn locate(&self, s: f32) -> (usize, f32) { let (k, t) = self.find(s); @@ -298,6 +311,12 @@ mod tests { assert!(w.at(125.0).distance(Vec2::new(110.0, 45.0)) < 1e-3); assert!(w.tangent(125.0).distance(Vec2::new(0.0, 1.0)) < 1e-5); assert_eq!(w.locate(125.0).0, 2, "the second line is command 2"); + // Anchors by distance: the start, the corner, the end; the walk lands on them exactly. + assert_eq!(w.anchor_distance(0), Some(0.0)); + let corner = w.anchor_distance(1).unwrap(); + assert!((corner - 100.0).abs() < 1e-3 && w.at(corner) == Vec2::new(110.0, 20.0), "{corner}"); + assert_eq!(w.anchor_distance(2), Some(w.length())); + assert_eq!(w.anchor_distance(3), None); assert!((w.project(Vec2::new(130.0, 60.0)) - 140.0).abs() < 1e-2); let tail = w.tail(50.0).unwrap(); let tw = CurveWalk::new(&tail).unwrap(); From 891464f505d856781f61a3e284f8e87ae49c7527 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:49:55 -0700 Subject: [PATCH 013/402] feat(engine): motion.pin_point/unpin_point, auto-key pins the path where the object is put (M2) --- crates/doc/src/motion.rs | 46 ++++- crates/engine/src/cmds_motion.rs | 251 ++++++++++++++++++++----- crates/engine/src/lib.rs | 2 + crates/engine/src/motion_path_tests.rs | 9 +- crates/engine/src/motion_pin_tests.rs | 229 ++++++++++++++++++++++ 5 files changed, 479 insertions(+), 58 deletions(-) create mode 100644 crates/engine/src/motion_pin_tests.rs diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 1c36ab2f..a79de542 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -724,19 +724,12 @@ impl MotionTween { } else if t >= 1.0 - 1e-3 { cmd } else { - let Some(path) = trial.path.as_mut() else { return Err(PinError::NoPath) }; - if path.cmds.len() > MAX_PATH_SEGMENTS { + if self.path.as_ref().is_some_and(|p| p.cmds.len() > MAX_PATH_SEGMENTS) { return Err(PinError::Full); } - if !path.split_segment(cmd, t) { + if !trial.split_path(cmd, t) { return Err(PinError::OffPath); } - // The new anchor ends the first half; the anchors after it move up one. - for p in &mut trial.pins { - if p.anchor as usize >= cmd { - p.anchor += 1; - } - } cmd }; trial.pin(anchor, frame, base)?; @@ -744,6 +737,41 @@ impl MotionTween { Ok(anchor) } + /// Splits the path's segment `cmd` at curve parameter `t` (the curve unchanged; the new + /// anchor is `cmd`). Pins after it stay on their anchors. False when there is no such + /// segment. + pub fn split_path(&mut self, cmd: usize, t: f32) -> bool { + let Some(path) = self.path.as_mut() else { return false }; + if !path.split_segment(cmd, t) { + return false; + } + for p in &mut self.pins { + if p.anchor as usize >= cmd { + p.anchor = p.anchor.saturating_add(1); + } + } + true + } + + /// Deletes anchor `i` between the ends, refitting the two segments around it as one + /// ([`Path::merge_at`]). A pin on it goes, with its keys; later pins stay on their anchors. + /// False when it can't be deleted (an end, or no such anchor). + pub fn delete_anchor(&mut self, i: usize) -> bool { + let Some(path) = self.path.as_mut() else { return false }; + if !path.merge_at(i) { + return false; + } + if let Some(frame) = self.pins.iter().find(|p| p.anchor as usize == i).map(|p| p.frame) { + self.unpin(frame); + } + for p in &mut self.pins { + if p.anchor as usize > i { + p.anchor -= 1; + } + } + true + } + /// Lets the pin on `frame` go: its X/Y keys go with it and its anchor shapes the path only /// (ADR 0038's behaviour). The pin, if there was one. pub fn unpin(&mut self, frame: u32) -> Option { diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 2f7f6cc2..0893d409 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -6,11 +6,16 @@ //! [`begin_edit`] swaps the target for how it looks at the playhead, and after the command //! [`finish_edit`] turns whatever changed in its transform or colour effect into property keys //! and puts the base object back (with any other change, a new fill say, kept). +//! +//! On a motion path, moving the object at a frame pins the path there (ADR 0049): the anchor +//! pinned to that frame moves (an end, at the first or last position key), or a new anchor is +//! added where the object is, pinned to the frame, and moved; after the last position key the +//! path carries on to where the object was put. 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, Property, Props}; +use anicraft_doc::{ColorEffect, 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; @@ -21,7 +26,7 @@ pub fn specs() -> 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.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 and where the object is", false, info), + 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), c("motion.set_path", "Edit Motion Path", "", None, "{d: SVG path data in stage space (its first subpath; ends are the start and end positions), layer?, frame?}", true, set_path), c("motion.clear_path", "Remove Motion Path", "", None, "{layer?, frame?}: back to the straight path the X/Y curves trace", true, clear_path), c("motion.orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}: turn the object as its motion path turns", true, orient), @@ -29,6 +34,8 @@ pub fn specs() -> Vec { c("motion.delete_points", "Delete Motion Path Points", "", None, "{anchors: [index, ..] (as motion.info lists them; the ends stay), layer?, frame?}: the path refits through the rest", true, delete_points), c("motion.convert_point", "Convert Motion Path Point", "", None, "{anchor, smooth: bool, layer?, frame?}: smooth (handles in line) or corner (handles on the anchor)", true, convert_point), c("motion.move_path", "Move Motion Path", "", None, "{dx, dy, layer?, frame?}: the whole path with its object, keeping the timing", true, move_path), + c("motion.pin_point", "Pin Motion Path Point", "", None, "{anchor? (default: a new anchor where the object is), frame? (the frame to pin it to, between the first and last position keys), layer?}: the object passes the anchor exactly on that frame → {anchor, frame, pins}", true, pin_point), + c("motion.unpin_point", "Unpin Motion Path Point", "", None, "{anchor? | frame?, layer?}: the anchor shapes the path only again; the X/Y keys of its frame go → {anchor, frame, pins}", true, unpin_point), ] } @@ -132,19 +139,37 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { } } -/// Most bends [`move_on_path`] makes to land the object where it was put; each takes 15–35% -/// off the miss on typical paths (the path's length changes as it bends, sliding the object). +/// Most bends [`move_on_path`] makes to land the object where it was put off the path; each +/// takes 15–35% off the miss on typical paths (the path's length changes as it bends, sliding the +/// object). const BEND_STEPS: usize = 48; -/// The object on a motion path was moved by `d` at `offset`: at or before the first position -/// key the path's start moves, at or after the last its end, in between the path bends so it -/// passes where the object was put (a few bends, as the path's length changes with each); -/// without position keys the whole path moves. +/// The object on a motion path was moved by `d` at `offset` (ADR 0049): the anchor pinned to +/// that frame moves with it (before the first position key, the start); after the last position +/// key the path carries on to where it was put; in between, a new anchor where the object is gets +/// pinned to the frame and moved. Where the object is off the path (an overshooting ease) the +/// path bends instead (ADR 0030); without position keys the whole path moves. fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u32) { let Some(mut path) = m.path.clone() else { return }; - let f = offset as f32; match m.position_range() { - Some((f0, f1)) if f1 > f0 && offset > f0 && offset < f1 => { + Some((f0, f1)) if f1 > f0 => { + let pinned = m.pinned_anchors(base).into_iter().find(|p| p.frame == offset).map(|p| p.anchor as usize); + if let Some(a) = pinned.or((offset < f0).then_some(0)) { + m.move_anchor(a, d, base, last); + return; + } + if offset > f1 { + let end = anicraft_doc::motion::path_ends(&path).map(|(_, b)| b).unwrap_or_default(); + if !m.extend_to(offset, end + d, base) { + m.move_anchor(path.cmds.len().saturating_sub(1), d, base, last); + } + return; + } + if let Ok(a) = m.pin_here(offset, base) { + m.move_anchor(a, d, base, last); + return; + } + let f = offset as f32; let Some(target) = m.on_path(base).map(|op| op.point(f) + d) else { return }; let mut trial = m.clone(); for _ in 0..BEND_STEPS { @@ -160,10 +185,6 @@ fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u trial.path = Some(path.clone()); } } - Some((f0, f1)) if f1 > f0 => { - let anchor = if offset <= f0 { 0 } else { path.cmds.len().saturating_sub(1) }; - path.move_anchor(anchor, d); - } _ => path = path.transformed(&Affine::translate(d.x, d.y)), } m.set_path(&path, base, last); @@ -182,7 +203,7 @@ fn set_path(s: &mut Session, p: &Value) -> Result { let path = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; if last == 0 && m.position_range().is_none_or(|(a, b)| a == b) { return Err(EngineError::State("a one-frame span has no room to move along a path: make the span longer first".into())); @@ -190,33 +211,61 @@ fn set_path(s: &mut Session, p: &Value) -> Result { if !m.set_path(&path, &base, last) { return Err(EngineError::Param("param 'd' needs a segment of some length, with finite points within ±1000000".into())); } - Ok(path_summary(m)) + Ok(path_summary(m, start, &base)) } -fn path_summary(m: &MotionTween) -> Value { - let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient}) }; +fn path_summary(m: &MotionTween, start: u32, base: &Props) -> Value { + let pins = pins_json(m, start, base); + let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient, "pins": pins}) }; let len = anicraft_geom::walk::CurveWalk::new(path).map_or(0.0, |w| w.length()); let (a, b) = anicraft_doc::motion::path_ends(path).unwrap_or_default(); // Anchor `i` is path command `i` (a motion path is a move and cubics). let anchors: Vec<[f32; 2]> = path.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect(); - json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient}) + json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient, "pins": pins}) +} + +/// The anchors tied to frames (ADR 0049), ends included: `{anchor, frame, end, at}`, frames +/// counted from the timeline's start. +fn pins_json(m: &MotionTween, start: u32, base: &Props) -> Value { + let path = m.path.clone().or_else(|| m.path_from_tracks(base)); + let pins = m.pinned_anchors(base); + let n = pins.len(); + let v: Vec = pins + .iter() + .enumerate() + .map(|(i, q)| { + let at = path.as_ref().and_then(|p| p.point(q.anchor as usize, anicraft_geom::edit::ANCHOR)).map(|v| json!([v.x, v.y])); + json!({"anchor": q.anchor, "frame": start + q.frame, "end": i == 0 || i + 1 == n, "at": at}) + }) + .collect(); + Value::Array(v) } /// Edits the motion path at the target frame with `edit`: the tween's own path, or the straight -/// one its X/Y curves trace (which the edit makes its own, as on the stage). The ends' keys stay -/// unless the edit moved an end, so the timing is kept. Returns what `edit` returned and the -/// path's summary. -fn edit_path(s: &mut Session, p: &Value, edit: impl FnOnce(&mut anicraft_geom::Path) -> Result) -> Result<(T, Value)> { +/// one its X/Y curves trace (which the edit makes its own, as on the stage, its position keys +/// pinned to their anchors). The ends' and pins' keys stay unless the edit moved their anchors, +/// so the timing is kept. Returns what `edit` returned and the path's summary. +fn edit_path(s: &mut Session, p: &Value, edit: impl FnOnce(&mut MotionTween) -> Result) -> Result<(T, Value)> { let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; - let mut path = m.path.clone().or_else(|| m.path_from_tracks(&base)).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?; - let out = edit(&mut path)?; + if m.path.is_none() { + let (path, pins) = m.path_and_pins_from_tracks(&base).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?; + m.path = Some(path); + m.pins = pins; + } + let out = edit(m)?; + let path = m.path.clone().ok_or_else(|| EngineError::State("the motion path went away".into()))?; if !m.set_path(&path, &base, last) { return Err(EngineError::State("that would leave the motion path with no length".into())); } - Ok((out, path_summary(m))) + Ok((out, path_summary(m, start, &base))) +} + +/// The motion path being edited (there is one inside [`edit_path`]). +fn path_mut(m: &mut MotionTween) -> Result<&mut anicraft_geom::Path> { + m.path.as_mut().ok_or_else(|| EngineError::State("no motion path here".into())) } /// An anchor index param, checked against the path. @@ -242,7 +291,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result { if !(0.0..=1000.0).contains(&slop) { return Err(EngineError::Param("param 'slop' must be between 0 and 1000".into())); } - let (anchor, mut v) = edit_path(s, p, |path| { + let (anchor, mut v) = edit_path(s, p, |m| { + let path = path_mut(m)?; if path.cmds.len() > anicraft_doc::motion::MAX_PATH_SEGMENTS { return Err(EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS))); } @@ -268,7 +318,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result { if !(1e-3..=1.0 - 1e-3).contains(&t) { return Err(EngineError::State("there is already an anchor there".into())); } - if !path.split_segment(cmd, t) { + // Pins after it stay on their anchors. + if !m.split_path(cmd, t) { return Err(EngineError::State("cannot add a point there".into())); } // The new anchor ends the first half. @@ -283,8 +334,8 @@ fn delete_points(s: &mut Session, p: &Value) -> Result { if wanted.is_empty() { return Err(EngineError::Param("param 'anchors' lists no anchor".into())); } - let ((deleted, kept_ends), mut v) = edit_path(s, p, |path| { - let n = path.cmds.len(); + let ((deleted, kept_ends, unpinned), mut v) = edit_path(s, p, |m| { + let n = path_mut(m)?.cmds.len(); let mut set = std::collections::BTreeSet::new(); for &i in wanted.iter().take(100_000) { match usize::try_from(i).ok().filter(|i| *i < n) { @@ -296,23 +347,28 @@ fn delete_points(s: &mut Session, p: &Value) -> Result { if set.is_empty() { return Err(EngineError::State("the ends of a motion path can't be deleted: they are where the motion starts and ends. Drag them to move them, or Straighten the path".into())); } - // Last first, so the indices still to go stay where they were. - let mut deleted = 0; + // Last first, so the indices still to go stay where they were. A pinned anchor's pin + // goes with it (and its X/Y keys). + let (mut deleted, mut unpinned) = (0, 0); for i in set.into_iter().rev() { - if path.merge_at(i) { + let pinned = m.live_pins().iter().any(|q| q.anchor as usize == i); + if m.delete_anchor(i) { deleted += 1; + unpinned += usize::from(pinned); } } - Ok((deleted, ends)) + Ok((deleted, ends, unpinned)) })?; v["deleted"] = json!(deleted); v["kept_ends"] = json!(kept_ends); + v["unpinned"] = json!(unpinned); Ok(v) } fn convert_point(s: &mut Session, p: &Value) -> Result { let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required (true: smooth, false: corner)".into()))?; - let (changed, mut v) = edit_path(s, p, |path| { + let (changed, mut v) = edit_path(s, p, |m| { + let path = path_mut(m)?; let a = anchor_index(p, "anchor", path)?; Ok(if smooth { path.make_smooth(a) } else { path.make_corner(a) }) })?; @@ -326,6 +382,7 @@ fn move_path(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("params 'dx' and 'dy' must be finite".into())); } let (kf, _) = motion_span(s, p)?; + let start = kf.start; let i = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; if !m.translate(d) { @@ -337,7 +394,8 @@ fn move_path(s: &mut Session, p: &Value) -> Result { el.transform = Affine::translate(d.x, d.y).mul(&el.transform); *slot = Arc::new(el); } - let mut v = kf.motion.as_ref().map_or(Value::Null, path_summary); + let base = base_of(kf)?; + let mut v = kf.motion.as_ref().map_or(Value::Null, |m| path_summary(m, start, &base)); v["moved"] = json!([d.x, d.y]); Ok(v) } @@ -349,8 +407,10 @@ fn clear_path(s: &mut Session, p: &Value) -> Result { if m.path.take().is_none() { return Err(EngineError::State(format!("the motion tween at frame {} has no motion path to remove", frame + 1))); } - // Orient to path has nothing left to turn with. + // Orient to path has nothing left to turn with, and pins nothing to pin. Their keys stay: + // the straight path runs through them. m.orient = false; + m.pins.clear(); Ok(json!({"cleared": true})) } @@ -358,7 +418,7 @@ fn orient(s: &mut Session, p: &Value) -> Result { let on = opt_bool(p, "orient")?.ok_or_else(|| EngineError::Param("param 'orient' is required (true or false)".into()))?; let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; // The straight path the X/Y curves trace becomes the path to turn along. let mut created = false; @@ -367,11 +427,84 @@ fn orient(s: &mut Session, p: &Value) -> Result { created = m.set_path(&path, &base, last); } m.orient = on; - let mut v = path_summary(m); + let mut v = path_summary(m, start, &base); v["path_created"] = json!(created); Ok(v) } +/// Why a pin can't be made, in words an artist (or an agent) can act on. `start` is the span's +/// first frame (messages count frames from 1, as the timeline does). +fn pin_error(e: PinError, start: u32, frame: u32) -> EngineError { + let shown = |f: u32| start + f + 1; + match e { + PinError::NoPath => EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()), + PinError::NoAnchor => EngineError::Param("no such anchor on this motion path (motion.info lists them, from 0 at the start)".into()), + PinError::End => EngineError::State("the ends of a motion path are always pinned, to the first and last position keys: move the object on those frames to move them".into()), + PinError::Outside(f0, f1) => EngineError::State(format!("frame {} is outside the motion (frames {} to {}): move the object there to carry the path on", shown(frame), shown(f0), shown(f1))), + PinError::Order(q) => EngineError::State(format!("anchor {} is pinned to frame {}: pins keep the path's order, a later frame on a later anchor", q.anchor, shown(q.frame))), + PinError::OffPath => EngineError::State(format!("at frame {} the object is beyond an end of the path (its ease overshoots): pin an anchor of the path instead", shown(frame))), + PinError::Full => EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS)), + } +} + +/// A straight motion's path becomes the tween's own, its position keys pinned to its anchors +/// (nothing moves). +fn own_path(m: &mut MotionTween, base: &Props, last: u32) -> std::result::Result<(), PinError> { + if m.path.is_none() { + let (path, pins) = m.path_and_pins_from_tracks(base).ok_or(PinError::NoPath)?; + m.path = Some(path.clone()); + m.pins = pins; + m.set_path(&path, base, last); + } + Ok(()) +} + +fn pin_point(s: &mut Session, p: &Value) -> Result { + let anchor = opt_u64(p, "anchor")?.map(|a| usize::try_from(a).unwrap_or(usize::MAX)); + let (kf, offset) = motion_span(s, p)?; + let base = base_of(kf)?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?; + let a = match anchor { + Some(a) => m.pin(a, offset, &base).map(|_| a), + None => m.pin_here(offset, &base), + } + .map_err(|e| pin_error(e, start, offset))?; + let mut v = path_summary(m, start, &base); + v["anchor"] = json!(a); + v["frame"] = json!(start + offset); + Ok(v) +} + +fn unpin_point(s: &mut Session, p: &Value) -> Result { + let anchor = opt_u64(p, "anchor")?; + let (kf, offset) = motion_span(s, p)?; + let base = base_of(kf)?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?; + let all = m.pinned_anchors(&base); + let found: Option = match anchor { + Some(a) => all.iter().find(|q| u64::from(q.anchor) == a).copied(), + None => all.iter().find(|q| q.frame == offset).copied(), + }; + let Some(pin) = found else { + return Err(EngineError::State(match anchor { + Some(a) => format!("anchor {a} isn't pinned to a frame"), + None => format!("no anchor is pinned to frame {}", start + offset + 1), + })); + }; + if all.first() == Some(&pin) || all.last() == Some(&pin) { + return Err(pin_error(PinError::End, start, pin.frame)); + } + m.unpin(pin.frame); + let mut v = path_summary(m, start, &base); + v["anchor"] = json!(pin.anchor); + v["frame"] = json!(start + pin.frame); + Ok(v) +} + /// Insert Keyframe (F6) inside a motion tween: every property gets a key at `frame` holding its /// value there; the timeline is not split. Whether `frame` was in a motion tween. pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool { @@ -384,7 +517,13 @@ pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool { let Some(m) = kf.motion.as_mut() else { return false }; let Some(base) = m.target_index(&kf.elements).and_then(|t| kf.elements.get(t)).map(|e| Props::of(e)) else { return true }; let now = m.props_at(&base, offset as f32); + // On a motion path the frame's place is an anchor pinned to it (ADR 0049), where the + // object is: nothing moves on this frame. + let pinned = m.path.is_some() && m.pin_here(offset, &base).is_ok(); for p in Property::ALL { + if pinned && matches!(p, Property::X | Property::Y) { + continue; + } m.set_key(p, offset, now.get(p), base.get(p)); } true @@ -505,8 +644,19 @@ fn set_key(s: &mut Session, p: &Value) -> Result { let (kf, offset) = motion_span(s, p)?; let base = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); let base = base.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; - let start = kf.start; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + // On a path, the X/Y keys of a pinned frame are its anchor's place: setting one moves the + // anchor (ADR 0049). + let pinned = matches!(prop, Property::X | Property::Y).then(|| m.pinned_anchors(&base).into_iter().find(|q| q.frame == offset)).flatten().filter(|_| m.path.is_some()); + if let Some(pin) = pinned { + let at = m.path.as_ref().and_then(|p| p.point(pin.anchor as usize, anicraft_geom::edit::ANCHOR)).unwrap_or_default(); + let d = if prop == Property::X { Vec2::new(value - at.x, 0.0) } else { Vec2::new(0.0, value - at.y) }; + if d != Vec2::ZERO && !m.move_anchor(pin.anchor as usize, d, &base, last) { + return Err(EngineError::Param(format!("{} must keep the motion path within ±1000000 px", prop.label()))); + } + return Ok(json!({"property": prop.key(), "frame": start + offset, "value": value, "anchor": pin.anchor})); + } m.set_key(prop, offset, value, base.get(prop)); Ok(json!({"property": prop.key(), "frame": start + offset, "value": value})) } @@ -516,11 +666,20 @@ fn remove_key(s: &mut Session, p: &Value) -> Result { let (kf, offset) = motion_span(s, p)?; let start = kf.start; let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; - let removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); + // Removing a pinned frame's X or Y key lets the pin go, with both keys (ADR 0049). + let pin = m.live_pins().into_iter().find(|q| q.frame == offset).filter(|_| only.is_none_or(|o| matches!(o, Property::X | Property::Y))); + let mut removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); + if pin.is_some() { + for k in [Property::X.key(), Property::Y.key()] { + if !removed.contains(&k) { + removed.push(k); + } + } + } if removed.is_empty() { return Err(EngineError::State(format!("there is no property keyframe at frame {}", start + offset + 1))); } - Ok(json!({"removed": removed, "frame": start + offset})) + Ok(json!({"removed": removed, "frame": start + offset, "unpinned": pin.map(|q| q.anchor)})) } fn set_ease(s: &mut Session, p: &Value) -> Result { @@ -561,8 +720,10 @@ fn info(s: &mut Session, p: &Value) -> Result { let values: serde_json::Map = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().to_string(), json!(n.get(*p))))).collect(); // Where the object is (on a motion path the X/Y values are its timing, not its place). let position = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| m.apply(e, (frame - kf.start) as f32).transform.translation()).map(|q| json!([q.x, q.y])); - let path = path_summary(m); + let path = m.path.as_ref().map(|p| p.to_svg()); // The anchors point edits address: the path's own, or the straight path's (ADR 0038). let anchors: Vec<[f32; 2]> = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).map(|p| p.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect()).unwrap_or_default(); - Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path["path"], "anchors": anchors, "orient": m.orient})) + // And those tied to frames, ends included (ADR 0049). + let pins = base.map_or(Value::Array(Vec::new()), |b| pins_json(m, kf.start, &b)); + Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path, "anchors": anchors, "pins": pins, "orient": m.orient})) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 31d651af..e95da941 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -895,6 +895,8 @@ mod motion_tests; #[cfg(test)] mod motion_path_tests; #[cfg(test)] +mod motion_pin_tests; +#[cfg(test)] mod plugin_tests; #[cfg(test)] mod tests_sound; diff --git a/crates/engine/src/motion_path_tests.rs b/crates/engine/src/motion_path_tests.rs index f01e57b2..b5cd82e2 100644 --- a/crates/engine/src/motion_path_tests.rs +++ b/crates/engine/src/motion_path_tests.rs @@ -154,13 +154,14 @@ fn moving_the_object_on_a_path_reshapes_the_path() { s.set_frame(23); run(&mut s, "element.translate", json!({"dx": 10, "dy": 0})); assert!(pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3); - // In between: the path bends through where the object was put; no key is added. - let before = keys(&s); + // In between: an anchor where the object was put, pinned to that frame (ADR 0049; ADR 0030 + // bent the path instead and added no key). let want = pos(&mut s, 9) + Vec2::new(0.0, 40.0); s.set_frame(9); run(&mut s, "element.translate", json!({"dx": 0, "dy": 40})); - assert!(pos(&mut s, 9).distance(want) < 0.01, "{:?} vs {want:?}", pos(&mut s, 9)); - assert_eq!(keys(&s), before, "the timing keeps its keys"); + assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9)); + assert_eq!(keys(&s), Some(vec![0, 9, 23]), "a position key on the pinned frame"); + assert_eq!(motion(&s).pins, vec![anicraft_doc::Pin { frame: 9, anchor: 1 }]); assert!(pos(&mut s, 0).distance(Vec2::new(0.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3, "the ends stay"); // A drag on the stage is a gesture: one undo step however many moves. let steps = s.history_len(); diff --git a/crates/engine/src/motion_pin_tests.rs b/crates/engine/src/motion_pin_tests.rs new file mode 100644 index 00000000..447f9e5c --- /dev/null +++ b/crates/engine/src/motion_pin_tests.rs @@ -0,0 +1,229 @@ +//! Motion path anchors pinned to frames (ADR 0049) through the command registry: auto-key +//! pinning where the object is put, `motion.pin_point` / `motion.unpin_point`, the X/Y keys of a +//! pinned frame as its anchor's place, point edits keeping pins on their anchors, F6, undo and +//! the file round trip. + +use super::*; +use anicraft_doc::{Pin, Property}; +use anicraft_geom::Vec2; +use anicraft_geom::edit::ANCHOR; +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 fails(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 10 × 10 square centred on (5, 5) with a motion tween over frames 0..24 travelling the hump +/// from (5, 5) up and over to (105, 5), reached on frame 23. +fn on_hump() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s.set_frame(23); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 0})); + s.set_frame(0); + run(&mut s, "motion.set_path", json!({"d": "M5 5 C38 -60 72 -60 105 5"})); + s +} + +fn pos(s: &mut Session, frame: u32) -> Vec2 { + s.set_frame(frame); + s.visible_elements().first().map(|e| e.transform.translation()).unwrap_or_default() +} + +fn motion(s: &Session) -> &anicraft_doc::MotionTween { + s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).expect("motion tween") +} + +fn anchor(s: &Session, i: usize) -> Vec2 { + motion(s).path.as_ref().and_then(|p| p.point(i, ANCHOR)).expect("anchor") +} + +fn key_frames(s: &Session, p: Property) -> Vec { + motion(s).track(p).map(|t| t.keys.iter().map(|k| k.frame).collect()).unwrap_or_default() +} + +#[test] +fn moving_the_object_at_a_middle_frame_pins_an_anchor_there() { + let mut s = on_hump(); + let was = pos(&mut s, 9); + // A drag on the stage: one undo step however many moves, one pin. + let steps = s.history_len(); + s.set_frame(9); + s.begin_gesture("Move"); + for _ in 0..4 { + run(&mut s, "element.translate", json!({"dx": 5, "dy": 10})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + let want = was + Vec2::new(20.0, 40.0); + assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9)); + assert!(anchor(&s, 1).distance(want) < 1e-3, "the new anchor is where the object was put"); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]); + assert!(pos(&mut s, 0).distance(Vec2::new(5.0, 5.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 5.0)) < 1e-3, "the ends stay"); + // motion.info reports every anchor tied to a frame, ends included. + let info = run(&mut s, "motion.info", json!({})); + let pins: Vec<(u64, u64, bool)> = info["pins"].as_array().unwrap().iter().map(|p| (p["anchor"].as_u64().unwrap(), p["frame"].as_u64().unwrap(), p["end"].as_bool().unwrap())).collect(); + assert_eq!(pins, vec![(0, 0, true), (1, 9, false), (2, 23, true)]); + // A later frame pins a later anchor; the first pin holds. + s.set_frame(16); + run(&mut s, "element.translate", json!({"dx": 0, "dy": -30})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }, Pin { frame: 16, anchor: 2 }]); + assert!(pos(&mut s, 9).distance(want) < 1e-3); + assert!(pos(&mut s, 16).distance(anchor(&s, 2)) < 1e-3); + // Undo takes the pin back with its anchor and keys. + s.undo().expect("undo"); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]); + assert_eq!(key_frames(&s, Property::X), vec![0, 9, 23]); +} + +#[test] +fn moving_after_the_last_position_key_carries_the_path_on() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s.set_frame(12); + run(&mut s, "element.translate", json!({"dx": 60, "dy": 0})); + run(&mut s, "motion.set_path", json!({"d": "M5 5 C25 -30 45 -30 65 5"})); + let before: Vec = (0..=12).map(|f| pos(&mut s, f)).collect(); + s.set_frame(20); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 40})); + assert!(pos(&mut s, 20).distance(Vec2::new(105.0, 45.0)) < 1e-3); + assert_eq!(motion(&s).position_range(), Some((0, 20))); + assert_eq!(motion(&s).pins, vec![Pin { frame: 12, anchor: 1 }], "the old end stays pinned to its frame"); + for (f, b) in before.iter().enumerate() { + assert!(pos(&mut s, f as u32).distance(*b) < 1e-2, "frame {f} as it was"); + } +} + +#[test] +fn pin_and_unpin_an_anchor_by_command() { + let mut s = on_hump(); + let v = run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5})); + assert_eq!(v["anchor"], 1); + let unpinned = motion(&s).clone(); + let off = pos(&mut s, 6); + assert!(off.distance(anchor(&s, 1)) > 5.0, "an anchor alone is reached when the timing says"); + let steps = s.history_len(); + let v = run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6})); + assert_eq!(s.history_len(), steps + 1); + assert_eq!((v["anchor"].as_u64(), v["frame"].as_u64()), (Some(1), Some(6))); + assert_eq!(v["pins"].as_array().map(Vec::len), Some(3)); + assert!(pos(&mut s, 6).distance(anchor(&s, 1)) < 1e-3, "passed exactly on its frame"); + assert_eq!(key_frames(&s, Property::Y), vec![0, 6, 23]); + // What can't be pinned is refused with the reason. + assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 0, "frame": 6})).contains("always pinned")); + assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 7, "frame": 6})).contains("no such anchor")); + assert!(fails(&mut s, "motion.unpin_point", json!({"anchor": 2})).contains("always pinned")); + assert!(fails(&mut s, "motion.unpin_point", json!({"frame": 3})).contains("no anchor is pinned to frame 4")); + // Unpinning (by anchor or by frame) gives the tween back as it was. + run(&mut s, "motion.unpin_point", json!({"anchor": 1})); + assert_eq!(*motion(&s), unpinned); + assert!(pos(&mut s, 6).distance(off) < 1e-3, "ADR 0038's timing again"); + run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6})); + run(&mut s, "motion.unpin_point", json!({"frame": 6})); + assert_eq!(*motion(&s), unpinned); +} + +#[test] +fn pin_point_without_an_anchor_pins_where_the_object_is() { + let mut s = on_hump(); + let was = pos(&mut s, 10); + let v = run(&mut s, "motion.pin_point", json!({"frame": 10})); + assert_eq!(v["anchor"], 1); + assert!(pos(&mut s, 10).distance(was) < 0.01, "nothing moves on that frame"); + assert!(anchor(&s, 1).distance(was) < 0.01); + // Outside the motion, or on an end: refused. + assert!(fails(&mut s, "motion.pin_point", json!({"frame": 0})).contains("outside the motion")); + // A straight motion's middle keys are pinned as soon as its path is the tween's own. + let mut t = Session::default(); + run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut t, "timeline.create_motion_tween", json!({})); + t.set_frame(10); + run(&mut t, "element.translate", json!({"dx": 100, "dy": 0})); + t.set_frame(20); + run(&mut t, "element.translate", json!({"dx": 0, "dy": 100})); + let info = run(&mut t, "motion.info", json!({})); + assert_eq!(info["pins"].as_array().map(Vec::len), Some(3), "shown pinned while straight"); + run(&mut t, "motion.pin_point", json!({"frame": 15})); + assert_eq!(motion(&t).pins, vec![Pin { frame: 10, anchor: 1 }, Pin { frame: 15, anchor: 2 }]); +} + +#[test] +fn a_pinned_frames_x_and_y_keys_are_its_anchors_place() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 8})); + let a = anchor(&s, 1); + // The Motion Editor sets X on the pinned frame: the anchor moves, and the object with it. + let v = run(&mut s, "motion.set_key", json!({"property": "x", "frame": 8, "value": a.x + 12.0})); + assert_eq!(v["anchor"], 1); + assert!(anchor(&s, 1).distance(a + Vec2::new(12.0, 0.0)) < 1e-3); + assert!(pos(&mut s, 8).distance(a + Vec2::new(12.0, 0.0)) < 1e-3); + // And the ends: X on the last frame moves the path's end. + run(&mut s, "motion.set_key", json!({"property": "y", "frame": 23, "value": 25.0})); + assert!(anchor(&s, 2).distance(Vec2::new(105.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 25.0)) < 1e-3); + // Removing the pinned frame's X key lets the pin go, with its Y key. + let v = run(&mut s, "motion.remove_key", json!({"property": "x", "frame": 8})); + assert_eq!(v["unpinned"], 1); + assert_eq!(v["removed"], json!(["x", "y"])); + assert!(motion(&s).pins.is_empty() && !key_frames(&s, Property::Y).contains(&8)); +} + +#[test] +fn point_edits_keep_pins_on_their_anchors() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 14})); + let pinned = anchor(&s, 1); + // A point added before the pinned anchor: the pin follows it to index 2. + run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 2 }]); + assert!(pos(&mut s, 14).distance(pinned) < 1e-3); + // Deleting the point before it keeps the pin; deleting the pinned point lets it go. + let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + assert_eq!(v["unpinned"], 0); + assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 1 }]); + assert!(pos(&mut s, 14).distance(pinned) < 1e-3); + let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + assert_eq!(v["unpinned"], 1); + assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X) == vec![0, 23], "its keys went with it"); + // Straighten forgets the pins; their keys stay as the straight path's corners. + run(&mut s, "motion.pin_point", json!({"frame": 14})); + run(&mut s, "motion.clear_path", json!({})); + assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X).contains(&14)); +} + +#[test] +fn insert_keyframe_inside_a_path_tween_pins_the_path_there() { + let mut s = on_hump(); + let was = pos(&mut s, 11); + s.set_frame(11); + run(&mut s, "timeline.insert_keyframe", json!({})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 11, anchor: 1 }]); + assert!(pos(&mut s, 11).distance(was) < 0.01, "{:?} vs {was:?}", pos(&mut s, 11)); + assert!(key_frames(&s, Property::Rotation).contains(&11), "every other property keyed too"); +} + +#[test] +fn pins_round_trip_through_the_file_format() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 7})); + let text = format::to_json(&s.doc).expect("save"); + assert!(text.contains("\"pins\"")); + let back = format::from_json(&text).expect("load"); + assert_eq!(back, s.doc); + // A path tween from before pins writes none and reads back the same. + let plain = on_hump(); + let text = format::to_json(&plain.doc).expect("save"); + assert!(!text.contains("\"pins\"")); + assert_eq!(format::from_json(&text).expect("load"), plain.doc); +} From 6ba7fb86e2b1291f59242900798e09af2c5032d7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:55:54 -0700 Subject: [PATCH 014/402] feat(ui): pinned motion path points on the stage, Motion Editor, timeline and Properties (M2) --- src/a11y.rs | 2 +- src/app.rs | 21 ++++++ src/i18n/tests.rs | 2 +- src/main.rs | 2 +- src/motion_editor.rs | 35 ++++++++- src/motion_path.rs | 170 +++++++++++++++++++++++++++++++++++++++---- src/panels.rs | 27 +++++++ src/timeline.rs | 11 ++- 8 files changed, 246 insertions(+), 24 deletions(-) diff --git a/src/a11y.rs b/src/a11y.rs index 7d9d5557..15318b84 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", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple"] { + 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"] { 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 83c138d5..cb8cf466 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1237,6 +1237,27 @@ impl App { self.status_ok(tr!("Added a point to the motion path. {undo} to undo.", undo = self.undo_key())); } } + Some(which @ ("motionpins" | "motionpinsspan")) => { + // Anchors pinned to frames (ADR 0049): `motionpath`'s curve with its middle point + // pinned to frame 17, and the star moved up on frame 35, which pinned a new point + // there. Subselection on that point, the span selected, and the Motion Editor on + // Y (or the timeline, with its diamonds at the pinned frames). + self.open_panel(Some("motionpath")); + self.run("motion.pin_point", json!({"anchor": 1, "frame": 16})); + self.run("timeline.goto", json!({"frame": 34})); + self.run("element.translate", json!({"dx": 20, "dy": -110})); + self.s.mark_saved(); + self.run("timeline.goto", json!({"frame": 24})); + self.run("element.select", json!({"ids": []})); + self.frame_sel = Some(timeline::FrameSel::cell(self.s.layer, 24)); + self.tool = Tool::Subselect; + self.motion_anchors = vec![2]; + if which == "motionpins" { + self.bottom = BottomTab::MotionEditor; + } + self.me_prop = anicraft_engine::doc::Property::Y; + self.me_key = None; + } Some("pen") => { // A pen path still being drawn: a corner, a smooth point with handles, a corner. self.tool = Tool::Pen; diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 0023ff9d..45096bc0 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", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple"] { + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple"] { 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 d4ea7ea9..29a3838d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -176,7 +176,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|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope]\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|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]\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/motion_editor.rs b/src/motion_editor.rs index f4b51ed4..2400e223 100644 --- a/src/motion_editor.rs +++ b/src/motion_editor.rs @@ -6,11 +6,15 @@ //! the span. Drag a key up or down to change its value, drag the two handles of the selected //! segment to shape its ease (a cubic Bézier), click to move the playhead, double-click to add //! a key. Every drag is one undo step (a session gesture); every change is a command. +//! +//! On X and Y, the keys of frames pinned to a motion path point (ADR 0049) are drawn in the +//! motion colour: they are the point's place and its timing, so dragging one moves the point on +//! the stage, and removing one unpins it. 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, Property, Props, Track}; +use anicraft_engine::doc::{Easing, MotionTween, Pin, Property, Props, Track}; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, WidgetType, pos2, vec2}; use serde_json::json; @@ -117,6 +121,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.text(pos2(list.left() + 10.0, list.top() + RULER_H * 0.5), Align2::LEFT_CENTER, tr!("Property"), font(Type::Heading), color(Type::Heading)); painter.text(pos2(list.right() - 44.0, list.top() + RULER_H * 0.5), Align2::RIGHT_CENTER, tr!("Frame {frame}", frame = app.s.frame + 1), font(Type::DataSmall), color(Type::DataSmall)); let now = m.props_at(&base, offset as f32); + // Frames pinned to path points: their X and Y keys are the points' places (ADR 0049). + let pins = m.pinned_anchors(&base); + let pin_at = |p: Property, f: u32| pins.iter().find(|q| q.frame == f).copied().filter(|_| matches!(p, Property::X | Property::Y)); 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); @@ -174,7 +181,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_filled(toggle, T.rc(), T.hover); } diamond(&painter, toggle.center(), 5.0, if keyed { T.text } else { Color32::TRANSPARENT }, Stroke::new(1.5, if keyed { T.text } else { T.text_faint })); - let tip = if keyed { tr!("Remove the {property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1) } else { tr!("Add a {property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1) }; + let tip = match (keyed, pin_at(p, offset)) { + (true, Some(q)) if m.path.is_some() && interior(&pins, q) => tr!("Unpin point {anchor} of the motion path from frame {frame}: its X and Y keyframes go", anchor = q.anchor, frame = app.s.frame + 1), + (true, _) => tr!("Remove the {property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1), + (false, _) => tr!("Add a {property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1), + }; a11y::control(ui, &tr, WidgetType::Checkbox, &tr!("{property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1), Some(keyed)); if tr.on_hover_text(tip).clicked() { app.me_prop = p; @@ -277,7 +288,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { for &(f, v, _) in &keys { let c = pos2(x_of(f as f32), y_of(v)); let picked = sel_key == Some(f); - diamond(&gp, c, if picked { 6.5 } else { 5.5 }, if picked { T.accent } else { T.text }, Stroke::new(1.0, T.ink)); + if pin_at(p, f).is_some() { + // A path point's place: the motion colour, ringed like the stage's pinned points. + diamond(&gp, c, if picked { 7.5 } else { 6.5 }, if picked { T.accent } else { T.tween_motion }, Stroke::new(1.5, T.ink)); + } else { + diamond(&gp, c, if picked { 6.5 } else { 5.5 }, if picked { T.accent } else { T.text }, Stroke::new(1.0, T.ink)); + } + } + if matches!(p, Property::X | Property::Y) && pins.len() > 2 { + gp.text(pos2(graph.right() - 8.0, graph.bottom() - 6.0), Align2::RIGHT_BOTTOM, tr!("Blue keys are pinned motion path points: drag one to move its point"), font(Type::Caption), T.tween_motion); } // ---- graph interaction ------------------------------------------------------------------- @@ -380,11 +399,19 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.me_key = Some(f - start); } } - 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.")); + match hover.and_then(near_key).and_then(|f| pin_at(p, f)) { + Some(q) => gr.on_hover_text_at_pointer(tr!("Frame {frame} · point {anchor} of the motion path: drag to move the point", frame = start + q.frame + 1, anchor = q.anchor)), + 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); } +/// Whether `q` is a pin between the ends (which can be let go). +fn interior(pins: &[Pin], q: Pin) -> bool { + pins.first() != Some(&q) && pins.last() != Some(&q) +} + /// The value distance a segment's handles are measured against: the segment's own rise, or a /// quarter of the view for a flat segment (whose ease then shows no change until its ends /// differ). diff --git a/src/motion_path.rs b/src/motion_path.rs index a9d40f66..94d272d8 100644 --- a/src/motion_path.rs +++ b/src/motion_path.rs @@ -12,14 +12,19 @@ //! * **Ctrl-drag** (⌘ on macOS) the path or its object, with Selection or Subselection, to move //! the whole path; the timing stays. //! +//! Anchors pinned to frames (ADR 0049) are diamonds, the keyframe mark, with their frame number +//! beside them; the others are squares that only shape the path. Selection takes the ends and the +//! pinned anchors; the right-click menu pins a Subselection anchor to the playhead's frame or +//! unpins it. +//! //! A tween without a path of its own shows the straight path its X/Y curves trace; the first //! edit makes it a path. Every change is a `motion.*` command, and a drag is one undo step (a //! session gesture). Only the anchor selection and the drag in progress live here. use crate::app::{App, Drag, Tool}; use crate::pathtools::Xf; -use crate::theme::T; -use anicraft_engine::doc::{ElementId, Props}; +use crate::theme::{T, Type, font}; +use anicraft_engine::doc::{ElementId, Pin, Props}; use anicraft_engine::geom::edit::{ANCHOR, C1, C2}; use anicraft_engine::geom::{Affine, Path, PathCmd, Vec2}; use egui::{Key, Modifiers, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; @@ -52,10 +57,37 @@ pub struct Shown { pub keys: Vec, /// The playhead's frame in the span. pub offset: u32, + /// The span's first frame. + pub start: u32, + /// The anchors tied to frames (from the span's start), ends included, in order (ADR 0049). + pub pins: Vec, /// The object travelling it. pub target: ElementId, } +impl Shown { + /// The pin on anchor `a`, if it is tied to a frame. + pub fn pin(&self, a: usize) -> Option { + self.pins.iter().find(|p| p.anchor as usize == a).copied() + } + + /// Whether anchor `a` is an end (always pinned). + fn is_end(&self, a: usize) -> bool { + is_end(a, self.path.cmds.len()) + } + + /// Why anchor `a` can't be pinned to the playhead's frame, or `None` when it can. + fn unpinnable(&self, a: usize) -> Option { + let (Some(first), Some(last)) = (self.pins.first(), self.pins.last()) else { return Some(tr!("The object doesn't move yet").into()) }; + let f = self.offset; + if !(first.frame < f && f < last.frame) { + return Some(tr!("Move the playhead between frames {first} and {last}, where the object moves along the path", first = self.start + first.frame + 1, last = self.start + last.frame + 1)); + } + let a = a as u32; + self.pins.iter().find(|p| p.frame != f && p.anchor != a && (p.frame < f) != (p.anchor < a)).map(|p| tr!("Point {anchor} is pinned to frame {frame}: pins keep the path's order", anchor = p.anchor, frame = self.start + p.frame + 1)) + } +} + /// The motion path of the active layer's motion tween at the playhead, when its object or a /// frame of its span is selected and it moves at all. pub fn shown(app: &App) -> Option { @@ -77,18 +109,19 @@ pub fn shown(app: &App) -> Option { let mut keys: Vec = [anicraft_engine::doc::Property::X, anicraft_engine::doc::Property::Y].into_iter().filter_map(|p| m.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).filter(|f| *f < k.duration).collect(); keys.sort_unstable(); keys.dedup(); - Some(Shown { path, dots, keys, offset: app.s.frame - k.start, target: target.id }) + let pins = m.pinned_anchors(&base); + Some(Shown { path, dots, keys, offset: app.s.frame - k.start, start: k.start, pins, target: target.id }) } -/// The anchors the tool can take: both ends with Selection, every anchor with Subselection -/// (and shown to the Pen, which adds between them). -fn grabbable_anchors(path: &Path, tool: Tool) -> Vec<(usize, Vec2)> { +/// The anchors the tool can take: the ends and the pinned anchors with Selection (the motion's +/// keyframes), every anchor with Subselection (and shown to the Pen, which adds between them). +fn grabbable_anchors(path: &Path, pins: &[Pin], tool: Tool) -> Vec<(usize, Vec2)> { let all = path.anchors(); match tool { Tool::Subselect | Tool::Pen => all, _ => { let n = all.len(); - all.into_iter().enumerate().filter(|(i, _)| *i == 0 || *i + 1 == n).map(|(_, a)| a).collect() + all.into_iter().enumerate().filter(|(i, _)| *i == 0 || *i + 1 == n || pins.iter().any(|p| p.anchor as usize == *i)).map(|(_, a)| a).collect() } } } @@ -125,7 +158,7 @@ pub fn hit(app: &App, shown: &Shown, p: Pos2, xf: Xf, segments: bool) -> Option< } } } - if let Some((cmd, _)) = grabbable_anchors(&shown.path, app.tool).into_iter().find(|(_, q)| near(*q)) { + if let Some((cmd, _)) = grabbable_anchors(&shown.path, &shown.pins, app.tool).into_iter().find(|(_, q)| near(*q)) { return Some(Grab::Anchor(cmd)); } if segments && app.tool == Tool::Select { @@ -289,6 +322,22 @@ pub fn delete_selected(app: &mut App) { } } +/// Pins anchor `a` to the playhead's frame (ADR 0049): the object passes it exactly then. +pub fn pin_anchor(app: &mut App, a: usize) { + if let Some(v) = app.run("motion.pin_point", json!({"anchor": a})) { + let frame = v["frame"].as_u64().unwrap_or(0) + 1; + app.status_ok(tr!("Pinned point {anchor} to frame {frame}: the object passes it then. {undo} to undo.", anchor = a, frame = frame, undo = app.undo_key())); + } +} + +/// Lets anchor `a`'s pin go: it shapes the path only, and its frame's X/Y keys go. +pub fn unpin_anchor(app: &mut App, a: usize) { + if let Some(v) = app.run("motion.unpin_point", json!({"anchor": a})) { + let frame = v["frame"].as_u64().unwrap_or(0) + 1; + app.status_ok(tr!("Unpinned point {anchor} from frame {frame}: it shapes the path only. {undo} to undo.", anchor = a, frame = frame, undo = app.undo_key())); + } +} + /// Makes the selected anchors smooth or corners (one undo step). pub fn convert_selected(app: &mut App, smooth: bool) { let anchors = selected(app); @@ -359,7 +408,8 @@ pub fn menu(app: &mut App, ui: &mut egui::Ui) -> bool { return false; } let anchors = selected(app); - let Some(n) = shown(app).map(|s| s.path.cmds.len()) else { return false }; + let Some(shown) = shown(app) else { return false }; + let n = shown.path.cmds.len(); if anchors.is_empty() { return false; } @@ -372,6 +422,34 @@ pub fn menu(app: &mut App, ui: &mut egui::Ui) -> bool { ui.close(); } ui.separator(); + // Pinning to frames (ADR 0049): one anchor at a time, to the playhead's frame. + if let [a] = anchors[..] { + let frame = shown.start + shown.offset + 1; + match shown.pin(a) { + Some(p) if shown.is_end(a) => { + ui.add_enabled(false, egui::Button::new(tr!("Pinned to Frame {frame}", frame = shown.start + p.frame + 1))).on_disabled_hover_text(tr!("The ends of a motion path are always pinned, to the first and last position keys")); + } + Some(p) => { + if ui.button(tr!("Unpin from Frame {frame}", frame = shown.start + p.frame + 1)).on_hover_text(tr!("The point shapes the path only; its frame's X and Y keyframes go")).clicked() { + unpin_anchor(app, a); + ui.close(); + } + } + None => { + let why = shown.unpinnable(a); + let resp = ui.add_enabled(why.is_none(), egui::Button::new(tr!("Pin to Frame {frame}", frame = frame))); + let resp = match why { + Some(why) => resp.on_disabled_hover_text(why), + None => resp.on_hover_text(tr!("The object passes this point exactly on frame {frame}", frame = frame)), + }; + if resp.clicked() { + pin_anchor(app, a); + ui.close(); + } + } + } + ui.separator(); + } let deletable = anchors.iter().any(|a| !is_end(*a, n)); let label = if anchors.len() > 1 { tr!("Delete Points") } else { tr!("Delete Point") }; let resp = ui.add_enabled(deletable, egui::Button::new(label)); @@ -418,6 +496,17 @@ fn anchor_box(painter: &Painter, c: Pos2, filled: bool) { painter.rect_stroke(r, 0.0, Stroke::new(1.5, T.tween_motion), StrokeKind::Middle); } +/// A pinned anchor: a diamond (the keyframe mark) with its frame number in a tag beside it. +fn pinned_anchor(painter: &Painter, c: Pos2, filled: bool, frame: u32) { + let r = 5.5; + let pts = vec![c + vec2(0.0, -r), c + vec2(r, 0.0), c + vec2(0.0, r), c + vec2(-r, 0.0)]; + painter.add(egui::Shape::convex_polygon(pts, if filled { T.tween_motion } else { T.ink }, Stroke::new(1.5, T.tween_motion))); + let g = painter.layout_no_wrap(frame.to_string(), font(Type::DataSmall), T.ink); + let tag = Rect::from_min_size(c + vec2(r + 3.0, -r - g.size().y - 1.0), g.size() + vec2(6.0, 2.0)); + painter.rect_filled(tag, T.rc(), T.tween_motion); + painter.galley(tag.min + vec2(3.0, 1.0), g, T.ink); +} + /// Draws the path: a line in the motion colour on a dark halo (it reads on any artwork), a dot /// per frame, larger on position keys and ringed at the playhead, and the anchors the tool can /// take (with the selected anchors' handles under Subselection). `hot` is what the pointer is @@ -455,8 +544,12 @@ pub fn draw(app: &App, painter: &Painter, shown: &Shown, xf: Xf, hot: Option pinned_anchor(painter, xf.to_screen(q), lit, shown.start + p.frame + 1), + None => anchor_box(painter, xf.to_screen(q), lit), + } } } } @@ -495,10 +588,12 @@ mod tests { let q = dragged(&p, Grab::Segment(1, 0.5), Vec2::new(0.0, 20.0), false); assert!(q.segment_point(1, 0.5).unwrap().distance(before + Vec2::new(0.0, 20.0)) < 1e-3); assert_eq!(q.point(1, ANCHOR), p.point(1, ANCHOR)); - // Selection takes only the ends; Subselection every anchor, and the Pen sees them all. - assert_eq!(grabbable_anchors(&p, Tool::Select).iter().map(|a| a.0).collect::>(), vec![0, 2]); - assert_eq!(grabbable_anchors(&p, Tool::Subselect).len(), 3); - assert_eq!(grabbable_anchors(&p, Tool::Pen).len(), 3); + // Selection takes the ends and pinned anchors; Subselection every anchor, and the Pen + // sees them all. + assert_eq!(grabbable_anchors(&p, &[], Tool::Select).iter().map(|a| a.0).collect::>(), vec![0, 2]); + assert_eq!(grabbable_anchors(&p, &[Pin { frame: 5, anchor: 1 }], Tool::Select).len(), 3); + assert_eq!(grabbable_anchors(&p, &[], Tool::Subselect).len(), 3); + assert_eq!(grabbable_anchors(&p, &[], Tool::Pen).len(), 3); assert_eq!(handles(&p, &[1]), vec![(1, C2, 1), (2, C1, 1)]); assert_eq!(handles(&p, &[0]), vec![(1, C1, 0)]); assert_eq!(handles(&p, &[0, 2]), vec![(1, C1, 0), (2, C2, 2)], "every selected anchor shows its handles"); @@ -670,6 +765,51 @@ mod tests { } } + #[test] + fn pinning_from_the_menu_pins_to_the_playhead_and_unpinning_lets_go() { + let mut app = app(); + let s = shown(&app).unwrap(); + assert_eq!(s.pins.len(), 2, "only the ends are pinned"); + assert!(s.is_end(0) && s.pin(1).is_none()); + assert_eq!(s.unpinnable(1), None, "frame 10 is inside the motion"); + let steps = app.s.history().undo_len(); + pin_anchor(&mut app, 1); + assert_eq!(app.s.history().undo_len(), steps + 1); + assert!(status(&app).starts_with("Pinned point 1 to frame 10"), "{}", status(&app)); + let s = shown(&app).unwrap(); + assert_eq!(s.pin(1), Some(Pin { frame: 9, anchor: 1 })); + assert!(s.dots[9].distance(anchor(&s, 1)) < 1e-3, "the object is on the pinned anchor on its frame"); + // Selection now takes the pinned anchor too. + app.tool = Tool::Select; + assert_eq!(hit(&app, &s, screen(anchor(&s, 1)), XF, false), Some(Grab::Anchor(1))); + unpin_anchor(&mut app, 1); + assert!(status(&app).starts_with("Unpinned point 1 from frame 10"), "{}", status(&app)); + assert!(shown(&app).unwrap().pin(1).is_none()); + // Outside the motion the menu says why it can't pin. + app.s.set_frame(0); + assert!(shown(&app).unwrap().unpinnable(1).is_some_and(|w| w.contains("between frames 1 and"))); + } + + #[test] + fn the_menu_offers_pin_unpin_and_shows_an_ends_frame() { + let (mut app, ctx) = app_and_ctx(); + for anchors in [vec![1], vec![0], vec![2]] { + app.motion_anchors = anchors; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(menu(&mut app, ui)); + }); + out.textures_delta.clear(); + } + pin_anchor(&mut app, 1); + app.motion_anchors = vec![1]; + let s = shown(&app).unwrap(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(menu(&mut app, ui)); + draw(&app, ui.painter(), &s, XF, Some(Grab::Anchor(1))); + }); + out.textures_delta.clear(); + } + #[test] fn upkeep_forgets_anchors_the_path_lost() { let mut app = app(); diff --git a/src/panels.rs b/src/panels.rs index 94456ccc..36e64f91 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -1319,6 +1319,33 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L } }); } + // Points pinned to frames (ADR 0049), and the keyboard route to pinning at the + // playhead. + let pins = base.map(|b| m.pinned_anchors(&b)).unwrap_or_default(); + if let (Some(&first), Some(&last)) = (pins.first(), pins.last()) { + let offset = frame.saturating_sub(k.start); + let n = pins.len().saturating_sub(2); + row_prose(ui, tr!("Pinned"), |ui| { + let how = tr!("Points of the motion path pinned to frames: the object passes each one exactly then, and the X and Y keyframes there are its place. The ends are always pinned. Moving the object on the stage at a frame pins a point there; with the Subselection tool (A), right-click a point to pin or unpin it."); + ui.label(text(Type::Body, trn!("{n} point", "{n} points", n))).on_hover_text(how); + match pins.iter().find(|q| q.frame == offset) { + Some(&q) if q != first && q != last => { + let tip = tr!("Point {anchor} shapes the path only again; the X and Y keyframes of frame {frame} go", anchor = q.anchor, frame = frame + 1); + if ui.small_button(tr!("Unpin")).on_hover_text(tip).named(tr!("Unpin the motion path point at this frame")).clicked() { + app.run("motion.unpin_point", json!({"frame": frame})); + } + } + Some(_) => {} + None if first.frame < offset && offset < last.frame => { + let tip = tr!("Add a point where the object is on frame {frame}, pinned to it: nothing moves now, and the object passes the point then however the path is edited", frame = frame + 1); + if ui.small_button(tr!("Pin Here")).on_hover_text(tip).named(tr!("Pin the motion path at this frame")).clicked() { + app.run("motion.pin_point", json!({"frame": frame})); + } + } + None => {} + } + }); + } let mut orient = m.orient; if crate::theme::checkbox(ui, &mut orient, tr!("Orient to path")).on_hover_text(tr!("Turn the object as its motion path turns")).named(tr!("Orient to path")).changed() { app.run("motion.orient", json!({"orient": orient})); diff --git a/src/timeline.rs b/src/timeline.rs index 871dbc07..5f79b04b 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -586,11 +586,18 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } let kc = pos2(x0 + cell_w * 0.5, y + ROW_H * 0.5); if let Some(m) = motion { - // Property keyframes: small diamonds where any property has a key. + // 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 + // stage marks that point. + let pins = m.live_pins(); for f in m.key_frames().into_iter().filter(|f| *f > 0 && *f < k.duration) { let c = pos2(x_of(k.start + f) + cell_w * 0.5, kc.y); - let r = (cell_w * 0.35).clamp(2.5, 4.5); + let pinned = pins.iter().any(|p| p.frame == f); + let r = (cell_w * 0.35).clamp(2.5, 4.5) + if pinned { 1.0 } else { 0.0 }; cp.add(egui::Shape::convex_polygon(vec![c + vec2(0.0, -r), c + vec2(r, 0.0), c + vec2(0.0, r), c + vec2(-r, 0.0)], T.ink, Stroke::NONE)); + if pinned { + cp.circle_filled(c, r * 0.4, T.tween_motion); + } } } else if tweened && k.duration > 1 { let end = pos2(x1 - cell_w * 0.5 - 4.0, kc.y); From 6e5784d2b6b5401c0c1a084b63fbbc09935eff24 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:57:35 -0700 Subject: [PATCH 015/402] docs: ADR 0049 motion path pins, ADR 0030/0038 notes, roadmap and changelog (M2) --- CHANGELOG.md | 18 ++++ docs/adr/0030-motion-paths.md | 9 +- docs/adr/0038-motion-path-points.md | 8 +- docs/adr/0049-motion-path-pins.md | 138 ++++++++++++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 4 +- 6 files changed, 170 insertions(+), 8 deletions(-) create mode 100644 docs/adr/0049-motion-path-pins.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 3aee6023..19a9b140 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## Unreleased +* **Motion path points pinned to frames** (ADR 0049, M2). As in Animate, a motion tween's + position keyframes are now points on its path: move the object at a frame and the path gets a + point there that the object passes exactly on that frame, whatever else you do to the path. + * Moving the object between the ends adds a pinned point where you put it; after the last + position keyframe the path carries on to the new place. The eases on X and Y time the + object between pinned points as they did between the ends. + * Pinned points are diamonds with their frame number on the stage, and Selection can drag + them. With Subselection, right-click any point to **Pin to Frame** (the playhead's frame) + or **Unpin**. Properties › Frame has **Pin Here** / **Unpin**, and F6 inside a path tween + pins where the object is. + * The Motion Editor draws a pinned frame's X and Y keys in blue; dragging one moves its + point. The timeline marks pinned frames with a larger diamond. + * Adding and deleting points keeps the pins on their points; deleting a pinned point, or + unpinning it, removes its frame's X and Y keys and the motion flows as before. + * Older files open and play exactly as they did (only the ends are pinned). + * Headless: new `motion.pin_point` and `motion.unpin_point`; `motion.info` and the path + commands report `pins`. + * **Stroke caps, joins, miter limit, and dashed and dotted lines** (ADR 0046, M7). Properties › Stroke has Animate's rows: **Style** (Solid, Dashed with a dash and gap editor, Dotted with dot spacing), **Cap** (None, Round, Square), **Join** (Miter, Round, Bevel) and **Miter** diff --git a/docs/adr/0030-motion-paths.md b/docs/adr/0030-motion-paths.md index d6b73af4..0652c711 100644 --- a/docs/adr/0030-motion-paths.md +++ b/docs/adr/0030-motion-paths.md @@ -1,6 +1,6 @@ # ADR 0030: Motion paths for motion tweens -* Status: accepted (2026-11-09) +* Status: accepted (2026-11-09); §4 between the ends superseded by ADR 0049 (pins) * Relates to: ADR 0016 (motion tweens), ADR 0003 (file format), ADR 0004 (destructive actions), roadmap M2 @@ -88,7 +88,10 @@ and loses nothing irreversible, so it doesn't ask (ADR 0004). * A path's anchors are not tied to frames: an anchor in the middle of the path is reached when the timing says so, not on a frame of its own. Moving the object at a middle frame bends the - path through that point rather than adding an anchor there. + path through that point rather than adding an anchor there. *Since ADR 0049, anchors can be + pinned to frames, and moving the object at a middle frame pins a new anchor there instead; + this timing still applies, leg by leg between pinned anchors, and is unchanged for files + without pins.* * The X/Y values the Motion Editor shows are timing on a path, not the object's place. Editing them retimes the motion along the path. * Performance: evaluating a tween on an 8-segment path with orient takes 10–15 µs per object @@ -96,7 +99,7 @@ and loses nothing irreversible, so it doesn't ask (ADR 0004). measured on the development machine, release and dev profiles). * Adding, deleting and converting path points and moving the whole path came next, in ADR 0038, which also explains why anchors tied to frames wait for a model change. -* Not yet (later PRs): position keys as anchors (spatial keys), copying and pasting +* Not yet (later PRs): ~~position keys as anchors (spatial keys)~~ (done in ADR 0049), copying and pasting a path from a stroke or onto a guide, ease along the path for loop paths, the path shown for tweens inside symbols edited in place, snapping the ends, and importing motion paths from XFL (motion tween import still waits on samples, ADR 0016). diff --git a/docs/adr/0038-motion-path-points.md b/docs/adr/0038-motion-path-points.md index 145e9a32..958f2c96 100644 --- a/docs/adr/0038-motion-path-points.md +++ b/docs/adr/0038-motion-path-points.md @@ -1,6 +1,6 @@ # ADR 0038: Editing motion path points and moving the whole path -* Status: accepted (2026-11-09) +* Status: accepted (2026-11-09); anchors tied to frames came in ADR 0049 * Relates to: ADR 0030 (motion paths), ADR 0016 (motion tweens), ADR 0004 (destructive actions), roadmap M2 @@ -97,6 +97,10 @@ the timing model of ADR 0030 cleanly: Until then, moving the object at a frame bends the path through that point (ADR 0030 §4), which covers the common "be here on this frame" case without a new model. +*ADR 0049 does this: pinned anchors with frames, whose X/Y keys hold their place, cutting the +timing into legs. Point edits keep pins on their anchors, deleting a pinned point lets its pin +go, and unpinning brings back this ADR's behaviour.* + ## Consequences * The X/Y keys never change from a point edit, so retiming and path editing stay independent. @@ -111,7 +115,7 @@ which covers the common "be here on this frame" case without a new model. Most of the cost is measuring the path again (`CurveWalk`) and snapshotting the keyframe. * Not yet (later PRs): - * anchors tied to frames (above); + * ~~anchors tied to frames (above)~~ (ADR 0049); * a marquee over motion path anchors; * arrow-key nudging and Free Transform (scale, rotate) of a whole path; * deleting an end by giving the start to the next anchor (with its keys); diff --git a/docs/adr/0049-motion-path-pins.md b/docs/adr/0049-motion-path-pins.md new file mode 100644 index 00000000..040965a7 --- /dev/null +++ b/docs/adr/0049-motion-path-pins.md @@ -0,0 +1,138 @@ +# ADR 0049: Motion path anchors pinned to frames + +* Status: accepted (2026-11-10) +* Relates to: ADR 0030 (motion paths), ADR 0038 (motion path points), ADR 0016 (motion + tweens), ADR 0003 (file format), ADR 0004 (destructive actions), roadmap M2 + +## Context + +ADR 0030 gave motion tweens a path that the object travels by arc length, timed by the X/Y +curves. Only the path's ends were tied to frames: the first and last position keys. A middle +anchor was reached whenever the timing got there, and moving the object at a middle frame bent +the path through that point without adding a key. ADR 0038 left anchors tied to frames out, +because a pinned anchor would compete with the X/Y curves for the timing. + +In Animate, a motion tween's position keyframes *are* the path's anchors. Moving the object at +frame 12 adds an anchor the object passes on frame 12, and the eases set the speed between those +anchors. Artists coming from Animate expect to say "be here on this frame" and have it hold +while they keep editing the path. We learned this from Adobe's public help pages and from +watching the program. Nothing was copied. + +## Decision + +1. **A pin ties an anchor to a frame.** `MotionTween.pins: Vec` + (`crates/doc/src/motion.rs`) lists the anchors between the ends that are pinned, by frame. + Frames and anchors both increase, so a later frame is always on a later anchor. The ends are + always pinned, to the first and last position keys, and they are not stored. A pin's frame + holds X and Y keys with the anchor's place, so the X/Y curves pass through every pinned + anchor and stay a truthful picture of the motion. Anchors that aren't pinned still shape the + path, as in ADR 0038. We chose this over the alternatives below: + * Making every position key an anchor would break older files. Their middle position keys + are timing keys under ADR 0030, and they would have to be turned into anchors, which moves + objects. + * Giving anchors a frame of their own, separate from the keys, would mean two sources of + timing. That is the conflict ADR 0038 described. +2. **Timing goes leg by leg.** The pinned anchors, ends included, cut the span into legs. On each + leg, ADR 0030's rule applies to the stretch of path between its two anchors: + * Position keys inside the leg split it into pieces. + * On each piece, how far along its chord the X/Y curves are (signed) is how far along the + piece's share of the stretch the object is. The shares are the chords' lengths. + * A leg whose chords add up to nothing (a loop) is crossed at an even pace. + + The results: + * the object is **exactly on each pinned anchor on its frame**; + * eases, holds and overshoot work between pins as they did between the ends; + * a straight path still reproduces the X/Y curves exactly, pins or not; + * **with no pins, it is ADR 0030's arithmetic, number for number.** A test compares + evaluation bit for bit with a copy of the old code, over eased, overshooting and middle-key + tweens and a loop. + + `CurveWalk::anchor_distance` gives each anchor's distance along the path. `evaluate` stays + pure. +3. **Pinning and unpinning.** + * `MotionTween::pin(anchor, frame)` writes the anchor's place as the X/Y keys on that frame. + A pin already on that frame, or the same anchor's pin on another frame, gives way (that is + how a pin is retimed). A pin that would break the order is refused, and the refusal names + the pin in the way. + * `pin_here(frame)` pins where the object is. It uses the anchor there, or splits the path at + that point (the curve unchanged), so nothing moves on that frame. + * `unpin(frame)` removes the pin **and its frame's X/Y keys**. The anchor stays and shapes the + path only. Pinning a frame without keys and then unpinning it gives back the same tween, + key for key. So unpinning brings back ADR 0038's behaviour instead of leaving timing keys + where the pin was. + * Removing the X or Y key of a pinned frame unpins it, taking both keys. A pin always has + both. +4. **The path keeps its pins.** + * `set_path` writes each pin's anchor place as its keys. Keys that already hold the place + stay exactly as they are, so editing elsewhere never changes the timing. + * Adding a point moves the later pins' indices up with their anchors. + * Deleting a pinned point lets its pin go, with its keys. `motion.delete_points` reports how + many it unpinned. + * Moving the whole path, splitting a span (pins after the cut move to the second half, + re-indexed onto the cut path) and Straighten keep the meaning. Straighten forgets the pins, + but their keys stay as the straight path's corners. + * A tween without a path of its own shows the straight path through its position keys, and + those keys are pinned to its corners. The first edit that makes the path the tween's own + keeps them pinned when the edited path has as many anchors. A path of another shape is a + new path: only its ends are pinned. +5. **Auto-key pins** (replacing ADR 0030 §4 between the ends). Moving the object on a path at a + frame: + * at a pinned frame (an end or a pin), moves that anchor with its handles, and its keys + follow; + * before the first position key, moves the start (as before); + * between the ends, adds an anchor where the object is, pins it to that frame and moves it: + Animate's "move it on frame 12, it passes there on frame 12"; + * after the last position key, carries the path on in a straight stretch to where the object + was put. The new end is reached on that frame, and the old end stays pinned to its frame. + + Only where the object is off the path (an ease overshooting an end) does the old least-squares + bend remain. A stage drag is one gesture, so it makes one pin and one undo step. Insert + Keyframe (F6) inside a path tween pins where the object is. +6. **The Motion Editor shows X/Y keys as anchor timing.** On X and Y, a pinned frame's key is + drawn larger in the motion colour. A note explains the blue keys, and the hover says which + point a key belongs to. Setting the X or Y key of a pinned frame (dragging it in the graph or + typing the value) moves the anchor, and the stage follows. That holds for the ends too, which + ADR 0030 left inconsistent. The key toggle on a pinned frame says it unpins. +7. **On the stage** (`src/motion_path.rs`): + * Pinned anchors are diamonds, the keyframe mark, with their frame number on a tag beside + them. The other anchors stay squares. + * Selection takes the ends and the pinned anchors (the motion's keyframes). Subselection + takes every anchor. + * Subselection's right-click menu has *Pin to Frame n* (the playhead's frame). It is + disabled, with the reason, outside the motion or out of order. It also has *Unpin from + Frame n*, and for an end, a disabled *Pinned to Frame n* that says why. + * The timeline draws a larger diamond with a hole at pinned frames. + * Properties › Frame shows how many points are pinned, with *Pin Here* or *Unpin* at the + playhead. That is the keyboard and screen-reader route. +8. **Headless.** `motion.pin_point {anchor?, frame?}` pins an anchor to the frame, or, without + `anchor`, pins where the object is. `motion.unpin_point {anchor? | frame?}` unpins. + `motion.info` and every path command's result list `pins` as `{anchor, frame, end, at}`, ends + included, frames counted from the timeline's start. Unpinning is undoable and loses nothing + irreversible, so it doesn't ask (ADR 0004). +9. **File format.** `pins` is additive, `#[serde(default)]`, and not written when it is empty. A + file from before pins has none and evaluates exactly as before. Loading drops pins that + can't hold: out of order, outside the position keys, on an end or a missing anchor, or on a + tween without a path. An older build ignores the field. It still has the pins' X/Y keys, so + it shows the same path with those frames as timing keys (close to the pinned motion, but not + exact). + +## Consequences + +* "Be here on this frame" now holds through later path edits, the way it does in Animate. Bending + a segment, moving other anchors or adding points never moves a pinned frame's place. +* ADR 0030's statement that a middle anchor is reached "when the timing says so" now holds for + unpinned anchors only. ADR 0038's "anchors tied to frames: not in this slice" is this ADR. +* An X or Y key added in the Motion Editor on a path frame that isn't pinned is still a timing + key (ADR 0030). Pinning is a deliberate act: the stage, F6, the menu, Properties or the command. +* Performance, measured with the optimised dev profile on the development machine, on an + 8-segment oriented path: evaluating a frame takes 3.3 µs per object without pins and 4.0 µs + with 7 pins. The stage's 97 frame dots take 9.5 µs and 11.4 µs. Release builds are 6–16% + faster. The cost is the per-call list of live pins and one binary search per pin. +* Not yet (later PRs): + * dragging keys in time in the Motion Editor or on the timeline to retime a pin (re-pinning to + another frame does it today); + * two pins on one anchor (a hold is an ease or a timing key today); + * the pins' frame tags avoiding each other where points crowd; + * pins on loop paths whose start and end meet; + * importing Animate's motion path keyframes from XFL (motion tween import still waits on + samples, ADR 0016). diff --git a/docs/adr/README.md b/docs/adr/README.md index 332df53a..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 | -| 0049 | m2/path-pins | Motion path anchors pinned to frames | diff --git a/docs/roadmap.md b/docs/roadmap.md index 662323b9..87d4fec4 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). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, 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`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **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. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path`). Not yet: anchors tied to frames (spatial keys, a model change: ADR 0038), 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), 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`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **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: a marquee across several layers, snapping while drawing, width profiles in the merge, deleting or adding raw anchors, smooth handle pairs. **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. | @@ -32,7 +32,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); ~~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; spatial keys, 3D and XFL import later); ~~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); ~~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 deferred (not the bottleneck as tiles); ~~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: 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); not yet: `.fla` variants of the corpus, sound and video items; ~~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 1be002ace7033a1e1ad00e4d2b2a8bda06039d97 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:12:24 -0700 Subject: [PATCH 016/402] fix(doc): only pins in force route an X/Y key removal; stale pins go (M2) --- crates/doc/src/motion.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index a79de542..bbe806a3 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -920,12 +920,20 @@ impl MotionTween { /// Removes property `p`'s key at `frame`; a track left with no keys goes. Whether a key was /// there. Removing the X or Y key of a pinned frame lets the pin go (with both keys). pub fn remove_key(&mut self, p: Property, frame: u32) -> bool { - if matches!(p, Property::X | Property::Y) && self.pins.iter().any(|q| q.frame == frame) { + if !matches!(p, Property::X | Property::Y) { + return self.remove_track_key(p, frame); + } + // Only pins in force count (removing an end's keys can leave one outside the motion). + self.pins = self.live_pins(); + if self.pins.iter().any(|q| q.frame == frame) { let had = self.track(p).is_some_and(|t| t.key_at(frame).is_some()); self.unpin(frame); return had; } - self.remove_track_key(p, frame) + let had = self.remove_track_key(p, frame); + // An end's key gone may leave pins outside the motion: they go, never to come back. + self.pins = self.live_pins(); + had } fn remove_track_key(&mut self, p: Property, frame: u32) -> bool { @@ -1484,6 +1492,14 @@ mod tests { assert!(pinned.remove_key(Property::X, 8)); assert!(pinned.pins.is_empty() && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_none())); assert_eq!(pinned, m); + // Removing the end's keys lets a pin that is no longer between the ends go; its keys + // stay as plain keys, removed one by one. + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(pinned.remove_key(Property::X, 20) && pinned.remove_key(Property::Y, 20)); + assert!(pinned.pins.is_empty(), "frame 8 is the last position key now: an end"); + assert!(pinned.remove_key(Property::X, 8)); + assert!(pinned.track(Property::X).is_some_and(|t| t.key_at(8).is_none()) && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_some())); + assert!(pinned.is_sane()); } /// ADR 0030's timing as it was before pins: what files without pins must still give. From 3a12a5f5a5efd663f732f39db2ecf8443233525f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:22:25 -0700 Subject: [PATCH 017/402] docs: reserve ADR 0048 for GPU binning and outlines (M3) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..f974a6d8 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 | +| 0048 | m3/gpu-binning | GPU stage, fourth slice: tile binning on the GPU, cheap outlines | From 0fbf8c5d0f5b67aeef1d94ed5f9bf36c4095555b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:48:46 -0700 Subject: [PATCH 018/402] feat(render): hairlines for outline mode, and integer tile backdrops in the GPU binning (M3) Outline mode (an outlined layer, onion skin's outlines) draws hairlines straight from the flattened path: coverage 1 - the distance to the nearest segment, one edge per segment where a stroked hairline was four plus a disc at every bend. Exact for axis- aligned lines, no darkening at overlaps and joins. The GPU stage computes the same. The binning's per-row float backdrops become one integer per tile plus a piece on the tile's left edge wherever the outline crosses it (Vello's backdrops and y-edges), which lets the GPU compute the same lists without float atomics. Parity unchanged. --- crates/gpu/examples/gpu_bench.rs | 81 ++++++-- crates/gpu/src/binning.rs | 316 ++++++++++++++++++++----------- crates/gpu/src/fine.wgsl | 54 ++++-- crates/gpu/src/tests.rs | 58 +++++- crates/render/src/hairline.rs | 169 +++++++++++++++++ crates/render/src/lib.rs | 53 +++++- crates/render/src/raster.rs | 29 ++- 7 files changed, 612 insertions(+), 148 deletions(-) create mode 100644 crates/render/src/hairline.rs diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index b932f0fb..a8df5239 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -11,7 +11,7 @@ //! stage's way (512 px tiles drawn in parallel, as the render service does, until finished); //! the work the fine pass did; and how far the GPU's picture is from the oracle's. -use anicraft_doc::{Bitmap, BitmapId, ColorEffect, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; +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_geom::{FillRule, Path}; use anicraft_gpu::{GpuRenderer, Output, compare_premul8}; use anicraft_geom::Affine; @@ -139,6 +139,57 @@ fn filtered() -> Document { doc } +/// Onion skin as the stage composes it (ADR 0047), for the bench: no onion skin, ±5 frames +/// tinted and fading, or ±5 frames as outlines. +#[derive(Clone, Copy, PartialEq)] +enum Onion { + Off, + Tinted, + Outlines, +} + +/// Frame `frame` with ±5 onion frames, as `anicraft_engine::onion::compose` draws them with +/// the default colours, tint and fade: each frame's items under the playhead's on their own +/// layer (nearest on top), at its alpha and tint, or as hairline outlines in its colour. (The +/// engine sits beside this crate, so the bench builds the same list itself.) +fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList { + let now = evaluate(doc, frame); + if mode == Onion::Off { + return now; + } + let frames = doc.frame_count().max(1); + let (past, future) = (Rgba::hex(0x4f8dff), Rgba::hex(0x4cd07d)); + let rank: std::collections::HashMap = doc.timeline(0).layers.iter().enumerate().map(|(i, l)| (l.id, i)).collect(); + let mut dl = DisplayList::default(); + let mut part_of: Vec = Vec::new(); + for d in (1..=5u32).rev() { + for (is_past, f) in [(true, frame.checked_sub(d)), (false, Some(frame + d).filter(|f| *f < frames))] { + let Some(f) = f else { continue }; + // Fading from 0.5 next to the playhead to 0.12 at the marker; tinted at 0.8. + let alpha = 0.5 + (0.12 - 0.5) * (d - 1) as f32 / 4.0; + 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 }); + if mode == Onion::Outlines && item.masks.is_none() { + item.outline = Some(color.with_alpha(alpha)); + } + } + part_of.extend(std::iter::repeat_n(part_of.last().map_or(0, |p| p + 1), part.items.len())); + dl.append(part); + } + } + let k = part_of.last().map_or(0, |p| p + 1); + part_of.extend(std::iter::repeat_n(k, now.items.len())); + dl.append(now); + // Layer by layer, bottom first; within a layer, the parts in order (a stable sort). + let mut order: Vec = (0..dl.items.len()).collect(); + order.sort_by_key(|&i| (std::cmp::Reverse(dl.items.get(i).and_then(|it| rank.get(&it.layer)).copied().unwrap_or(0)), part_of.get(i).copied().unwrap_or(0))); + let mut items: Vec> = std::mem::take(&mut dl.items).into_iter().map(Some).collect(); + dl.items = order.into_iter().filter_map(|i| items.get_mut(i).and_then(Option::take)).collect(); + dl +} + fn main() { let gpu = match GpuRenderer::new() { Ok(g) => g, @@ -150,24 +201,32 @@ fn main() { println!("adapter: {}", gpu.adapter); let (layers, shapes) = (arg("--layers", 50), arg("--shapes", 200)); let runs = arg("--runs", 12); - let scenes: Vec<(String, Document)> = vec![ - (format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)), - ("1,000 shapes".into(), sample::stress(5, 200, 240)), - (format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))), - ("sample".into(), sample::demo()), - ("composited sample".into(), composited()), - ("filtered sample".into(), filtered()), - ("200 bitmaps".into(), bitmaps()), + let only: Option = std::env::args().skip_while(|a| a != "--only").nth(1); + let onion_doc = sample::stress(20, 100, 48); + let plain = |name: String, doc: Document| (name, doc, Onion::Off); + let scenes: Vec<(String, Document, Onion)> = vec![ + plain(format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)), + plain("1,000 shapes".into(), sample::stress(5, 200, 240)), + plain("50,000 shapes".into(), sample::stress(250, 200, 240)), + plain(format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))), + plain("sample".into(), sample::demo()), + plain("composited sample".into(), composited()), + plain("filtered sample".into(), filtered()), + plain("200 bitmaps".into(), bitmaps()), + ("onion off 20×100".into(), onion_doc.clone(), Onion::Off), + ("onion ±5 tinted".into(), onion_doc.clone(), Onion::Tinted), + ("onion ±5 outlines".into(), onion_doc, Onion::Outlines), ]; println!( "{:<20} {:>10} {:>8} {:>9} {:>9} {:>9} {:>7} {:>22} {:>8} {:>8} parity (mean / max / differing px)", "scene", "size", "CPU ms", "readback", "direct", "direct+", "tiled", "prepare + bin + submit", "entries", "pieces" ); - for (name, doc) in &scenes { + for (name, doc, onion) in scenes.iter().filter(|(n, ..)| only.as_ref().is_none_or(|o| n.contains(o.as_str()))) { for scale in [1.0f32, 2.0] { let v = View::stage(doc, scale * 1920.0 / doc.stage.width as f32); let frames = doc.frame_count().max(1); - let dl0 = evaluate(doc, 0); + let evaluate = |doc: &Document, f: u32| onion_list(doc, f, *onion); + let dl0 = evaluate(doc, if *onion == Onion::Off { 0 } else { 30 }); // Warm-up (pipeline caches, allocations). let _ = gpu.render(&dl0, &v, Output::Premul8); let _ = gpu.render_texture(&dl0, &v); diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index c944a57d..7f0407c1 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -1,13 +1,26 @@ //! Tile binning: the CPU half of the GPU stage (ADR 0019, ADR 0029). //! //! The surface is cut into 16 × 16 pixel tiles. Every fill's edges are split at tile rows and -//! columns; each piece lands in the one tile it crosses. What a piece contributes to the tiles -//! to its right is a plain winding change per pixel row (it lies wholly to their left), so it -//! is summed into a **backdrop** of 16 values, one per pixel row, carried across the tile row -//! as in the public sparse-strips and Vello designs. A tile of a fill then needs only its own -//! pieces and its backdrop: the fine shader computes each pixel's exact area coverage from -//! those, the same integral the CPU oracle's accumulation buffer computes (ADR 0002). Tiles -//! with neither (outside the fill) get no entry; interior tiles get a backdrop and no pieces. +//! columns; each piece lands in the one tile it crosses. Everything left of a tile reaches it +//! as the fill's winding number along the tile's left edge (ADR 0048), which is +//! +//! * its **backdrop**, the winding number just below the tile's top-left corner: an integer, +//! the sum of the directions of the pieces further left that start on the tile row's top +//! edge (they are the edges crossing it), plus +//! * a step wherever the outline crosses the tile's left edge, kept as one more piece: a +//! vertical line on that edge from the crossing down to the tile's bottom, upwards where the +//! outline crosses rightwards (the winding there drops by one), downwards where it crosses +//! leftwards. +//! +//! These are the backdrops and "y-edges" of Vello's tiles (its public design notes). A tile of +//! a fill then needs only its own pieces and its backdrop: the fine shader computes each +//! pixel's exact area coverage from those, the same integral the CPU oracle's accumulation +//! buffer computes (ADR 0002). Tiles with neither (outside the fill) get no entry; interior +//! tiles get a backdrop and no pieces. Backdrops are integers, so they add up the same in any +//! order, and the GPU computes the same lists ([`crate::gpu_binning`]). +//! +//! A **hairline** (outline mode, ADR 0048) is binned by distance instead: each segment, whole, +//! into every tile with a pixel centre within its reach; the shader takes the nearest. //! //! Each tile then lists its entries in drawing order, so the shader composites every pixel in //! one pass, front to back in the display list's order. Masks and groups (ADR 0029) are more @@ -34,8 +47,10 @@ type Vec4 = [f32; 4]; /// Tile side in pixels (the shader's workgroup is one tile, one invocation per pixel). pub const TILE: u32 = 16; const T: f32 = TILE as f32; -/// "No backdrop" in an entry; "no clip" or "no group" in the tables. +/// "No clip" or "no group" in the tables. pub const NONE: u32 = u32::MAX; +/// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd). +pub const HAIRLINE: u32 = 2; /// `vec4`s of paint data per fill. pub const PAINT_VEC4S: usize = 4; /// Gradient table entries (the oracle's LUT size). @@ -97,11 +112,10 @@ pub fn blend_code(m: BlendMode) -> u32 { /// A scene ready for the fine shader. /// /// * `index` (u32): `[start, count]` per tile into the entry list; then each entry as -/// `[op, first piece, pieces, backdrop]` (the backdrop's first `vec4` in `geo`, or [`NONE`]), -/// or a control entry ([`CTRL`] set); then each op's header `[kind, fill rule, ramp start in -/// paints, flags]`. +/// `[op, first piece, pieces, backdrop]` (the backdrop an `i32`), or a control entry ([`CTRL`] +/// set); then each op's header `[kind, fill rule (or HAIRLINE), ramp start in paints, flags]`. /// * `geo` (`vec4`): pieces `(x0, y0, x1, y1)` relative to their tile's top-left, in the -/// edge's direction; then backdrops, four `vec4`s (16 rows) each. +/// edge's direction (left-edge steps included); a hairline's are its segments, whole. /// * `paints` (`vec4`): per op its colour, then the inverse paint transform and gradient, /// bitmap or layer parameters; then the gradient tables (256 premultiplied colours each); /// then (filled in on the GPU, [`Binned::layer_at`]) the filtered layers' pixels. @@ -133,11 +147,9 @@ pub struct Binned { /// A chunk of fills' share of the scene (binned in parallel; chunking keeps allocations few). #[derive(Default)] struct Local { - /// `[op, tile, first piece, pieces, backdrop or NONE]`, piece and backdrop indices local. + /// `[op, tile, first piece, pieces, backdrop]`, piece indices local. entries: Vec<[u32; 5]>, pieces: Vec<[f32; 4]>, - /// Backdrops, four `vec4`s (16 pixel rows) each. - backdrops: Vec<[f32; 4]>, } /// An edge piece inside one tile row, in absolute pixels; `col` is the tile column relative to @@ -204,6 +216,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let op_group: Vec = scene.fills.iter().map(|f| f.group.filter(|&g| (g as usize) < scene.groups.len()).unwrap_or(NONE)).collect(); let tables = Tables { fills: nf as u32, op_clip, op_group, clip_chain, art_ops, scene }; + let __t=std::time::Instant::now(); let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); let (tx, ty) = (tiles_x as usize, tiles_y as usize); @@ -232,20 +245,19 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result }) .collect(); - // Where each chunk's pieces and backdrops go in `geo`. + let __a=__t.elapsed().as_secs_f32()*1000.0; + // Where each chunk's pieces go in `geo`. let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); let mut piece_at = Vec::with_capacity(locals.len()); - let mut bd_at = Vec::with_capacity(locals.len()); - let (mut p, mut b) = (0usize, pieces); + let mut p = 0usize; for (l, _) in &locals { piece_at.push(p as u32); - bd_at.push(b as u32); p += l.pieces.len(); - b += l.backdrops.len(); } // Phase 2, parallel over tile rows: each tile's stream of entries. - let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &bd_at, &tables)).collect(); + let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &tables)).collect(); + let __b=__t.elapsed().as_secs_f32()*1000.0; let mut row_at = vec![0usize; ty + 1]; for (r, out) in rows.iter().enumerate() { row_at[r + 1] = row_at[r] + out.stream.len(); @@ -274,24 +286,24 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result } }); } - // Pieces, then backdrops, copied in parallel into their places. - let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; b]; + let __c=__t.elapsed().as_secs_f32()*1000.0; + // Pieces copied in parallel into their places. + let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; { - let (mut piece_dst, mut bd_dst) = geo.split_at_mut(pieces); - let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(2 * locals.len()); + let mut piece_dst = &mut geo[..]; + let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len()); for (l, _) in &locals { let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len()); jobs.push((a, &l.pieces)); piece_dst = rest; - let (a, rest) = std::mem::take(&mut bd_dst).split_at_mut(l.backdrops.len()); - jobs.push((a, &l.backdrops)); - bd_dst = rest; } jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s)); } // Tens of thousands of small buffers: free them on the pool, off the frame's path. anicraft_render::drop_in_background((locals, rows)); + let __d=__t.elapsed().as_secs_f32()*1000.0; + if width>1000 {eprintln!("bin {width}: fills {__a:.2} rows {:.2} index {:.2} geo {:.2}", __b-__a, __c-__b, __d-__c);} // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); let mut ramps: Vec<[f32; 4]> = Vec::new(); @@ -316,6 +328,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let u = f32::from_bits; for (op, f) in ops.iter().enumerate() { let rule = match f.rule { + _ if f.hairline => HAIRLINE, FillRule::NonZero => 0, FillRule::EvenOdd => 1, }; @@ -403,7 +416,7 @@ fn colour_effect(fx: &anicraft_doc::ColorEffect) -> (f32, f32, [f32; 3], u32) { /// 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], bd_at: &[u32], t: &Tables) -> RowOut { +fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u32], t: &Tables) -> RowOut { let first_tile = (r * tx) as u32; let slices = || { locals.iter().enumerate().map(move |(c, (l, rows))| { @@ -430,13 +443,12 @@ fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u3 let mut ae = vec![[0u32; 4]; nart]; let mut cursor: Vec<[u32; 2]> = count[..tx].to_vec(); for (c, es) in slices() { - let (p0, b0) = (piece_at.get(c).copied().unwrap_or(0), bd_at.get(c).copied().unwrap_or(0)); + let p0 = piece_at.get(c).copied().unwrap_or(0); for &[op, tile, s0, n, bd] in es { let Some(cur) = cursor.get_mut(tile.wrapping_sub(first_tile) as usize) else { continue }; let art = usize::from(op >= t.fills); let at = cur[art] as usize; cur[art] += 1; - let bd = if bd == NONE { NONE } else { b0 + bd }; let slot = if art == 1 { ae.get_mut(at) } else { fe.get_mut(at) }; if let Some(slot) = slot { *slot = [op, p0 + s0, n, bd]; @@ -514,30 +526,26 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< } } -/// Splits one fill's edges into tile pieces and walks each tile row for backdrops. +/// Splits one fill's edges into tile pieces (with the steps where its outline crosses a tile's +/// left edge) and walks each tile row for the backdrops. fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, pieces: &mut Vec) { - let b = f.bounds; - if b.is_empty() { - return; - } - let tx0 = b.x0.max(0) as u32 / TILE; - let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x); - let ty0 = b.y0.max(0) as u32 / TILE; - let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y); - if tx1 <= tx0 || ty1 <= ty0 { - return; - } - let ncols = (tx1 - tx0) as i32; - let range = Range { ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols }; + let Some(range) = Range::of(f, tiles_x, tiles_y) else { return }; pieces.clear(); - for poly in &f.polys { - let n = poly.len(); - if n < 2 { - continue; + if f.hairline { + for poly in &f.polys { + for_segments(poly, |a, b| hairline_tiles(a, b, &range, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] }))); } - for i in 0..n { - let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - split_edge(a, c, &range, pieces); + } else { + for poly in &f.polys { + let n = poly.len(); + if n < 2 { + continue; + } + for i in 0..n { + let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; + split_edge(a, c, &range, |p| pieces.push(p)); + crossings(a, c, &range, |p| pieces.push(p)); + } } } if pieces.is_empty() { @@ -549,53 +557,37 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec let mut i = 0usize; while let Some(first) = pieces.get(i) { let row = first.row; - let row_y0 = ((ty0 + row) * TILE) as f32; - let mut wind = [0.0f32; 16]; - // Parts left of the fill's tiles only shift the winding. + let row_y0 = range.row_y0(row); + // Pieces left of the fill's tiles only count where they start on the row's top edge. + let mut backdrop = 0i32; while let Some(p) = pieces.get(i).filter(|p| p.row == row && p.col < 0) { - add_rows(&mut wind, &p.seg, row_y0); + backdrop += top_crossing(&p.seg, row_y0); i += 1; } - let mut last_bd: Option<(u32, [f32; 16])> = None; - for col in 0..ncols { + for col in 0..range.ncols { let start = i; while pieces.get(i).is_some_and(|p| p.row == row && p.col == col) { i += 1; } let here = pieces.get(start..i).unwrap_or(&[]); - let empty_wind = wind.iter().all(|w| w.abs() < 1e-6); - if empty_wind { - wind = [0.0; 16]; - } - if here.is_empty() && empty_wind { + if here.is_empty() && backdrop == 0 { // Nothing here; and nothing further right either once the row's pieces are used. if !pieces.get(i).is_some_and(|p| p.row == row) { break; } continue; } - let tile_x = tx0 + col as u32; - let tile = (ty0 + row) * tiles_x + tile_x; - let bd = if empty_wind { - NONE - } else { - match last_bd { - Some((k, w)) if w == wind => k, - _ => { - let k = out.backdrops.len() as u32; - out.backdrops.extend_from_slice(wind.as_chunks::<4>().0); - last_bd = Some((k, wind)); - k - } - } - }; + let tile_x = range.tx0 + col as u32; + let tile = (range.ty0 + row) * tiles_x + tile_x; let (ox, oy) = ((tile_x * TILE) as f32, row_y0); let s0 = out.pieces.len() as u32; for p in here { out.pieces.push([p.seg[0] - ox, p.seg[1] - oy, p.seg[2] - ox, p.seg[3] - oy]); - add_rows(&mut wind, &p.seg, row_y0); } - out.entries.push([op, tile, s0, here.len() as u32, bd]); + out.entries.push([op, tile, s0, here.len() as u32, backdrop as u32]); + if !f.hairline { + backdrop += here.iter().map(|p| top_crossing(&p.seg, row_y0)).sum::(); + } } // Skip whatever is left of this row (pieces right of the range never get here). while pieces.get(i).is_some_and(|p| p.row == row) { @@ -604,33 +596,67 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec } } -/// The fill's tile range, in pixels and tiles. -struct Range { - ylo: f32, - yhi: f32, - xlo: f32, - xhi: f32, - ncols: i32, -} - -/// Adds the winding a piece gives everything to its right, per pixel row of its tile row. -fn add_rows(wind: &mut [f32; 16], seg: &[f32; 4], row_y0: f32) { - let (ya, yb, dir) = if seg[1] < seg[3] { (seg[1], seg[3], 1.0) } else { (seg[3], seg[1], -1.0) }; - let r0 = ((ya - row_y0).floor().max(0.0)) as usize; - let r1 = ((yb - row_y0).ceil().min(T)) as usize; - for r in r0..r1 { - let lo = row_y0 + r as f32; - let d = yb.min(lo + 1.0) - ya.max(lo); - if d > 0.0 - && let Some(w) = wind.get_mut(r) - { - *w += dir * d; +/// The edges of a closed polygon (fills) or the segments of an open polyline (hairlines; a +/// single point is a dot). +fn for_segments(poly: &[Vec2], mut f: impl FnMut(Vec2, Vec2)) { + match poly { + [] => {} + [p] => f(*p, *p), + _ => { + for w in poly.windows(2) { + f(w[0], w[1]); + } } } } +/// The direction (`1` down, `−1` up) of a piece that starts on its tile row's top edge at +/// `row_y0`, which means its edge crosses that edge; `0` for any other piece. +pub(crate) fn top_crossing(seg: &[f32; 4], row_y0: f32) -> i32 { + if seg[1] == seg[3] || seg[1].min(seg[3]) != row_y0 { + return 0; + } + if seg[3] > seg[1] { 1 } else { -1 } +} + +/// A fill's tile range, in pixels and tiles. +#[derive(Clone, Copy)] +pub(crate) struct Range { + pub(crate) tx0: u32, + pub(crate) ty0: u32, + pub(crate) ylo: f32, + pub(crate) yhi: f32, + pub(crate) xlo: f32, + pub(crate) xhi: f32, + pub(crate) ncols: i32, + pub(crate) nrows: i32, +} + +impl Range { + /// The tiles `f`'s bounds cover, within the surface's; `None` when there are none. + pub(crate) fn of(f: &Fill, tiles_x: u32, tiles_y: u32) -> Option { + let b = f.bounds; + if b.is_empty() { + return None; + } + let tx0 = b.x0.max(0) as u32 / TILE; + let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x); + let ty0 = b.y0.max(0) as u32 / TILE; + let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y); + if tx1 <= tx0 || ty1 <= ty0 { + return None; + } + let (ncols, nrows) = ((tx1 - tx0) as i32, (ty1 - ty0) as i32); + Some(Range { tx0, ty0, ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols, nrows }) + } + + fn row_y0(&self, row: u32) -> f32 { + ((self.ty0 + row) * TILE) as f32 + } +} + /// Splits edge `a → b` at tile rows and columns inside the fill's range. -fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec) { +fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { if !(a.is_finite() && b.is_finite()) || a.y == b.y { return; } @@ -653,18 +679,18 @@ fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec) { continue; } let (xs, xe) = (x_at(ys), x_at(ye)); - split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, out); + split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, &mut out); } } /// Splits a piece inside one tile row at the fill's left and right edges and at tile columns. -fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec) { +fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl FnMut(Piece)) { let mut push = |col: i32, u: Vec2, v: Vec2| { if v.y <= u.y { return; } let seg = if down { [u.x, u.y, v.x, v.y] } else { [v.x, v.y, u.x, u.y] }; - out.push(Piece { row, col, seg }); + out(Piece { row, col, seg }); }; // Points where the piece crosses a column boundary (or the range's edges), top to bottom. let dx = e.x - s.x; @@ -674,7 +700,9 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec hi { + continue; + } + let y = if a.y == b.y { a.y } else { a.y + (x - a.x) * slope }; + if !y.is_finite() || y <= r.ylo || y >= r.yhi { + continue; + } + let row = ((y - r.ylo) / T).floor(); + if row < 0.0 || row >= r.nrows as f32 { + continue; + } + let ry0 = r.ylo + row * T; + if y <= ry0 { + continue; // on the row's top edge: the backdrop has it + } + let bottom = ry0 + T; + let seg = if b.x > a.x { [x, bottom, x, y] } else { [x, y, x, bottom] }; + out(Piece { row: row as u32, col: k, seg }); + } +} + +/// Every tile of the range with a pixel centre within a hairline's reach of segment `a → b` +/// (conservatively: a little more), as `(row, col)` relative to the range. +fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32)) { + if !(a.is_finite() && b.is_finite()) { + return; + } + // Pixel centres within reach of the segment lie within these margins of it. + const M: f32 = anicraft_render::hairline::REACH + 1.0; + let (ymin, ymax) = (a.y.min(b.y), a.y.max(b.y)); + let r0 = (((ymin - M - r.ylo) / T).floor()).max(0.0); + let r1 = (((ymax + M - r.ylo) / T).floor()).min((r.nrows - 1) as f32); + if r1 < r0 { + return; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + for row in r0 as i32..=r1 as i32 { + let top = r.ylo + row as f32 * T; + // The segment's part within the row's band, then the columns within reach of it. + let (xa, xb) = if dy == 0.0 { + (a.x.min(b.x), a.x.max(b.x)) + } else { + let t0 = ((top - M - a.y) / dy).clamp(0.0, 1.0); + let t1 = ((top + T + M - a.y) / dy).clamp(0.0, 1.0); + let (u, v) = (a.x + dx * t0, a.x + dx * t1); + (u.min(v), u.max(v)) + }; + let c0 = (((xa - M - r.xlo) / T).floor()).max(0.0); + let c1 = (((xb + M - r.xlo) / T).floor()).min((r.ncols - 1) as f32); + if c1 < c0 { + continue; + } + for col in c0 as i32..=c1 as i32 { + out(row as u32, col); + } + } +} + /// Coverage of pixel `(px, py)` (tile-relative) from one piece: the same integral the oracle's /// accumulation buffer computes. Used by tests to check the binning on the CPU. #[cfg(test)] diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 60ead56f..9a81fc4c 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -1,11 +1,13 @@ // AniCraft GPU stage: fine rasterization (ADR 0019, ADR 0029). // // One workgroup per 16 × 16 tile, one invocation per pixel. Each pixel walks its tile's entries -// in drawing order. An entry's coverage is its backdrop (winding from edges left of the tile, -// per pixel row) plus the exact area each of the tile's edge pieces covers in the pixel: the -// same integral as the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the -// fill rule, the paint (solid, or the oracle's own 256-entry gradient table) and src-over on -// premultiplied colour, all in f32, as the oracle does. +// in drawing order. An entry's coverage is its backdrop (the winding number just below the +// tile's top-left corner, an integer; ADR 0048) plus the exact area each of the tile's edge +// pieces covers in the pixel, the steps on the tile's left edge included: the same integral as +// the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the fill rule, the +// paint (solid, or the oracle's own 256-entry gradient table) and src-over on premultiplied +// colour, all in f32, as the oracle does. A hairline (ADR 0048) is 1 − the distance from the +// pixel centre to its nearest segment (crates/render/src/hairline.rs). // // Masks and groups (ADR 0029) are control entries in the same list, mirroring the oracle's band // compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage, levels @@ -66,6 +68,7 @@ const LEVEL_END: u32 = 0x80000005u; const CLIPPED: u32 = 1u; const ART: u32 = 2u; const MAX_GROUP_DEPTH: u32 = 8u; +const HAIRLINE: u32 = 2u; // Mean of clamp(u, 0, 1) for u running linearly from u0 to u1. fn avg_clamp(u0: f32, u1: f32) -> f32 { @@ -102,6 +105,22 @@ fn piece_cover(s: vec4, px: f32, py: f32) -> f32 { return dir * (yb - ya) * avg_clamp(px + 1.0 - xa, px + 1.0 - xb); } +// Distance from `p` to the segment `s` (x0, y0, x1, y1): hairline.rs › seg_dist, step by step. +fn seg_dist(p: vec2, s: vec4) -> f32 { + let dx = s.z - s.x; + let dy = s.w - s.y; + let qx = p.x - s.x; + let qy = p.y - s.y; + let l = dx * dx + dy * dy; + var t = 0.0; + if l > 0.0 { + t = clamp((qx * dx + qy * dy) / l, 0.0, 1.0); + } + let ex = qx - dx * t; + let ey = qy - dy * t; + return sqrt(ex * ex + ey * ey); +} + fn fold(w: f32, rule: u32) -> f32 { if rule == 0u { return min(abs(w), 1.0); @@ -357,16 +376,23 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { } let first = index[e + 1u]; let pieces = index[e + 2u]; - let bd = index[e + 3u]; - var w = 0.0; - if bd != NONE { - w = geo[bd + (lid.y >> 2u)][lid.y & 3u]; - } - for (var k = 0u; k < pieces; k++) { - w += piece_cover(geo[first + k], px, py); - } let h = params.at.y + op * 4u; - var cov = fold(w, index[h + 1u]); + let rule = index[h + 1u]; + var cov = 0.0; + if rule == HAIRLINE { + var d = 2.0; + let pc = vec2(px + 0.5, py + 0.5); + for (var k = 0u; k < pieces; k++) { + d = min(d, seg_dist(pc, geo[first + k])); + } + cov = clamp(1.0 - d, 0.0, 1.0); + } else { + var w = f32(bitcast(index[e + 3u])); + for (var k = 0u; k < pieces; k++) { + w += piece_cover(geo[first + k], px, py); + } + cov = fold(w, rule); + } let flags = index[h + 3u]; if (flags & ART) != 0u { let k = clamp(cov, 0.0, 1.0); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 005fcf68..dfe406be 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -126,10 +126,40 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { 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 }; 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()); out } +/// Outline mode (ADR 0048): hairlines along closed and open paths, crossing tiles in every +/// direction, overlapping, faded, past the surface, over a fill, and a point. +fn outlined() -> DisplayList { + let outline = |path: Path, c: Rgba, t: Affine| { + let mut i = item(path, Paint::Solid(Rgba::BLACK)); + i.outline = Some(c); + i.transform = t; + i + }; + let blue = Rgba::hex(0x4f8dff).with_alpha(0.5); + let green = Rgba::hex(0x4cd07d).with_alpha(0.8); + let mut wave = Path::default(); + wave.move_to(Vec2::new(-20.0, 90.0)); + for k in 0..12 { + wave.line_to(Vec2::new(k as f32 * 15.3, 90.0 + if k % 2 == 0 { 9.7 } else { -7.1 })); + } + list(vec![ + item(Path::rect(20.0, 20.0, 50.0, 40.0), Paint::Solid(Rgba::new(0.9, 0.8, 0.2, 1.0))), + outline(Path::ellipse(50.0, 45.0, 37.3, 29.1), blue, Affine::IDENTITY), + outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::rotate(0.05)), + outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::translate(0.25, 0.5)), + outline(Path::rect(16.0, 32.0, 112.0, 0.0), Rgba::BLACK, Affine::IDENTITY), + outline(Path::rect(8.5, 4.25, 133.0, 100.0), Rgba::new(0.8, 0.1, 0.1, 1.0), Affine::IDENTITY), + outline(wave, Rgba::new(0.2, 0.2, 0.2, 0.9), Affine::IDENTITY), + outline(Path::ellipse(140.0, 100.0, 60.0, 50.0), blue, Affine::IDENTITY), + outline(Path::line(Vec2::new(60.5, 70.5), Vec2::new(60.5, 70.5)), Rgba::BLACK, Affine::IDENTITY), + ]) +} + /// Masks and groups (ADR 0029): each stresses one part of the oracle's band compositor. fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { let red = Rgba::new(0.9, 0.1, 0.1, 1.0); @@ -264,13 +294,8 @@ fn emulate(b: &Binned, v: &View) -> Vec { } k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"), } - let mut wnd = if bd == binning::NONE { 0.0 } else { b.geo[bd as usize + ly / 4][ly % 4] }; - for k in 0..n { - let s = b.geo[first + k]; - wnd += piece_cover(s, lx as f32, ly as f32); - } let hd = b.ops_at as usize + op * 4; - let mut cov = if b.index[hd + 1] == 0 { wnd.abs().min(1.0) } else { let t = wnd.abs() % 2.0; if t > 1.0 { 2.0 - t } else { t } }; + let mut cov = entry_cover(&b.geo[first..first + n], bd, b.index[hd + 1], lx, ly); let flags = b.index[hd + 3]; if flags & bn::ART != 0 { let k = cov.clamp(0.0, 1.0); @@ -308,6 +333,26 @@ fn emulate(b: &Binned, v: &View) -> Vec { out } +/// An entry's coverage of pixel `(lx, ly)` of its tile, as `fine.wgsl` computes it: the +/// backdrop and its pieces under fill rule `rule`, or a hairline's distance. +fn entry_cover(pieces: &[[f32; 4]], backdrop: u32, rule: u32, lx: usize, ly: usize) -> f32 { + if rule == bn::HAIRLINE { + let p = Vec2::new(lx as f32 + 0.5, ly as f32 + 0.5); + let d = pieces.iter().fold(2.0f32, |d, s| d.min(anicraft_render::hairline::seg_dist(p, Vec2::new(s[0], s[1]), Vec2::new(s[2], s[3])))); + return (1.0 - d).clamp(0.0, 1.0); + } + let mut wnd = backdrop as i32 as f32; + for s in pieces { + wnd += piece_cover(*s, lx as f32, ly as f32); + } + if rule == 0 { + wnd.abs().min(1.0) + } else { + let t = wnd.abs() % 2.0; + if t > 1.0 { 2.0 - t } else { t } + } +} + /// `fine.wgsl` › `close_group` and `blend`, on the CPU (the oracle's formulas, written again /// from the shader's numbering). fn close_group(s: Premul, below: Premul, alpha: f32, m: u32) -> Premul { @@ -549,6 +594,7 @@ fn degenerate_geometry_bins_without_trouble() { clip, group, layer: None, + hairline: false, }; // A fill naming a layer that isn't there draws nothing. let mut lost = fill(None, None); diff --git a/crates/render/src/hairline.rs b/crates/render/src/hairline.rs new file mode 100644 index 00000000..5acf09dc --- /dev/null +++ b/crates/render/src/hairline.rs @@ -0,0 +1,169 @@ +//! Hairlines (ADR 0048): the one-pixel lines of outline mode (an outlined layer, onion skin's +//! outlines), drawn straight from the flattened path instead of as stroke polygons. +//! +//! A pixel's coverage is `1 − d`, clamped to `0..=1`, where `d` is the distance from the +//! pixel's centre to the nearest point of the line. Across a horizontal or vertical line that +//! is exactly the area a one-pixel-wide line covers in each pixel (a line through a pixel +//! centre covers it fully; one on a pixel boundary covers the two pixels beside it half each); +//! in other directions it is the line seen through a one-pixel tent filter. Overlaps and joins +//! never darken (the nearest point counts, not a sum), ends and corners are round, and each +//! segment is one edge to bin and test, where a stroked hairline was four plus a disc at every +//! bend. The GPU stage computes the same distance (`fine.wgsl` › `seg_dist`). + +use crate::raster::IRect; +use anicraft_geom::Vec2; + +/// How far a hairline reaches from its line, in pixels: beyond this its coverage is 0. +pub const REACH: f32 = 1.0; + +/// Distance from `p` to the segment `a → b` (a point when they coincide). The GPU computes it +/// with the same steps (`fine.wgsl` › `seg_dist`). +#[inline] +pub fn seg_dist(p: Vec2, a: Vec2, b: Vec2) -> f32 { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let (qx, qy) = (p.x - a.x, p.y - a.y); + let l = dx * dx + dy * dy; + let t = if l > 0.0 { ((qx * dx + qy * dy) / l).clamp(0.0, 1.0) } else { 0.0 }; + let (ex, ey) = (qx - dx * t, qy - dy * t); + (ex * ex + ey * ey).sqrt() +} + +/// A hairline's coverage at distance `d` from it. +#[inline] +pub fn coverage(d: f32) -> f32 { + (REACH - d).clamp(0.0, 1.0) +} + +/// Pixel bounds of hairlines along `polys`, within `surface`. +pub fn bounds(polys: &[Vec], surface: IRect) -> Option { + let (mut x0, mut y0, mut x1, mut y1) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); + for p in polys.iter().flatten().filter(|p| p.is_finite()) { + x0 = x0.min(p.x); + y0 = y0.min(p.y); + x1 = x1.max(p.x); + y1 = y1.max(p.y); + } + if !(x1 >= x0 && y1 >= y0) { + return None; + } + let b = IRect { + x0: (x0 - REACH).floor().max(surface.x0 as f32) as i32, + y0: (y0 - REACH).floor().max(surface.y0 as f32) as i32, + x1: (x1 + REACH).ceil().min(surface.x1 as f32) as i32, + y1: (y1 + REACH).ceil().min(surface.y1 as f32) as i32, + }; + (!b.is_empty()).then_some(b) +} + +/// Adds segment `a → b` to `acc` (coverage over `b`, row by row, `bounds.width()` per row), +/// keeping the larger coverage in every pixel it reaches. +pub fn add_segment(acc: &mut [f32], bounds: IRect, a: Vec2, b: Vec2) { + if !(a.is_finite() && b.is_finite()) || bounds.is_empty() { + return; + } + let w = bounds.width(); + // Pixel rows whose centres lie within reach of the segment. + let ylo = ((a.y.min(b.y) - REACH - 0.5).floor()).max(bounds.y0 as f32); + let yhi = ((a.y.max(b.y) + REACH + 0.5).ceil()).min(bounds.y1 as f32); + if yhi <= ylo { + return; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + for py in ylo as i32..yhi as i32 { + let yc = py as f32 + 0.5; + // The part of the segment within reach of this row's centres, then the pixels within + // reach of that part. + let (xa, xb) = if dy.abs() < 1e-12 { + (a.x.min(b.x), a.x.max(b.x)) + } else { + let t0 = ((yc - REACH - a.y) / dy).clamp(0.0, 1.0); + let t1 = ((yc + REACH - a.y) / dy).clamp(0.0, 1.0); + let (u, v) = (a.x + dx * t0, a.x + dx * t1); + (u.min(v), u.max(v)) + }; + let x0 = (xa - REACH - 0.5).floor().max(bounds.x0 as f32); + let x1 = (xb + REACH + 0.5).ceil().min(bounds.x1 as f32); + if x1 <= x0 { + continue; + } + let row = (py - bounds.y0) as usize * w; + for px in x0 as i32..x1 as i32 { + let c = coverage(seg_dist(Vec2::new(px as f32 + 0.5, yc), a, b)); + if let Some(v) = acc.get_mut(row + (px - bounds.x0) as usize) + && c > *v + { + *v = c; + } + } + } +} + +/// Adds an open polyline (a closed one repeats its first point at the end). +pub fn add_polyline(acc: &mut [f32], bounds: IRect, pts: &[Vec2]) { + match pts { + [] => {} + [p] => add_segment(acc, bounds, *p, *p), + _ => { + for w in pts.windows(2) { + add_segment(acc, bounds, w[0], w[1]); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn draw(pts: &[Vec2], w: i32, h: i32) -> Vec { + let b = IRect { x0: 0, y0: 0, x1: w, y1: h }; + let mut acc = vec![0.0; (w * h) as usize]; + add_polyline(&mut acc, b, pts); + acc + } + + #[test] + fn axis_aligned_lines_cover_exactly_one_pixel_of_area_per_row_or_column() { + // Through pixel centres: the row is covered fully, nothing else. + let a = draw(&[Vec2::new(-5.0, 4.5), Vec2::new(30.0, 4.5)], 20, 10); + for (i, v) in a.iter().enumerate() { + let want = if i / 20 == 4 { 1.0 } else { 0.0 }; + assert!((v - want).abs() < 1e-6, "pixel {i}: {v}"); + } + // On a pixel boundary: the two rows beside it, half each. A quarter off: 3/4 and 1/4. + for (y, rows) in [(4.0f32, [(3usize, 0.5f32), (4, 0.5)]), (4.25, [(3, 0.25), (4, 0.75)])] { + let a = draw(&[Vec2::new(7.5, -5.0), Vec2::new(7.5, 30.0)], 10, 20); + assert!(a.chunks(10).all(|r| (r[7] - 1.0).abs() < 1e-6 && r[6] == 0.0), "vertical through centres"); + let a = draw(&[Vec2::new(-5.0, y), Vec2::new(30.0, y)], 20, 10); + for (r, want) in rows { + assert!(a[r * 20..r * 20 + 20].iter().all(|v| (v - want).abs() < 1e-6), "y {y}, row {r}"); + } + assert!((a.iter().sum::() - 20.0).abs() < 1e-4, "one pixel of area per column"); + } + } + + #[test] + fn joins_and_overlaps_never_darken_and_ends_are_round() { + // A corner and the same segment twice: still at most 1 anywhere, 1 on the line. + let a = draw(&[Vec2::new(2.5, 2.5), Vec2::new(12.5, 2.5), Vec2::new(12.5, 12.5), Vec2::new(2.5, 2.5)], 16, 16); + assert!(a.iter().all(|v| (0.0..=1.0).contains(v))); + assert_eq!(a[2 * 16 + 12], 1.0); + assert_eq!(a[8 * 16 + 12], 1.0); + // Round end: the pixel centre half a pixel past the end, diagonally, is √0.5 away. + let a = draw(&[Vec2::new(4.0, 4.0), Vec2::new(10.0, 4.0)], 16, 10); + assert!((a[4 * 16 + 10] - (1.0 - 0.5f32.sqrt())).abs() < 1e-6, "{}", a[4 * 16 + 10]); + assert_eq!(a[4 * 16 + 11], 0.0, "beyond reach past the end"); + // A single point is a dot. + let a = draw(&[Vec2::new(3.5, 3.5)], 8, 8); + assert_eq!(a[3 * 8 + 3], 1.0); + assert_eq!(a.iter().filter(|v| **v > 0.0).count(), 1); + } + + #[test] + fn far_and_broken_points_stay_bounded() { + let a = draw(&[Vec2::new(-1e9, -1e9), Vec2::new(1e9, 1e9), Vec2::new(f32::NAN, 0.0), Vec2::new(3.0, f32::INFINITY)], 32, 32); + assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); + assert!(a.iter().any(|v| *v > 0.9), "the long diagonal shows"); + assert!(bounds(&[vec![Vec2::new(f32::NAN, 1.0)]], IRect { x0: 0, y0: 0, x1: 8, y1: 8 }).is_none()); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b79f4e11..e5a75183 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8,6 +8,7 @@ pub mod paint; pub mod raster; pub mod stroke; pub mod filters; +pub mod hairline; pub mod html; pub mod lottie; pub mod svg; @@ -218,9 +219,16 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re open.push(OpenGroup { id: g, buf: vec![[0.0; 4]; rows.len()], dirty: NO_PIXELS }); } let mask = op.clip.map(|c| band_clips.get(&clips, c, band, w, &mut cov, &mut row)); - cov.reset(b); - for poly in &op.polys { - cov.add_polygon(poly); + if op.hairline { + cov.reset_direct(b); + for poly in &op.polys { + cov.add_hairline(poly); + } + } else { + cov.reset(b); + for poly in &op.polys { + cov.add_polygon(poly); + } } match open.last_mut() { Some(top) => { @@ -294,6 +302,9 @@ pub struct Fill { /// [`render`] draws it: the layer's pixel at `(x, y)` is at `(x - x0, y - y0)` of its /// `bounds`, transparent outside. pub layer: Option, + /// A hairline (outline mode, ADR 0048): `polys` are open polylines (a closed one repeats + /// its first point), drawn by [`hairline`]'s distance coverage; `rule` doesn't apply. + pub hairline: bool, } /// A filtered group (a symbol instance with filters) as [`render`] draws it: its items on @@ -383,7 +394,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat op.bounds = op.bounds.intersect(&clips.bounds(c)); !op.bounds.is_empty() }); - let fill = |op: Prepared| Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds, clip: op.clip, group: op.group, layer: op.layer }; + let fill = |op: Prepared| Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds, clip: op.clip, group: op.group, layer: op.layer, hairline: op.hairline }; let mut fills = Vec::with_capacity(ops.len()); for op in ops { stats.edges += op.polys.iter().map(Vec::len).sum::(); @@ -465,6 +476,7 @@ impl FilterSetup { masks: None, group: Some(self.group), layer: None, + hairline: false, } } } @@ -656,6 +668,8 @@ struct Prepared { group: Option, /// A filtered layer's pixels instead of `shader` ([`Fill::layer`]; only in [`prepare_scene`]). layer: Option, + /// A hairline ([`Fill::hairline`]). + hairline: bool, } /// The clips of a display list: their mask artwork and where each can be non-zero. @@ -779,12 +793,36 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { return out; } let (clip, masks, group) = (item.clip, item.masks, item.group); + // (Mask artwork is never outlined: it draws nothing of its own.) + if let Some(color) = item.outline.filter(|_| !is_mask) { + // Outline mode: a hairline in the layer colour, no fill (ADR 0048). + let shader = Shader::Solid(premultiply(color)); + if shader.is_solid().is_some_and(|c| c[3] <= 0.0) { + return out; + } + let polys: Vec> = lines + .into_iter() + .map(|l| { + let mut pts = l.points; + if l.closed + && let Some(&first) = pts.first() + { + pts.push(first); + } + pts + }) + .collect(); + if let Some(b) = hairline::bounds(&polys, surface) { + out.push(Prepared { polys, rule: FillRule::NonZero, shader, bounds: b, clip, masks, group, layer: None, hairline: true }); + } + return out; + } let mut push = |polys: Vec>, rule, shader: Shader| { if shader.is_solid().is_some_and(|c| c[3] <= 0.0) { return; } if let Some(b) = pixel_bounds(&polys, surface) { - out.push(Prepared { polys, rule, shader, bounds: b, clip, masks, group, layer: None }); + out.push(Prepared { polys, rule, shader, bounds: b, clip, masks, group, layer: None, hairline: false }); } }; @@ -792,11 +830,6 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { push(lines.iter().map(|l| l.points.clone()).collect(), item.fill_rule, Shader::Solid([1.0; 4])); return out; } - if let Some(color) = item.outline { - // Outline mode: hairline in the layer colour, no fill. - push(stroke::stroke_polygons(&lines, 0.5), FillRule::NonZero, Shader::Solid(premultiply(color))); - return out; - } // The stroke is outlined from the flattened lines first, so the fill can then take them // without a copy; it is still drawn after the fill. let stroke = item.stroke.as_ref().and_then(|st| { diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 5f24b46a..76b7d0f2 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -46,16 +46,19 @@ pub struct Coverage { pub bounds: IRect, stride: usize, acc: Vec, + /// The buffer holds coverage itself (hairlines, ADR 0048), not area to sum along rows. + direct: bool, } impl Coverage { pub fn new(bounds: IRect) -> Coverage { let stride = bounds.width() + 2; - Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()] } + Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()], direct: false } } /// Re-targets the buffer at `bounds`, reusing its allocation (one buffer per render band). pub fn reset(&mut self, bounds: IRect) { + self.direct = false; self.bounds = bounds; self.stride = bounds.width() + 2; self.acc.clear(); @@ -180,6 +183,24 @@ impl Coverage { } } + /// Re-targets the buffer at `bounds` for hairlines ([`Coverage::add_hairline`]): it then + /// holds each pixel's coverage, and [`Coverage::resolve_row`] reads it as it is. + pub fn reset_direct(&mut self, bounds: IRect) { + self.direct = true; + self.bounds = bounds; + self.stride = bounds.width(); + self.acc.clear(); + self.acc.resize(self.stride * bounds.height(), 0.0); + } + + /// Adds a hairline along an open polyline ([`crate::hairline`]); the buffer must be in + /// direct mode ([`Coverage::reset_direct`]). + pub fn add_hairline(&mut self, pts: &[Vec2]) { + if self.direct { + crate::hairline::add_polyline(&mut self.acc, self.bounds, pts); + } + } + /// Resolves row `y` (relative to the bounds) into coverage values in `out` (len = width). pub fn resolve_row(&self, y: usize, rule: FillRule, out: &mut [f32]) { let start = y * self.stride; @@ -187,6 +208,12 @@ impl Coverage { out.fill(0.0); return; }; + if self.direct { + for (o, a) in out.iter_mut().zip(row) { + *o = *a; + } + return; + } let mut sum = 0.0f32; for (o, a) in out.iter_mut().zip(row) { sum += a; From 660bdcb0d8ca81b9cf633a4bbd098e9a48e1f6fd Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:55:24 -0700 Subject: [PATCH 019/402] fix(gpu): take the tiles' left-edge steps from the split pieces themselves (M3) Crossings computed apart from the splitting could disagree with it by a rounding near a tile corner and count one crossing twice (the backdrop and a step): 543 pixels off by up to 133/255 on a stress frame. The steps now come from consecutive pieces of a tile row in different columns, so the backdrop and the steps always describe the same pieces. A test on stress frames at awkward scales catches it. Also drops leftover timing prints. --- crates/gpu/src/binning.rs | 163 +++++++++++++++++++++++++------------- crates/gpu/src/tests.rs | 17 ++++ 2 files changed, 126 insertions(+), 54 deletions(-) diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 7f0407c1..a8bb81d2 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -216,7 +216,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let op_group: Vec = scene.fills.iter().map(|f| f.group.filter(|&g| (g as usize) < scene.groups.len()).unwrap_or(NONE)).collect(); let tables = Tables { fills: nf as u32, op_clip, op_group, clip_chain, art_ops, scene }; - let __t=std::time::Instant::now(); let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); let (tx, ty) = (tiles_x as usize, tiles_y as usize); @@ -227,7 +226,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result .enumerate() .map(|(c, chunk)| { let mut out = Local::default(); - let mut scratch = Vec::new(); + let mut scratch = (Vec::new(), Track::default()); for (i, f) in chunk.iter().enumerate() { bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch); } @@ -245,7 +244,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result }) .collect(); - let __a=__t.elapsed().as_secs_f32()*1000.0; // Where each chunk's pieces go in `geo`. let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); let mut piece_at = Vec::with_capacity(locals.len()); @@ -257,7 +255,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result // Phase 2, parallel over tile rows: each tile's stream of entries. let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &tables)).collect(); - let __b=__t.elapsed().as_secs_f32()*1000.0; let mut row_at = vec![0usize; ty + 1]; for (r, out) in rows.iter().enumerate() { row_at[r + 1] = row_at[r] + out.stream.len(); @@ -286,7 +283,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result } }); } - let __c=__t.elapsed().as_secs_f32()*1000.0; // Pieces copied in parallel into their places. let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; { @@ -302,8 +298,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result // Tens of thousands of small buffers: free them on the pool, off the frame's path. anicraft_render::drop_in_background((locals, rows)); - let __d=__t.elapsed().as_secs_f32()*1000.0; - if width>1000 {eprintln!("bin {width}: fills {__a:.2} rows {:.2} index {:.2} geo {:.2}", __b-__a, __c-__b, __d-__c);} // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); let mut ramps: Vec<[f32; 4]> = Vec::new(); @@ -528,7 +522,7 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< /// Splits one fill's edges into tile pieces (with the steps where its outline crosses a tile's /// left edge) and walks each tile row for the backdrops. -fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, pieces: &mut Vec) { +fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, (pieces, track): &mut (Vec, Track)) { let Some(range) = Range::of(f, tiles_x, tiles_y) else { return }; pieces.clear(); if f.hairline { @@ -541,11 +535,18 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec if n < 2 { continue; } + track.start(range.nrows as usize); + let mut keep = |p: Piece| pieces.push(p); for i in 0..n { let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - split_edge(a, c, &range, |p| pieces.push(p)); - crossings(a, c, &range, |p| pieces.push(p)); + split_edge(a, c, &range, |row, col, seg| { + if col < range.ncols { + keep(Piece { row, col, seg }); + } + track.see(row, Seen { col, end_y: seg[3] }, &range, &mut keep); + }); } + track.finish(&range, &mut keep); } } if pieces.is_empty() { @@ -655,13 +656,15 @@ impl Range { } } -/// Splits edge `a → b` at tile rows and columns inside the fill's range. -fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { +/// Splits edge `a → b` at tile rows and columns inside the fill's range, row by row, each row's +/// pieces in the edge's direction of travel. Parts right of the fill's tiles come as column +/// `ncols` (they draw nothing, but the steps on the tiles' left edges need to see them). +pub(crate) fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) { if !(a.is_finite() && b.is_finite()) || a.y == b.y { return; } - // Work top to bottom; restore the direction when storing. - let (p, q, down) = if a.y < b.y { (a, b, true) } else { (b, a, false) }; + let down = a.y < b.y; + let (p, q) = if down { (a, b) } else { (b, a) }; let y0 = p.y.max(r.ylo); let y1 = q.y.min(r.yhi); if y1 <= y0 { @@ -678,21 +681,26 @@ fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { if ye <= ys { continue; } - let (xs, xe) = (x_at(ys), x_at(ye)); - split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, &mut out); + let (top, bottom) = (Vec2::new(x_at(ys), ys), Vec2::new(x_at(ye), ye)); + if down { + split_row(row, top, bottom, r, &mut out); + } else { + split_row(row, bottom, top, r, &mut out); + } } } -/// Splits a piece inside one tile row at the fill's left and right edges and at tile columns. -fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl FnMut(Piece)) { +/// Splits a piece inside one tile row, from `s` to `e` (the edge's direction), at the fill's +/// left and right edges and at tile columns: column −1 left of the fill's tiles, `ncols` right. +fn split_row(row: u32, s: Vec2, e: Vec2, r: &Range, out: &mut impl FnMut(u32, i32, [f32; 4])) { + let down = e.y > s.y; let mut push = |col: i32, u: Vec2, v: Vec2| { - if v.y <= u.y { + if (down && v.y <= u.y) || (!down && v.y >= u.y) { return; } - let seg = if down { [u.x, u.y, v.x, v.y] } else { [v.x, v.y, u.x, u.y] }; - out(Piece { row, col, seg }); + out(row, col, [u.x, u.y, v.x, v.y]); }; - // Points where the piece crosses a column boundary (or the range's edges), top to bottom. + // Points where the piece crosses a column boundary (or the range's edges), in order. let dx = e.x - s.x; let at_x = |x: f32| -> Vec2 { let t = ((x - s.x) / dx).clamp(0.0, 1.0); @@ -707,7 +715,8 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl F return; } if lo >= r.xhi { - return; // wholly right of the fill's tiles: it covers none of their pixels + push(r.ncols, s, e); + return; } // Most pieces (flattened curves are short) lie inside one tile column. let cl = col_of(lo); @@ -737,47 +746,93 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl F push(-1, prev, next); } else if mid < r.xhi { push(col_of(mid).clamp(0, r.ncols - 1), prev, next); + } else { + push(r.ncols, prev, next); } prev = next; } } -/// The steps edge `a → b` makes in the winding along the left edges of the range's tiles: where -/// it crosses column boundary `x` (`lo < x ≤ hi`, horizontal edges too) strictly inside a tile -/// row, a vertical piece on that tile's left edge from the crossing to the row's bottom, upwards -/// when the edge runs right (the winding to the left drops by one) and downwards when it runs -/// left. -fn crossings(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { - if !(a.is_finite() && b.is_finite()) || a.x == b.x { +/// A piece as the left-edge steps see it: its column and the height where it ends. +#[derive(Clone, Copy)] +pub(crate) struct Seen { + pub(crate) col: i32, + pub(crate) end_y: f32, +} + +/// Per tile row of a fill, the last piece of the polygon walked so far there and its first: +/// consecutive pieces of a row in different columns are where the outline crosses tiles' left +/// edges. +#[derive(Default)] +pub(crate) struct Track { + last: Vec>, + first: Vec>, + touched: Vec, +} + +impl Track { + /// Ready for a polygon of a fill with `nrows` tile rows. + fn start(&mut self, nrows: usize) { + for &r in &self.touched { + if let Some(l) = self.last.get_mut(r as usize) { + *l = None; + } + if let Some(f) = self.first.get_mut(r as usize) { + *f = None; + } + } + self.touched.clear(); + if self.last.len() < nrows { + self.last.resize(nrows, None); + self.first.resize(nrows, None); + } + } + + /// The next piece of the polygon in tile row `row`; the steps between it and the row's + /// previous piece go to `out`. + fn see(&mut self, row: u32, s: Seen, r: &Range, out: &mut impl FnMut(Piece)) { + let (Some(last), Some(first)) = (self.last.get_mut(row as usize), self.first.get_mut(row as usize)) else { return }; + match *last { + Some(p) => steps(p, s, row, r, out), + None => { + *first = Some(s); + self.touched.push(row); + } + } + *last = Some(s); + } + + /// The polygon is closed: each row's last piece is followed by its first. + fn finish(&mut self, r: &Range, out: &mut impl FnMut(Piece)) { + for &row in &self.touched { + if let (Some(Some(l)), Some(Some(f))) = (self.last.get(row as usize), self.first.get(row as usize)) { + steps(*l, *f, row, r, out); + } + } + } +} + +/// The steps in the winding along the tiles' left edges between consecutive pieces `a` and `b` +/// of one tile row (ADR 0048): where the outline passes from column `a.col` to `b.col`, at the +/// height where `a` ends, each tile boundary between them gets a vertical piece on its left +/// edge from there to the row's bottom: upwards when the outline runs right (the winding left +/// of the tile drops by one), downwards when it runs left. On the row's top edge the backdrop +/// has the step already, on its bottom edge it changes nothing. +pub(crate) fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { + if a.col == b.col { return; } - let (lo, hi) = (a.x.min(b.x), a.x.max(b.x)); - let kmin = (((lo - r.xlo) / T).floor() + 1.0).max(0.0); - let kmax = ((hi - r.xlo) / T).floor().min((r.ncols - 1) as f32); - if kmax < kmin { + let top = r.ylo + (row * TILE) as f32; + let (y, bottom) = (a.end_y, top + T); + if !(y > top && y < bottom) { return; } - let slope = (b.y - a.y) / (b.x - a.x); - for k in kmin as i32..=kmax as i32 { + let right = a.col < b.col; + let (lo, hi) = if right { (a.col, b.col) } else { (b.col, a.col) }; + for k in (lo + 1).max(0)..=hi.min(r.ncols - 1) { let x = r.xlo + k as f32 * T; - if x <= lo || x > hi { - continue; - } - let y = if a.y == b.y { a.y } else { a.y + (x - a.x) * slope }; - if !y.is_finite() || y <= r.ylo || y >= r.yhi { - continue; - } - let row = ((y - r.ylo) / T).floor(); - if row < 0.0 || row >= r.nrows as f32 { - continue; - } - let ry0 = r.ylo + row * T; - if y <= ry0 { - continue; // on the row's top edge: the backdrop has it - } - let bottom = ry0 + T; - let seg = if b.x > a.x { [x, bottom, x, y] } else { [x, y, x, bottom] }; - out(Piece { row: row as u32, col: k, seg }); + let seg = if right { [x, bottom, x, y] } else { [x, y, x, bottom] }; + out(Piece { row, col: k, seg }); } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index dfe406be..adce571b 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -488,6 +488,22 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() { } } +/// Thousands of overlapping shapes at awkward scales: edges meet tile corners and boundaries +/// within float rounding, where the backdrops and the left-edge steps must agree (ADR 0048). +#[test] +fn binned_coverage_matches_the_oracle_on_stress_frames() { + let doc = sample::stress(20, 100, 48); + for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] { + let dl = anicraft_doc::evaluate(&doc, f); + let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) }; + let (scene, _) = prepare_scene(&dl, &v).unwrap(); + let b = binning::bin(&scene, v.width, v.height).unwrap(); + let (oracle, _) = render(&dl, &v).unwrap(); + let (mean, max) = f32_diff(&emulate(&b, &v), &oracle.data); + assert!(mean < 1e-4 && max < 4e-3, "frame {f} at {s}: mean {mean:e}, max {max:e}"); + } +} + #[test] fn the_composited_sample_really_has_masks_and_groups() { let comp = composited_sample(); @@ -960,3 +976,4 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() { assert_parity(g, "filtered sample tile", &dl, &tile); } } + From 72da28d74ce69d8b18f83e2868f364cb4f179c9a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:55:38 -0700 Subject: [PATCH 020/402] fix(gpu): keep the binning's helpers private (M3) --- crates/gpu/src/binning.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index a8bb81d2..8338c0f1 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -659,7 +659,7 @@ impl Range { /// Splits edge `a → b` at tile rows and columns inside the fill's range, row by row, each row's /// pieces in the edge's direction of travel. Parts right of the fill's tiles come as column /// `ncols` (they draw nothing, but the steps on the tiles' left edges need to see them). -pub(crate) fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) { +fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) { if !(a.is_finite() && b.is_finite()) || a.y == b.y { return; } @@ -755,16 +755,16 @@ fn split_row(row: u32, s: Vec2, e: Vec2, r: &Range, out: &mut impl FnMut(u32, i3 /// A piece as the left-edge steps see it: its column and the height where it ends. #[derive(Clone, Copy)] -pub(crate) struct Seen { - pub(crate) col: i32, - pub(crate) end_y: f32, +struct Seen { + col: i32, + end_y: f32, } /// Per tile row of a fill, the last piece of the polygon walked so far there and its first: /// consecutive pieces of a row in different columns are where the outline crosses tiles' left /// edges. #[derive(Default)] -pub(crate) struct Track { +struct Track { last: Vec>, first: Vec>, touched: Vec, @@ -818,7 +818,7 @@ impl Track { /// edge from there to the row's bottom: upwards when the outline runs right (the winding left /// of the tile drops by one), downwards when it runs left. On the row's top edge the backdrop /// has the step already, on its bottom edge it changes nothing. -pub(crate) fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { +fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { if a.col == b.col { return; } From f18cf5bd688396557b0ac7588584aa2e88555493 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:06:54 -0700 Subject: [PATCH 021/402] feat(gpu): tile binning on the GPU: count, prefix sum, scatter, tile lists (M3) The CPU lays out the fills' points, each fill's tile range, each tile row's fills in drawing order and room for every tile the fills' bounds cover, with an upper bound of the pieces, so every buffer is sized up front and nothing is read back. bin.wgsl splits the edges (one invocation per row of tiles of each fill, so no atomics), scan.wgsl places the pieces, and a pass per tile keeps the fills with pieces or a backdrop there, in order: the same lists as the CPU binning, which stays the reference and the way for fills in masks and groups. Binning::Auto bins on the GPU from 4,096 edges; ANICRAFT_GPU_BINNING overrides. Tests: the GPU's lists against the CPU's, entry by entry and pixel by pixel (stress frames, outlines, the analytic scenes), and GPU-binned frames against the oracle, on Vulkan and Direct3D 12. --- crates/gpu/src/bin.wgsl | 426 ++++++++++++++++++++++++++++++++++ crates/gpu/src/binning.rs | 246 ++++++++++++-------- crates/gpu/src/gpu_binning.rs | 410 ++++++++++++++++++++++++++++++++ crates/gpu/src/lib.rs | 196 +++++++++++++--- crates/gpu/src/scan.wgsl | 83 +++++++ crates/gpu/src/tests.rs | 104 ++++++++- 6 files changed, 1336 insertions(+), 129 deletions(-) create mode 100644 crates/gpu/src/bin.wgsl create mode 100644 crates/gpu/src/gpu_binning.rs create mode 100644 crates/gpu/src/scan.wgsl diff --git a/crates/gpu/src/bin.wgsl b/crates/gpu/src/bin.wgsl new file mode 100644 index 00000000..e062c6b0 --- /dev/null +++ b/crates/gpu/src/bin.wgsl @@ -0,0 +1,426 @@ +// AniCraft GPU stage: tile binning on the GPU (ADR 0048). +// +// The same tile lists as the CPU binning (binning.rs, the reference), from the prepared fills' +// flattened polygons, in four kinds of dispatch: +// +// 1. `count`, one invocation per row of tiles of each fill (an "op-row"): its edges split at +// tile rows and columns (binning.rs › split_edge, split_row), plus the steps where the +// outline passes from one column to another (› Track, steps), or a hairline's segments by +// reach (› hairline_tiles), counted per tile of the fill (an "op-tile"); and the backdrops: the +// directions of the pieces starting on the row's top edge, summed along the row. Each +// op-row is one invocation's alone, so nothing needs atomics and integers add up the same +// in any order: the counts and backdrops are exact. +// 2. `scan_blocks` and `scan_add`: an exclusive prefix sum of the counts (the public +// work-efficient scan: per workgroup, then the workgroups' totals, then added back), which +// places every op-tile's pieces. +// 3. `scatter`: the same walk again, writing each piece where its op-tile's pieces go, in the +// walk's order (the same every frame). +// 4. `tiles`, one invocation per tile: its fills in drawing order (the fills overlapping its +// row, from the CPU, which only needs their bounds), keeping those with pieces or a +// backdrop there, as the entries the fine pass reads. +// +// The binding layout fits the smallest devices (four storage buffers per stage): one buffer of +// inputs, one of working values (counts, backdrops, offsets, cursors, scan totals), the pieces +// (`geo`) and the fine pass's index. + +struct Params { + // tiles across, tiles down, op-rows, tiles + size: vec4, + // op-tiles, piece capacity, where the entries start in `index`, 0 + more: vec4, + // where the ops, polygons, points and op-row owners start in `input` + at: vec4, + // where the rows' fills and the rows' starts are in `input` + at2: vec4, +} + +@group(0) @binding(0) var params: Params; +@group(0) @binding(1) var input: array; +@group(0) @binding(2) var work: array; +@group(0) @binding(3) var geo: array>; +@group(0) @binding(4) var index: array; + +const T: f32 = 16.0; +// gpu_binning.rs › HAIRLINE_BIT: the op is a hairline. +const HAIRLINE_BIT: u32 = 0x80000000u; +// Margins of a hairline's reach (binning.rs › hairline_tiles). +const M: f32 = 2.0; + +// What to do with a piece. +const COUNT: u32 = 0u; +const WRITE: u32 = 1u; + +struct Op { + first_poly: u32, + polys: u32, + tx0: u32, + ty0: u32, + ncols: u32, + nrows: u32, + tile_base: u32, + flags: u32, +} + +fn op_at(i: u32) -> Op { + let b = params.at.x + i * 8u; + return Op(input[b], input[b + 1u], input[b + 2u], input[b + 3u], input[b + 4u], input[b + 5u], input[b + 6u], input[b + 7u]); +} + +fn point(i: u32) -> vec2 { + let b = params.at.z + i * 2u; + return vec2(bitcast(input[b]), bitcast(input[b + 1u])); +} + +// Finite (not NaN or infinite), from the bits: comparisons with NaN may be optimized away. +fn finite(v: f32) -> bool { + return (bitcast(v) & 0x7f800000u) != 0x7f800000u; +} + +fn finite2(p: vec2) -> bool { + return finite(p.x) && finite(p.y); +} + +// The working values: counts, backdrops, offsets and cursors, `params.more.x` each. +fn counts_at(t: u32) -> u32 { + return t; +} +fn backdrop_at(t: u32) -> u32 { + return params.more.x + t; +} +fn offset_at(t: u32) -> u32 { + return 2u * params.more.x + t; +} +fn cursor_at(t: u32) -> u32 { + return 3u * params.more.x + t; +} + +// The walk of one op-row: what it is and where its pieces go. +struct Walk { + mode: u32, + // the op-tile of the row's first column + tile0: u32, + ncols: i32, + hairline: bool, + row_y0: f32, + // the row's top-left in pixels + ox: f32, +} + +// The fill's range (binning.rs › Range). +struct Rng { + xlo: f32, + xhi: f32, + ylo: f32, + yhi: f32, + ncols: i32, + nrows: i32, +} + +// binning.rs › top_crossing. +fn top_crossing(s: vec4, row_y0: f32) -> i32 { + if s.y == s.w || min(s.y, s.w) != row_y0 { + return 0; + } + return select(-1, 1, s.w > s.y); +} + +// One piece in column `col` of the walk's row (−1: left of the fill's tiles). +fn emit(w: Walk, col: i32, s: vec4) { + if w.mode == COUNT { + if col >= 0 && col < w.ncols { + let t = counts_at(w.tile0 + u32(col)); + work[t] = work[t] + 1u; + } + if !w.hairline { + let c = top_crossing(s, w.row_y0); + if c != 0 && col + 1 < w.ncols { + let t = backdrop_at(w.tile0 + u32(col + 1)); + work[t] = bitcast(bitcast(work[t]) + c); + } + } + return; + } + if col < 0 || col >= w.ncols { + return; + } + let tile = w.tile0 + u32(col); + let k = work[cursor_at(tile)]; + work[cursor_at(tile)] = k + 1u; + let at = work[offset_at(tile)] + k; + if at < params.more.y { + let ox = w.ox + f32(u32(col) * 16u); + geo[at] = vec4(s.x - ox, s.y - w.row_y0, s.z - ox, s.w - w.row_y0); + } +} + +// The polygon's last piece so far in this invocation's row, and its first (binning.rs › Track). +var tr_last: bool; +var tr_last_col: i32; +var tr_last_y: f32; +var tr_first: bool; +var tr_first_col: i32; + +// binning.rs › steps: where the outline passes from column `a` (its piece ending at height +// `y`) to column `b`, a vertical piece on each tile boundary between them, from there to the +// row's bottom. +fn steps(w: Walk, r: Rng, a: i32, y: f32, b: i32) { + if a == b { + return; + } + let top = w.row_y0; + let bottom = top + T; + if !(y > top && y < bottom) { + return; + } + let right = a < b; + let lo = min(a, b); + let hi = max(a, b); + for (var k = max(lo + 1, 0); k <= min(hi, r.ncols - 1); k++) { + let x = r.xlo + f32(k) * T; + if right { + emit(w, k, vec4(x, bottom, x, y)); + } else { + emit(w, k, vec4(x, y, x, bottom)); + } + } +} + +// A piece of the polygon in this row, in the direction of travel (column −1: left of the +// fill's tiles; `ncols`: right of them, drawing nothing): kept, and seen by the steps. +fn piece(w: Walk, r: Rng, col: i32, s: vec4) { + if col < r.ncols { + emit(w, col, s); + } + if tr_last { + steps(w, r, tr_last_col, tr_last_y, col); + } else { + tr_first = true; + tr_first_col = col; + } + tr_last = true; + tr_last_col = col; + tr_last_y = s.w; +} + +fn push(w: Walk, r: Rng, col: i32, u: vec2, v: vec2, down: bool) { + if (down && v.y <= u.y) || (!down && v.y >= u.y) { + return; + } + piece(w, r, col, vec4(u, v)); +} + +// binning.rs › split_row: a piece inside one tile row, from `s` to `e` (the edge's direction), +// split at the fill's left and right edges and at tile columns. +fn split_row(w: Walk, s: vec2, e: vec2, r: Rng) { + let down = e.y > s.y; + let dx = e.x - s.x; + let lo = min(s.x, e.x); + let hi = max(s.x, e.x); + if hi <= r.xlo && lo < r.xlo { + push(w, r, -1, s, e, down); + return; + } + if lo >= r.xhi { + push(w, r, r.ncols, s, e, down); + return; + } + let cl = i32(floor((lo - r.xlo) / T)); + if dx == 0.0 || (lo >= r.xlo && hi < r.xhi && cl == i32(floor((hi - r.xlo) / T))) { + push(w, r, clamp(cl, 0, r.ncols - 1), s, e, down); + return; + } + let kmin = max(i32(floor((lo - r.xlo) / T)) + 1, 0); + let kmax = min(i32(ceil((hi - r.xlo) / T)) - 1, r.ncols); + let count = max(kmax - kmin + 1, 0); + var prev = s; + for (var j = 0; j <= count; j++) { + var next = e; + if j != count { + let k = select(kmax - j, kmin + j, dx > 0.0); + let x = r.xlo + f32(k) * T; + if !(x > lo && x < hi) { + continue; + } + let t = clamp((x - s.x) / dx, 0.0, 1.0); + next = vec2(x, s.y + (e.y - s.y) * t); + } + let mid = 0.5 * (prev.x + next.x); + if mid < r.xlo { + push(w, r, -1, prev, next, down); + } else if mid < r.xhi { + push(w, r, clamp(i32(floor((mid - r.xlo) / T)), 0, r.ncols - 1), prev, next, down); + } else { + push(w, r, r.ncols, prev, next, down); + } + prev = next; + } +} + +// binning.rs › split_edge, for tile row `row` only. +fn split_edge(w: Walk, a: vec2, b: vec2, r: Rng, row: u32) { + if !(finite2(a) && finite2(b)) || a.y == b.y { + return; + } + let down = a.y < b.y; + let p = select(b, a, down); + let q = select(a, b, down); + let y0 = max(p.y, r.ylo); + let y1 = min(q.y, r.yhi); + if y1 <= y0 { + return; + } + let first = u32(max(floor((y0 - r.ylo) / T), 0.0)); + let last = u32(max(ceil((y1 - r.ylo) / T), 0.0)); + if row < first || row >= last { + return; + } + let dxdy = (q.x - p.x) / (q.y - p.y); + let ry0 = r.ylo + f32(row * 16u); + let ys = max(y0, ry0); + let ye = min(y1, ry0 + T); + if ye <= ys { + return; + } + let top = vec2(p.x + (ys - p.y) * dxdy, ys); + let bottom = vec2(p.x + (ye - p.y) * dxdy, ye); + if down { + split_row(w, top, bottom, r); + } else { + split_row(w, bottom, top, r); + } +} + +// binning.rs › hairline_tiles, for tile row `row` only: the segment, whole, into every column +// within reach. +fn hairline(w: Walk, a: vec2, b: vec2, r: Rng, row: u32) { + if !(finite2(a) && finite2(b)) { + return; + } + let r0 = max(floor((min(a.y, b.y) - M - r.ylo) / T), 0.0); + let r1 = min(floor((max(a.y, b.y) + M - r.ylo) / T), f32(r.nrows - 1)); + let rf = f32(row); + if !(r1 >= r0) || rf < r0 || rf > r1 { + return; + } + let top = r.ylo + rf * T; + let dx = b.x - a.x; + let dy = b.y - a.y; + var xa = min(a.x, b.x); + var xb = max(a.x, b.x); + if dy != 0.0 { + let t0 = clamp((top - M - a.y) / dy, 0.0, 1.0); + let t1 = clamp((top + T + M - a.y) / dy, 0.0, 1.0); + let u = a.x + dx * t0; + let v = a.x + dx * t1; + xa = min(u, v); + xb = max(u, v); + } + let c0 = max(floor((xa - M - r.xlo) / T), 0.0); + let c1 = min(floor((xb + M - r.xlo) / T), f32(r.ncols - 1)); + if !(c1 >= c0) { + return; + } + for (var col = i32(c0); col <= i32(c1); col++) { + emit(w, col, vec4(a, b)); + } +} + +// The invocation's index in a dispatch of 64-wide workgroups spread over x and y. +fn linear(wg: vec3, n: vec3, lid: vec3, width: u32) -> u32 { + return (wg.y * n.x + wg.x) * width + lid.x; +} + +fn walk(mode: u32, t: u32) { + if t >= params.size.z { + return; + } + let opi = input[params.at.w + t]; + let o = op_at(opi); + // This op-row's row within the fill: how far `t` is past the fill's first op-row, which + // `row_of` holds in the op's own slot of rows (op-rows are in op order). + let row = t - input[params.at.w + params.size.z + opi]; + let ylo = f32(o.ty0 * 16u); + let r = Rng(f32(o.tx0 * 16u), f32((o.tx0 + o.ncols) * 16u), ylo, f32((o.ty0 + o.nrows) * 16u), i32(o.ncols), i32(o.nrows)); + let hair = (o.flags & HAIRLINE_BIT) != 0u; + let w = Walk(mode, o.tile_base + row * o.ncols, i32(o.ncols), hair, f32((o.ty0 + row) * 16u), r.xlo); + for (var pi = 0u; pi < o.polys; pi++) { + let pb = params.at.y + (o.first_poly + pi) * 2u; + let start = input[pb]; + let n = input[pb + 1u]; + if hair { + if n == 1u { + let p = point(start); + hairline(w, p, p, r, row); + } + for (var i = 0u; i + 1u < n; i++) { + hairline(w, point(start + i), point(start + i + 1u), r, row); + } + } else if n >= 2u { + tr_last = false; + tr_first = false; + for (var i = 0u; i < n; i++) { + let a = point(start + i); + let b = point(start + select(i + 1u, 0u, i + 1u == n)); + split_edge(w, a, b, r, row); + } + if tr_last && tr_first { + steps(w, r, tr_last_col, tr_last_y, tr_first_col); + } + } + } + if mode == COUNT && !hair { + // The backdrop deltas, summed along the row. + var acc = 0; + for (var c = 0u; c < o.ncols; c++) { + let at = backdrop_at(w.tile0 + c); + acc += bitcast(work[at]); + work[at] = bitcast(acc); + } + } +} + +@compute @workgroup_size(64) +fn count(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + walk(COUNT, linear(wg, n, lid, 64u)); +} + +@compute @workgroup_size(64) +fn scatter(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + walk(WRITE, linear(wg, n, lid, 64u)); +} + +@compute @workgroup_size(64) +fn tiles(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + let t = linear(wg, n, lid, 64u); + if t >= params.size.w { + return; + } + let tx = t % params.size.x; + let ty = t / params.size.x; + let start = index[2u * t]; + let rs = params.at2.x + input[params.at2.y + ty]; + let re = params.at2.x + input[params.at2.y + ty + 1u]; + var k = 0u; + for (var i = rs; i < re; i++) { + let opi = input[i]; + let o = op_at(opi); + if tx < o.tx0 || tx >= o.tx0 + o.ncols { + continue; + } + let ot = o.tile_base + (ty - o.ty0) * o.ncols + (tx - o.tx0); + var c = work[counts_at(ot)]; + let bd = work[backdrop_at(ot)]; + if c == 0u && bd == 0u { + continue; + } + let off = min(work[offset_at(ot)], params.more.y); + c = min(c, params.more.y - off); + let e = params.more.z + (start + k) * 4u; + index[e] = opi; + index[e + 1u] = off; + index[e + 2u] = c; + index[e + 3u] = bd; + k++; + } + index[2u * t + 1u] = k; +} diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 8338c0f1..809f68c4 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -51,6 +51,9 @@ const T: f32 = TILE as f32; pub const NONE: u32 = u32::MAX; /// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd). pub const HAIRLINE: u32 = 2; +/// How far from a hairline segment its tiles reach: pixel centres within its reach lie within +/// this of it (`bin.wgsl` › `M`). +pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 1.0; /// `vec4`s of paint data per fill. pub const PAINT_VEC4S: usize = 4; /// Gradient table entries (the oracle's LUT size). @@ -113,7 +116,8 @@ pub fn blend_code(m: BlendMode) -> u32 { /// /// * `index` (u32): `[start, count]` per tile into the entry list; then each entry as /// `[op, first piece, pieces, backdrop]` (the backdrop an `i32`), or a control entry ([`CTRL`] -/// set); then each op's header `[kind, fill rule (or HAIRLINE), ramp start in paints, flags]`. +/// set); then, at `ops_at`, each op's header `[kind, fill rule (or HAIRLINE), ramp start in +/// paints, flags]` ([`Binned::op_heads`]). /// * `geo` (`vec4`): pieces `(x0, y0, x1, y1)` relative to their tile's top-left, in the /// edge's direction (left-edge steps included); a hairline's are its segments, whole. /// * `paints` (`vec4`): per op its colour, then the inverse paint transform and gradient, @@ -127,6 +131,8 @@ pub struct Binned { pub index: Vec, pub entries_at: u32, pub ops_at: u32, + /// The op headers, which go at `ops_at` in the index. + pub op_heads: Vec, pub geo: Vec<[f32; 4]>, pub paints: Vec<[f32; 4]>, /// The paint buffer's whole length in `vec4`s: `paints`, then room for the layers. @@ -142,6 +148,10 @@ pub struct Binned { /// Pieces plus entries the fine pass walks, summed over tiles (each for 256 pixels): what /// bounds how long the dispatch runs. pub work: u64, + /// Binned on the GPU: `index` holds only the tile headers (`[start, 0]`, room for every + /// tile the fills' bounds cover), `geo` is empty, and the GPU computes the entries and + /// pieces from this plan (`entries` and `pieces` are then upper bounds). + pub gpu: Option, } /// A chunk of fills' share of the scene (binned in parallel; chunking keeps allocations few). @@ -189,6 +199,12 @@ struct RowOut { /// shader holds ([`MAX_GROUP_DEPTH`], [`MAX_CLIP_DEPTH`]) or it has more bitmaps than /// [`MAX_IMAGES`]; the caller draws it on the CPU. pub fn bin(scene: &Scene, width: u32, height: u32) -> Result { + bin_with(scene, width, height, None) +} + +/// [`bin`], or with `gpu`, a plan for binning on the GPU instead ([`Binned::gpu`]) when the +/// scene can take it and fits `gpu`'s limits ([`crate::gpu_binning`]). +pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_binning::Limits>) -> Result { if scene.groups.iter().any(|g| g.chain.len() > MAX_GROUP_DEPTH) { return Err(NeedsFull::Groups); } @@ -218,85 +234,16 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); - let (tx, ty) = (tiles_x as usize, tiles_y as usize); - // Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's - // entries then sorted (stably, so drawing order holds) by tile row, with row offsets. - let locals: Vec<(Local, Vec)> = ops - .par_chunks(CHUNK) - .enumerate() - .map(|(c, chunk)| { - let mut out = Local::default(); - let mut scratch = (Vec::new(), Track::default()); - for (i, f) in chunk.iter().enumerate() { - bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch); - } - out.entries.sort_by_key(|e| e[1] / tiles_x.max(1)); - let mut rows = vec![0u32; ty + 1]; - for e in &out.entries { - if let Some(r) = rows.get_mut((e[1] / tiles_x.max(1)) as usize + 1) { - *r += 1; - } - } - for r in 1..rows.len() { - rows[r] += rows[r - 1]; - } - (out, rows) - }) - .collect(); - - // Where each chunk's pieces go in `geo`. - let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); - let mut piece_at = Vec::with_capacity(locals.len()); - let mut p = 0usize; - for (l, _) in &locals { - piece_at.push(p as u32); - p += l.pieces.len(); - } - - // Phase 2, parallel over tile rows: each tile's stream of entries. - let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &tables)).collect(); - let mut row_at = vec![0usize; ty + 1]; - for (r, out) in rows.iter().enumerate() { - row_at[r + 1] = row_at[r] + out.stream.len(); - } - let total = row_at[ty]; - let work = rows.iter().map(|r| r.work).sum(); - let entries_at = 2 * tx * ty; - let ops_at = entries_at + 4 * total; - let mut index = vec![0u32; ops_at + 4 * ops.len()]; - // Phase 3, parallel over tile rows: headers and streams copied into place. - { - let (headers, rest) = index.split_at_mut(entries_at); - let (mut entries, _) = rest.split_at_mut(4 * total); - let mut row_entries: Vec<&mut [u32]> = Vec::with_capacity(ty); - for r in 0..ty { - let (mine, after) = std::mem::take(&mut entries).split_at_mut(4 * (row_at[r + 1] - row_at[r])); - row_entries.push(mine); - entries = after; + // On the GPU when asked and the scene can take it (no fill in a mask or a group, for now): + // then the fills alone are the ops (no mask artwork draws). + let plan = gpu.filter(|_| scene.fills.iter().all(|f| f.clip.is_none() && f.group.is_none())).and_then(|lim| crate::gpu_binning::plan(&scene.fills, tiles_x, tiles_y, lim)); + let lists = match &plan { + Some(p) => { + ops.truncate(nf); + Lists::on_gpu(p, tiles_x, tiles_y) } - headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).zip(&rows).enumerate().for_each(|(r, ((head, out), row))| { - for (h, &[s, n]) in head.as_chunks_mut::<2>().0.iter_mut().zip(&row.heads) { - *h = [row_at[r] as u32 + s, n]; - } - for (d, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(&row.stream) { - *d = *s; - } - }); - } - // Pieces copied in parallel into their places. - let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; - { - let mut piece_dst = &mut geo[..]; - let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len()); - for (l, _) in &locals { - let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len()); - jobs.push((a, &l.pieces)); - piece_dst = rest; - } - jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s)); - } - // Tens of thousands of small buffers: free them on the pool, off the frame's path. - anicraft_render::drop_in_background((locals, rows)); + None => cpu_lists(&ops, &tables, tiles_x, tiles_y), + }; // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); @@ -319,6 +266,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result return Err(NeedsFull::Filters); } let paints_len = cursor; + let mut op_heads: Vec = Vec::with_capacity(4 * ops.len()); let u = f32::from_bits; for (op, f) in ops.iter().enumerate() { let rule = match f.rule { @@ -372,10 +320,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result } else { 0 }; - let at = ops_at + 4 * op; - if let Some(slot) = index.get_mut(at..at + 4) { - slot.copy_from_slice(&[kind, rule, ramp, flags]); - } + op_heads.extend_from_slice(&[kind, rule, ramp, flags]); } paints.extend_from_slice(&ramps); if paints.len() != PAINT_VEC4S * ops.len() + table_len { @@ -383,7 +328,115 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result return Err(NeedsFull::Filters); } - Ok(Binned { tiles_x, tiles_y, index, entries_at: entries_at as u32, ops_at: ops_at as u32, geo, paints, paints_len, layer_at, images, entries: total, pieces, work }) + let Lists { index, geo, entries_at, ops_at, entries, pieces, work } = lists; + Ok(Binned { tiles_x, tiles_y, index, entries_at, ops_at, op_heads, geo, paints, paints_len, layer_at, images, entries, pieces, work, gpu: plan }) +} + +/// The tile lists (or, binned on the GPU, room for them). +struct Lists { + index: Vec, + geo: Vec<[f32; 4]>, + entries_at: u32, + ops_at: u32, + entries: usize, + pieces: usize, + work: u64, +} + +impl Lists { + /// Headers `[start, 0]` with room for every tile its fills' bounds cover; the GPU fills in + /// the entries and the counts. Entries and pieces are upper bounds. + fn on_gpu(p: &crate::gpu_binning::Plan, tiles_x: u32, tiles_y: u32) -> Lists { + let entries_at = 2 * tiles_x * tiles_y; + let ops_at = entries_at + 4 * p.op_tiles; + let work = u64::from(p.op_tiles) + u64::from(p.piece_cap); + Lists { index: p.headers.clone(), geo: Vec::new(), entries_at, ops_at, entries: p.op_tiles as usize, pieces: p.piece_cap as usize, work } + } +} + +/// The tile lists, binned on the CPU (in parallel per chunk of fills, then per tile row). +fn cpu_lists(ops: &[&Fill], tables: &Tables, tiles_x: u32, tiles_y: u32) -> Lists { + let (tx, ty) = (tiles_x as usize, tiles_y as usize); + // Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's + // entries then sorted (stably, so drawing order holds) by tile row, with row offsets. + let locals: Vec<(Local, Vec)> = ops + .par_chunks(CHUNK) + .enumerate() + .map(|(c, chunk)| { + let mut out = Local::default(); + let mut scratch = (Vec::new(), Track::default()); + for (i, f) in chunk.iter().enumerate() { + bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch); + } + out.entries.sort_by_key(|e| e[1] / tiles_x.max(1)); + let mut rows = vec![0u32; ty + 1]; + for e in &out.entries { + if let Some(r) = rows.get_mut((e[1] / tiles_x.max(1)) as usize + 1) { + *r += 1; + } + } + for r in 1..rows.len() { + rows[r] += rows[r - 1]; + } + (out, rows) + }) + .collect(); + + // Where each chunk's pieces go in `geo`. + let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); + let mut piece_at = Vec::with_capacity(locals.len()); + let mut p = 0usize; + for (l, _) in &locals { + piece_at.push(p as u32); + p += l.pieces.len(); + } + + // Phase 2, parallel over tile rows: each tile's stream of entries. + let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, tables)).collect(); + let mut row_at = vec![0usize; ty + 1]; + for (r, out) in rows.iter().enumerate() { + row_at[r + 1] = row_at[r] + out.stream.len(); + } + let total = row_at[ty]; + let work = rows.iter().map(|r| r.work).sum(); + let entries_at = 2 * tx * ty; + let ops_at = entries_at + 4 * total; + let mut index = vec![0u32; ops_at]; + // Phase 3, parallel over tile rows: headers and streams copied into place. + { + let (headers, rest) = index.split_at_mut(entries_at); + let (mut entries, _) = rest.split_at_mut(4 * total); + let mut row_entries: Vec<&mut [u32]> = Vec::with_capacity(ty); + for r in 0..ty { + let (mine, after) = std::mem::take(&mut entries).split_at_mut(4 * (row_at[r + 1] - row_at[r])); + row_entries.push(mine); + entries = after; + } + headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).zip(&rows).enumerate().for_each(|(r, ((head, out), row))| { + for (h, &[s, n]) in head.as_chunks_mut::<2>().0.iter_mut().zip(&row.heads) { + *h = [row_at[r] as u32 + s, n]; + } + for (d, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(&row.stream) { + *d = *s; + } + }); + } + // Pieces copied in parallel into their places. + let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; + { + let mut piece_dst = &mut geo[..]; + let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len()); + for (l, _) in &locals { + let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len()); + jobs.push((a, &l.pieces)); + piece_dst = rest; + } + jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s)); + } + // Tens of thousands of small buffers: free them on the pool, off the frame's path. + anicraft_render::drop_in_background((locals, rows)); + + 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 @@ -527,7 +580,7 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, (pie pieces.clear(); if f.hairline { for poly in &f.polys { - for_segments(poly, |a, b| hairline_tiles(a, b, &range, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] }))); + for_segments(poly, |a, b| hairline_tiles(a, b, &range, HAIRLINE_MARGIN, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] }))); } } else { for poly in &f.polys { @@ -622,6 +675,7 @@ pub(crate) fn top_crossing(seg: &[f32; 4], row_y0: f32) -> i32 { /// A fill's tile range, in pixels and tiles. #[derive(Clone, Copy)] +#[derive(Debug)] pub(crate) struct Range { pub(crate) tx0: u32, pub(crate) ty0: u32, @@ -836,17 +890,17 @@ fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { } } -/// Every tile of the range with a pixel centre within a hairline's reach of segment `a → b` -/// (conservatively: a little more), as `(row, col)` relative to the range. -fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32)) { +/// Every tile of the range within `margin` of segment `a → b` (rows and columns padded by it), +/// as `(row, col)` relative to the range. With [`HAIRLINE_MARGIN`], every tile with a pixel +/// centre within a hairline's reach (`bin.wgsl` › `hairline` uses the same). +pub(crate) fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, margin: f32, mut out: impl FnMut(u32, i32)) { if !(a.is_finite() && b.is_finite()) { return; } - // Pixel centres within reach of the segment lie within these margins of it. - const M: f32 = anicraft_render::hairline::REACH + 1.0; + let m = margin; let (ymin, ymax) = (a.y.min(b.y), a.y.max(b.y)); - let r0 = (((ymin - M - r.ylo) / T).floor()).max(0.0); - let r1 = (((ymax + M - r.ylo) / T).floor()).min((r.nrows - 1) as f32); + let r0 = (((ymin - m - r.ylo) / T).floor()).max(0.0); + let r1 = (((ymax + m - r.ylo) / T).floor()).min((r.nrows - 1) as f32); if r1 < r0 { return; } @@ -857,13 +911,13 @@ fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32)) { let (xa, xb) = if dy == 0.0 { (a.x.min(b.x), a.x.max(b.x)) } else { - let t0 = ((top - M - a.y) / dy).clamp(0.0, 1.0); - let t1 = ((top + T + M - a.y) / dy).clamp(0.0, 1.0); + let t0 = ((top - m - a.y) / dy).clamp(0.0, 1.0); + let t1 = ((top + T + m - a.y) / dy).clamp(0.0, 1.0); let (u, v) = (a.x + dx * t0, a.x + dx * t1); (u.min(v), u.max(v)) }; - let c0 = (((xa - M - r.xlo) / T).floor()).max(0.0); - let c1 = (((xb + M - r.xlo) / T).floor()).min((r.ncols - 1) as f32); + let c0 = (((xa - m - r.xlo) / T).floor()).max(0.0); + let c1 = (((xb + m - r.xlo) / T).floor()).min((r.ncols - 1) as f32); if c1 < c0 { continue; } diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs new file mode 100644 index 00000000..7e9390ee --- /dev/null +++ b/crates/gpu/src/gpu_binning.rs @@ -0,0 +1,410 @@ +//! Tile binning on the GPU (ADR 0048): the host half. +//! +//! [`crate::binning`] is the reference: it splits every fill's edges into tile pieces on the +//! CPU. Here the CPU only lays out what the GPU needs, in time proportional to the fills and +//! their points, and `bin.wgsl` does the splitting, the backdrops and the tile lists: +//! +//! * the fills' points and polygons, one flat buffer, with each fill's tile range; +//! * one GPU invocation per row of tiles of each fill (an *op-row*), and room for each tile +//! of each fill's bounds (an *op-tile*): its piece count, backdrop, place and cursor; +//! * per tile row, the fills overlapping it in drawing order, and per tile where its entries +//! go: room for every fill whose bounds cover it (the GPU keeps those with pieces or a +//! backdrop there, in order); +//! * an upper bound of the pieces, from each edge's rows and columns, so every buffer is sized +//! before the GPU runs and nothing is read back. +//! +//! The passes count, scan (prefix sum), scatter and list; their output is the same tile lists +//! as the CPU's, bit for bit in everything but rounding (a test compares them per pixel). + +use crate::binning::{HAIRLINE_MARGIN, Range, TILE, hairline_tiles}; +use anicraft_render::Fill; +use rayon::prelude::*; + +/// An op that is a hairline (`bin.wgsl` › `HAIRLINE_BIT`). +const HAIRLINE_BIT: u32 = 1 << 31; +/// `u32`s per op in the input (`bin.wgsl` › `Op`). +const OP_WORDS: usize = 8; +/// Values one scan workgroup handles (`scan.wgsl`). +const SCAN_BLOCK: u32 = 1024; + +/// When and how far the GPU bins. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// The largest buffer the device binds (bytes). + pub binding: u64, + /// Fewer edges than this bin on the CPU, where it takes less than setting up the passes. + pub min_edges: u64, +} + +/// Most edge visits the GPU's per-row passes may make (each row of a fill walks all its +/// edges): far above real scenes (the 50k-shape 4K stress frame makes about 6 M), it keeps a +/// fill with very many edges over very many rows on the CPU, which splits each edge once. +pub const MAX_VISITS: u64 = 1 << 26; + +/// What the GPU needs to bin a scene, laid out by the CPU. +pub struct Plan { + /// The ops, polygons, points, op-row owners (and each op's first op-row), the rows' fills + /// and the rows' starts, at [`Plan::at`]. + pub(crate) input: Vec, + pub(crate) at: [u32; 6], + pub(crate) op_rows: u32, + /// Tiles of the fills' bounds: the entries' room and the working values' length. + pub op_tiles: u32, + /// Room for pieces: an upper bound. + pub piece_cap: u32, + /// `[start, 0]` per tile. + pub(crate) headers: Vec, + /// Edges, and edge visits by the per-row passes. + pub edges: u64, + pub visits: u64, +} + +/// What one fill needs: its range and how much room. +struct Info { + range: Option, + polys: u32, + points: u32, + edges: u64, + pieces: u64, +} + +fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info { + let Some(r) = Range::of(f, tiles_x, tiles_y) else { return Info { range: None, polys: 0, points: 0, edges: 0, pieces: 0 } }; + let mut pieces = 0u64; + let mut edges = 0u64; + for poly in &f.polys { + if f.hairline { + let mut seg = |a, b| { + // With a pixel more reach than the binning's, whatever the GPU's rounding. + let mut n = 0u64; + hairline_tiles(a, b, &r, HAIRLINE_MARGIN + 1.0, |_, _| n += 1); + pieces += n; + edges += 1; + }; + match poly.as_slice() { + [] => {} + [p] => seg(*p, *p), + _ => poly.windows(2).for_each(|w| seg(w[0], w[1])), + } + } else { + let n = poly.len(); + if n < 2 { + continue; + } + for i in 0..n { + if let (Some(&a), Some(&b)) = (poly.get(i), poly.get((i + 1) % n)) { + pieces += edge_pieces(a, b, &r); + } + } + edges += n as u64; + } + } + let points = f.polys.iter().map(Vec::len).sum::() as u32; + Info { range: Some(r), polys: f.polys.len() as u32, points, edges, pieces } +} + +/// At most how many pieces edge `a → b` gives (`binning.rs` › `split_edge` and `steps`): one +/// per tile row it spans, one more per column boundary it crosses, a left-edge step per column +/// boundary it passes, and one for where it meets the next edge; with slack for rounding. +fn edge_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 { + if !(a.is_finite() && b.is_finite()) { + return 0; + } + let t = TILE as f32; + let (y0, y1) = (a.y.min(b.y).max(r.ylo), a.y.max(b.y).min(r.yhi)); + if y1 < y0 { + return 0; + } + let rows = ((y1 - r.ylo) / t).floor() - ((y0 - r.ylo) / t).floor() + 1.0; + let (x0, x1) = (a.x.min(b.x).max(r.xlo), a.x.max(b.x).min(r.xhi)); + let cols = if x1 >= x0 { ((x1 - r.xlo) / t).floor() - ((x0 - r.xlo) / t).floor() + 1.0 } else { 1.0 }; + (rows.clamp(0.0, r.nrows as f32 + 1.0) + 2.0 * cols.clamp(0.0, r.ncols as f32 + 1.0)) as u64 + 3 +} + +/// The plan for binning `fills` (the scene's, in drawing order) on a `tiles_x × tiles_y` +/// surface; `None` when the CPU should: too few edges to be worth it, too many visits, or a +/// buffer larger than the device binds. +pub fn plan(fills: &[Fill], tiles_x: u32, tiles_y: u32, lim: &Limits) -> Option { + let infos: Vec = fills.par_iter().map(|f| info(f, tiles_x, tiles_y)).collect(); + let n = fills.len(); + let (mut polys, mut points, mut op_tiles, mut op_rows, mut pieces, mut edges, mut visits) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64); + for i in &infos { + polys += u64::from(i.polys); + points += u64::from(i.points); + pieces += i.pieces; + edges += i.edges; + if let Some(r) = &i.range { + op_tiles += (r.ncols as u64) * (r.nrows as u64); + op_rows += r.nrows as u64; + visits += (r.nrows as u64) * i.edges; + } + } + let tiles = u64::from(tiles_x) * u64::from(tiles_y); + let words = OP_WORDS as u64 * n as u64 + 2 * polys + 2 * points + op_rows + n as u64 + op_rows + u64::from(tiles_y) + 1; + let work_words = 4 * op_tiles + 2 * op_tiles.div_ceil(u64::from(SCAN_BLOCK)) + 64; + let fits = |bytes: u64| bytes <= lim.binding; + if edges < lim.min_edges || visits > MAX_VISITS || pieces >= u64::from(u32::MAX) || op_tiles >= u64::from(u32::MAX) / 4 { + return None; + } + if !(fits(4 * words) && fits(4 * work_words) && fits(16 * pieces) && fits(4 * (2 * tiles + 4 * op_tiles + 4 * n as u64))) { + return None; + } + + // Where everything goes. + let at_ops = 0usize; + let at_polys = at_ops + OP_WORDS * n; + let at_points = at_polys + 2 * polys as usize; + let at_row_of = at_points + 2 * points as usize; + let at_row_ops = at_row_of + op_rows as usize + n; + let at_row_start = at_row_ops + op_rows as usize; + let mut input = vec![0u32; at_row_start + tiles_y as usize + 1]; + + // Per op: its first polygon, point, op-tile and op-row. + let mut firsts = Vec::with_capacity(n); + let (mut p0, mut q0, mut t0, mut r0) = (0u32, 0u32, 0u32, 0u32); + for i in &infos { + firsts.push((p0, q0, t0, r0)); + p0 += i.polys; + q0 += i.points; + if let Some(r) = &i.range { + t0 += (r.ncols * r.nrows) as u32; + r0 += r.nrows as u32; + } + } + { + let (head, rest) = input.split_at_mut(at_polys); + let (poly_words, rest) = rest.split_at_mut(at_points - at_polys); + let (point_words, rest) = rest.split_at_mut(at_row_of - at_points); + let (row_of, rest) = rest.split_at_mut(op_rows as usize); + let (row_base, rest) = rest.split_at_mut(n); + let (row_ops, row_start) = rest.split_at_mut(op_rows as usize); + // Each op's slices of the polygon and point tables, then filled in parallel. + let mut jobs: Vec = Vec::with_capacity(n); + let (mut pw, mut qw) = (poly_words, point_words); + for ((h, f), (i, first)) in head.chunks_mut(OP_WORDS).zip(fills).zip(infos.iter().zip(&firsts)) { + let (a, b) = std::mem::take(&mut pw).split_at_mut(2 * i.polys as usize); + let (c, d) = std::mem::take(&mut qw).split_at_mut(2 * i.points as usize); + pw = b; + qw = d; + jobs.push((h, a, c, f, i, *first)); + } + jobs.into_par_iter().for_each(|(h, pw, qw, f, i, (p0, q0, t0, _))| { + let (tx0, ty0, ncols, nrows) = i.range.map_or((0, 0, 0, 0), |r| (r.tx0, r.ty0, r.ncols as u32, r.nrows as u32)); + let flags = if f.hairline { HAIRLINE_BIT } else { 0 }; + h.copy_from_slice(&[p0, i.polys, tx0, ty0, ncols, nrows, t0, flags]); + let mut q = q0; + for (slot, poly) in pw.chunks_exact_mut(2).zip(&f.polys) { + slot.copy_from_slice(&[q, poly.len() as u32]); + q += poly.len() as u32; + } + for (slot, p) in qw.chunks_exact_mut(2).zip(f.polys.iter().flatten()) { + slot.copy_from_slice(&[p.x.to_bits(), p.y.to_bits()]); + } + }); + // Op-rows in op order: who owns each, and each op's first. + let mut k = 0usize; + for (op, (i, first)) in infos.iter().zip(&firsts).enumerate() { + if let Some(b) = row_base.get_mut(op) { + *b = first.3; + } + for _ in 0..i.range.map_or(0, |r| r.nrows) { + if let Some(o) = row_of.get_mut(k) { + *o = op as u32; + } + k += 1; + } + } + // Each tile row's fills, in drawing order (a counting sort by row). + for i in &infos { + if let Some(r) = &i.range { + for row in r.ty0..r.ty0 + r.nrows as u32 { + if let Some(c) = row_start.get_mut(row as usize + 1) { + *c += 1; + } + } + } + } + for j in 1..row_start.len() { + row_start[j] += row_start[j - 1]; + } + let mut cursor: Vec = row_start.to_vec(); + for (op, i) in infos.iter().enumerate() { + if let Some(r) = &i.range { + for row in r.ty0..r.ty0 + r.nrows as u32 { + if let Some(c) = cursor.get_mut(row as usize) + && let Some(slot) = row_ops.get_mut(*c as usize) + { + *slot = op as u32; + *c += 1; + } + } + } + } + } + // Where each tile's entries go: room for every fill whose bounds cover it (a 2D running + // sum over the bounds' corners). + let (w, h) = (tiles_x as usize + 1, tiles_y as usize + 1); + let mut cover = vec![0i64; w * h]; + for r in infos.iter().filter_map(|i| i.range) { + let (x0, y0, x1, y1) = (r.tx0 as usize, r.ty0 as usize, r.tx0 as usize + r.ncols as usize, r.ty0 as usize + r.nrows as usize); + for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] { + if let Some(c) = cover.get_mut(y * w + x) { + *c += d; + } + } + } + for y in 0..h { + for x in 0..w { + let left = if x > 0 { cover[y * w + x - 1] } else { 0 }; + let up = if y > 0 { cover[(y - 1) * w + x] } else { 0 }; + let diag = if x > 0 && y > 0 { cover[(y - 1) * w + x - 1] } else { 0 }; + cover[y * w + x] += left + up - diag; + } + } + let mut headers = vec![0u32; 2 * tiles as usize]; + let mut start = 0u64; + for ty in 0..tiles_y as usize { + for tx in 0..tiles_x as usize { + if let Some(hd) = headers.get_mut(2 * (ty * tiles_x as usize + tx)) { + *hd = start as u32; + } + start += cover.get(ty * w + tx).copied().unwrap_or(0).max(0) as u64; + } + } + if start != op_tiles { + return None; // the room per tile must add up to the op-tiles (it always does) + } + let at = [at_ops, at_polys, at_points, at_row_of, at_row_ops, at_row_start].map(|a| a as u32); + Some(Plan { input, at, op_rows: op_rows as u32, op_tiles: op_tiles as u32, piece_cap: pieces as u32, headers, edges, visits }) +} + +/// One op's share of the input to fill in: its record, polygon and point words, the fill, its +/// sizes, and its first polygon, point, op-tile and op-row. +type Job<'a> = (&'a mut [u32], &'a mut [u32], &'a mut [u32], &'a Fill, &'a Info, (u32, u32, u32, u32)); + +/// The binning pipelines (`bin.wgsl`, `scan.wgsl`). +pub(crate) struct Pipelines { + count: wgpu::ComputePipeline, + scatter: wgpu::ComputePipeline, + tiles: wgpu::ComputePipeline, + layout: wgpu::BindGroupLayout, + scan_blocks: wgpu::ComputePipeline, + scan_add: wgpu::ComputePipeline, + scan_layout: wgpu::BindGroupLayout, +} + +impl Pipelines { + pub(crate) fn new(device: &wgpu::Device) -> Pipelines { + let entry = |binding: u32, ty: wgpu::BufferBindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, count: None }; + let rw = wgpu::BufferBindingType::Storage { read_only: false }; + let bin_entries = [entry(0, wgpu::BufferBindingType::Uniform), entry(1, wgpu::BufferBindingType::Storage { read_only: true }), entry(2, rw), entry(3, rw), entry(4, rw)]; + let ([count, scatter, tiles], layout) = pipelines(device, "anicraft-bin", include_str!("bin.wgsl"), &bin_entries, ["count", "scatter", "tiles"]); + let ([scan_blocks, scan_add], scan_layout) = pipelines(device, "anicraft-scan", include_str!("scan.wgsl"), &[entry(0, wgpu::BufferBindingType::Uniform), entry(1, rw)], ["scan_blocks", "scan_add"]); + Pipelines { count, scatter, tiles, layout, scan_blocks, scan_add, scan_layout } + } +} + +/// One shader's entry points as pipelines sharing one bind group layout. +fn pipelines(device: &wgpu::Device, label: &str, src: &str, entries: &[wgpu::BindGroupLayoutEntry], points: [&str; N]) -> ([wgpu::ComputePipeline; N], wgpu::BindGroupLayout) { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: &[Some(&layout)], immediate_size: 0 }); + let pipes = points.map(|p| device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(p), layout: Some(&pl), module: &module, entry_point: Some(p), compilation_options: Default::default(), cache: None })); + (pipes, layout) +} + +/// Workgroups for `n` invocations of `width`, spread over x and y (at most 65,535 each way). +fn groups(n: u32, width: u32) -> (u32, u32) { + let g = n.div_ceil(width).max(1); + let x = g.min(65_535); + (x, g.div_ceil(x)) +} + +/// The fine pass's index and pieces, binned on the GPU into `enc` from `plan`: the index with +/// `heads` (the tile headers) at 0 and `op_heads` at `ops_at`. +#[allow(clippy::too_many_arguments)] +pub(crate) fn record(device: &wgpu::Device, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> { + use wgpu::util::DeviceExt; + let index_len = (ops_at as usize + op_heads.len()).max(4); + let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: true }); + { + let mut m = index.slice(..).get_mapped_range_mut().map_err(|e| e.to_string())?; + crate::write_words(&mut m, 0, &plan.headers); + crate::write_words(&mut m, ops_at as usize, op_heads); + } + index.unmap(); + let geo = device.create_buffer(&wgpu::BufferDescriptor { label: Some("geo"), size: 16 * u64::from(plan.piece_cap.max(1)), usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); + if plan.op_rows == 0 { + return Ok((index, geo)); + } + let n = plan.op_tiles; + // Counts, backdrops, offsets, cursors, then the scan's totals level by level. New buffers + // start zeroed. + let mut levels: Vec<[u32; 4]> = Vec::new(); + let (mut src, mut dst, mut len, mut sums) = (0u32, 2 * n, n, 4 * n); + loop { + let blocks = len.div_ceil(SCAN_BLOCK); + levels.push([src, dst, sums, len]); + if blocks <= 1 { + break; + } + (src, dst, len) = (sums, sums, blocks); + sums += blocks; + } + let work_len = (sums + 2) as u64; + let work = device.create_buffer(&wgpu::BufferDescriptor { label: Some("bin-work"), size: 4 * work_len, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false }); + let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-input"), contents: bytemuck::cast_slice(&plan.input), usage: wgpu::BufferUsages::STORAGE }); + let tiles = tiles_x * tiles_y; + let a = plan.at; + let params: [u32; 16] = [tiles_x, tiles_y, plan.op_rows, tiles, n, plan.piece_cap, entries_at, 0, a[0], a[1], a[2], a[3], a[4], a[5], 0, 0]; + let ubuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-params"), contents: bytemuck::cast_slice(¶ms), usage: wgpu::BufferUsages::UNIFORM }); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("anicraft-bin"), + layout: &pipes.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: work.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: geo.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: index.as_entire_binding() }, + ], + }); + let scans: Vec<(wgpu::BindGroup, u32)> = levels + .iter() + .map(|l| { + let u = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("scan-params"), contents: bytemuck::cast_slice(l), usage: wgpu::BufferUsages::UNIFORM }); + let b = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("anicraft-scan"), + layout: &pipes.scan_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: u.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: work.as_entire_binding() }], + }); + (b, l[3].div_ceil(SCAN_BLOCK)) + }) + .collect(); + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("anicraft-bin"), timestamp_writes: None }); + let rows = groups(plan.op_rows, 64); + pass.set_pipeline(&pipes.count); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(rows.0, rows.1, 1); + // The scan, level by level up, then each level's totals added back down. + pass.set_pipeline(&pipes.scan_blocks); + for (b, blocks) in &scans { + let g = groups(*blocks, 1); + pass.set_bind_group(0, b, &[]); + pass.dispatch_workgroups(g.0, g.1, 1); + } + pass.set_pipeline(&pipes.scan_add); + for (b, blocks) in scans.iter().rev().skip(1) { + let g = groups(*blocks, 1); + pass.set_bind_group(0, b, &[]); + pass.dispatch_workgroups(g.0, g.1, 1); + } + pass.set_pipeline(&pipes.scatter); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(rows.0, rows.1, 1); + let t = groups(tiles, 64); + pass.set_pipeline(&pipes.tiles); + pass.dispatch_workgroups(t.0, t.1, 1); + drop(pass); + Ok((index, geo)) +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ce7251c2..1d1921ad 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -2,10 +2,11 @@ //! //! Draws the same scene as the CPU oracle (`anicraft-render`) with wgpu compute: the oracle //! prepares it ([`anicraft_render::prepare_scene`]: flattening, strokes, paints and their -//! gradient tables, clips and groups), [`binning`] sorts the edges into 16 × 16 tiles on the -//! CPU, and one compute pass computes every pixel's exact area coverage and composites the -//! fills in order, inside their masks and groups (alpha and blend modes) as the oracle's band -//! compositor does. Bitmap fills are sampled from textures uploaded once per image +//! gradient tables, clips and groups), the edges are sorted into 16 × 16 tiles, on the GPU +//! ([`gpu_binning`], ADR 0048) or on the CPU ([`binning`], the reference, and the way for fills +//! in masks and groups), and one compute pass computes every pixel's exact area coverage +//! (or a hairline's distance) and composites the fills in order, inside their masks and groups +//! (alpha and blend modes) as the oracle's band compositor does. Bitmap fills are sampled from textures uploaded once per image //! ([`images`]); a filtered symbol is drawn into a layer of its own, filtered by compute passes //! that run the oracle's filter steps ([`layers`]), and composited like any fill (ADR 0032). //! The output is the oracle's within float rounding (the parity tests check mean and maximum @@ -22,6 +23,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod binning; +pub mod gpu_binning; pub mod images; mod layers; @@ -29,6 +31,7 @@ use anicraft_doc::DisplayList; use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, prepare_scene}; #[cfg(not(target_arch = "wasm32"))] use rayon::prelude::*; +use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use web_time::Instant; use wgpu::util::DeviceExt; @@ -68,11 +71,57 @@ pub struct GpuFrame { pub pixmap: Option, pub stats: RenderStats, pub timings: Timings, - /// Tile entries and edge pieces the fine pass walked. + /// Tile entries and edge pieces the fine pass walked (when binned on the GPU, the room + /// made for them: upper bounds). pub entries: usize, pub pieces: usize, + /// Whether the GPU binned the frame's tiles ([`Binning`]). + pub gpu_binned: bool, } +/// Where a frame's edges are sorted into tiles (ADR 0048). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Binning { + /// On the GPU when the scene can take it (no fill inside a mask or a group, for now) and + /// has enough edges to be worth the passes ([`AUTO_MIN_EDGES`]); otherwise on the CPU. + Auto, + /// Always on the CPU (the reference). + Cpu, + /// On the GPU whenever the scene can take it, however small (tests and benchmarks). + Gpu, +} + +impl Binning { + fn code(self) -> u8 { + match self { + Binning::Auto => 0, + Binning::Cpu => 1, + Binning::Gpu => 2, + } + } + + fn from_code(c: u8) -> Binning { + match c { + 1 => Binning::Cpu, + 2 => Binning::Gpu, + _ => Binning::Auto, + } + } + + /// `ANICRAFT_GPU_BINNING=cpu|gpu|auto` (for comparing them in the app); auto otherwise. + fn from_env() -> Binning { + match std::env::var("ANICRAFT_GPU_BINNING").map(|v| v.trim().to_ascii_lowercase()).as_deref() { + Ok("cpu") => Binning::Cpu, + Ok("gpu") => Binning::Gpu, + _ => Binning::Auto, + } + } +} + +/// Fewer edges than this are binned on the CPU in [`Binning::Auto`]: below it the CPU bins a +/// frame in less time than the GPU's passes take to set up (measured, docs/performance.md). +pub const AUTO_MIN_EDGES: u64 = 4096; + /// A frame rendered into a texture on the renderer's device: premultiplied RGBA8 /// (`Rgba8Unorm`, the bytes [`Pixmap::to_premul_rgba8`] gives), sampleable, ready for the window /// to show (egui's `register_native_texture`). The work is submitted, not waited for: anything @@ -86,6 +135,7 @@ pub struct GpuTexture { pub timings: Timings, pub entries: usize, pub pieces: usize, + pub gpu_binned: bool, } /// Where a frame's time went (milliseconds, on the calling thread). @@ -93,7 +143,8 @@ pub struct GpuTexture { pub struct Timings { /// Cull, flatten, stroke and paint set-up (shared with the oracle, parallel). pub prepare: f32, - /// Tile binning (parallel per fill and per tile row) and buffer packing. + /// Tile binning on the CPU (parallel per fill and per tile row), or laying out the GPU's + /// binning (per fill), and buffer packing. pub bin: f32, /// Upload and submit; for read-back frames also the wait for the GPU and the copy back. pub gpu: f32, @@ -131,6 +182,9 @@ pub struct GpuRenderer { texture_pipeline: wgpu::ComputePipeline, texture_layout: wgpu::BindGroupLayout, filters: layers::FilterPipelines, + bins: gpu_binning::Pipelines, + /// [`Binning`], as its code. + binning: AtomicU8, /// Bound where a texture slot or a buffer is unused. blank: wgpu::TextureView, /// Placeholders for a filter pass's coverage (written) and ramp (read): one buffer can't be @@ -316,6 +370,7 @@ impl GpuRenderer { let storage_texture = wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: wgpu::TextureFormat::Rgba8Unorm, view_dimension: wgpu::TextureViewDimension::D2 }; let (texture_pipeline, texture_layout) = make("anicraft-fine-texture", entry(5, storage_texture), "main_texture"); let filters = layers::FilterPipelines::new(&device); + let bins = gpu_binning::Pipelines::new(&device); let blank = device .create_texture(&wgpu::TextureDescriptor { label: Some("anicraft-blank"), @@ -341,6 +396,8 @@ impl GpuRenderer { texture_pipeline, texture_layout, filters, + bins, + binning: AtomicU8::new(Binning::from_env().code()), blank, blank_coverage, blank_ramp, @@ -402,7 +459,24 @@ impl GpuRenderer { }; check("read back", &self.render(&dl, &view, Output::Premul8)?.premul8)?; let t = self.render_texture(&dl, &view)?; - check("through a texture", &self.read_texture(&t)?) + check("through a texture", &self.read_texture(&t)?)?; + // And binned on the GPU (the plain fills; the bitmap and the symbol stay on the CPU's). + let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; + let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; + let got = self.render_with(&plain, &view, Output::Premul8, Binning::Gpu)?; + match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { + Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => Ok(()), + d => Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong binned on the GPU ({d:?})", self.adapter))), + } + } + + /// Where frames' edges are sorted into tiles from now on. + pub fn set_binning(&self, b: Binning) { + self.binning.store(b.code(), Ordering::Relaxed); + } + + pub fn binning(&self) -> Binning { + Binning::from_code(self.binning.load(Ordering::Relaxed)) } /// Whether the device has failed (lost, or an error in or outside a render); then use the @@ -423,19 +497,29 @@ impl GpuRenderer { /// Renders a display list and reads it back. [`GpuError::NeedsFull`] means "draw this one /// on the CPU". pub fn render(&self, dl: &DisplayList, view: &View, output: Output) -> Result { + self.render_with(dl, view, output, self.binning()) + } + + /// [`GpuRenderer::render`], binned as `binning` says (tests and benchmarks). + pub fn render_with(&self, dl: &DisplayList, view: &View, output: Output, binning: Binning) -> Result { self.guard(|| { - let (job, stats, mut timings, cost) = self.prepare(dl, view)?; + let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?; let t = Instant::now(); let (premul8, pixmap) = self.run_readback(&job, view, output)?; timings.gpu = ms(t); - Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces }) + Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() }) }) } /// Renders a display list into a new texture on this renderer's device (no readback). pub fn render_texture(&self, dl: &DisplayList, view: &View) -> Result { + self.render_texture_with(dl, view, self.binning()) + } + + /// [`GpuRenderer::render_texture`], binned as `binning` says (tests and benchmarks). + pub fn render_texture_with(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result { self.guard(|| { - let (job, stats, mut timings, cost) = self.prepare(dl, view)?; + let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?; let t = Instant::now(); let (w, h) = (view.width, view.height); let max = self.limits.max_texture_dimension_2d; @@ -464,7 +548,7 @@ impl GpuRenderer { self.queue.submit([enc.finish()]); self.pop(scopes)?; timings.gpu = ms(t); - Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces }) + Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() }) }) } @@ -511,14 +595,14 @@ impl GpuRenderer { /// The oracle's preparation and the binning, for the scene and each filtered layer it shows /// (in parallel); checked against the limits and the device's. - fn prepare(&self, dl: &DisplayList, view: &View) -> Result<(Job, RenderStats, Timings, Cost), GpuError> { + fn prepare(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result<(Job, RenderStats, Timings, Cost), GpuError> { let (w, h) = (view.width, view.height); if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { return Err(GpuError::TooLarge(format!("image {w}×{h} is outside the GPU stage's range"))); } let t0 = Instant::now(); let mut bin_ms = 0.0; - let (job, stats) = self.plan(dl, view, 0, &mut bin_ms)?; + let (job, stats) = self.plan(dl, view, 0, binning, &mut bin_ms)?; let total = ms(t0); let mut cost = Cost::default(); job.cost(&mut cost); @@ -533,10 +617,15 @@ impl GpuRenderer { } /// One scene: prepared and binned, then its shown layers planned the same way. - fn plan(&self, dl: &DisplayList, view: &View, depth: usize, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { + fn plan(&self, dl: &DisplayList, view: &View, depth: usize, binning: Binning, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { let (mut scene, stats) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; let t = Instant::now(); - let binned = binning::bin(&scene, view.width, view.height).map_err(GpuError::NeedsFull)?; + let lim = match binning { + Binning::Cpu => None, + Binning::Auto => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: AUTO_MIN_EDGES }), + Binning::Gpu => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }), + }; + let binned = binning::bin_with(&scene, view.width, view.height, lim.as_ref()).map_err(GpuError::NeedsFull)?; *bin_ms += ms(t); let shown: Vec<(u32, anicraft_render::FilterLayer)> = std::mem::take(&mut scene.layers).into_iter().zip(&binned.layer_at).filter_map(|(l, at)| Some(((*at)?, l))).collect(); // Free the prepared polygons on the pool, off this frame's path (as the oracle does). @@ -553,7 +642,7 @@ impl GpuRenderer { let shown = shown.into_iter(); let planned: Vec> = shown .map(|(at, l)| { - let (job, _) = self.plan(&l.list, &l.view, depth + 1, &mut 0.0)?; + let (job, _) = self.plan(&l.list, &l.view, depth + 1, binning, &mut 0.0)?; Ok(LayerJob { at, job: Box::new(job), view: l.view, ops: l.filters }) }) .collect(); @@ -561,11 +650,17 @@ impl GpuRenderer { Ok((Job { binned, layers }, stats)) } + /// The largest buffer the device binds. + fn binding_cap(&self) -> u64 { + self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size) + } + /// Every buffer a job binds fits what the device binds. fn check_sizes(&self, job: &Job) -> Result<(), GpuError> { - let cap = self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size); + let cap = self.binding_cap(); let b = &job.binned; - let sizes = [("tile lists", b.index.len() as u64 * 4), ("edges", b.geo.len() as u64 * 16), ("paints and layers", b.paints_len as u64 * 16)]; + let pieces = b.gpu.as_ref().map_or(b.geo.len() as u64, |p| u64::from(p.piece_cap)); + let sizes = [("tile lists", (u64::from(b.ops_at) + b.op_heads.len() as u64) * 4), ("edges", pieces * 16), ("paints and layers", b.paints_len as u64 * 16)]; for (what, n) in sizes { if n > cap { return Err(GpuError::TooLarge(format!("{what} need {} MB, more than this GPU binds ({} MB)", n >> 20, cap >> 20))); @@ -613,13 +708,34 @@ impl GpuRenderer { enc.copy_buffer_to_buffer(&img, 0, &pbuf, u64::from(l.at) * 16, 16 * n); } let views = self.images.lock().unwrap_or_else(PoisonError::into_inner).views(&self.device, &self.queue, self.limits.max_texture_dimension_2d, &b.images)?; - self.fine_pass(enc, b, &pbuf, &views, view, output, target); + let (ibuf, gbuf) = match &b.gpu { + Some(plan) => gpu_binning::record(&self.device, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?, + None => self.upload_lists(b)?, + }; + self.fine_pass(enc, b, &ibuf, &gbuf, &pbuf, &views, view, output, target); Ok(()) } + /// The CPU's tile lists and op headers, and its pieces, as buffers. + fn upload_lists(&self, b: &binning::Binned) -> Result<(wgpu::Buffer, wgpu::Buffer), GpuError> { + let len = (b.ops_at as usize + b.op_heads.len()).max(4); + let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * len as u64, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: true }); + { + let mut m = ibuf.slice(..).get_mapped_range_mut().map_err(|e| GpuError::Device(e.to_string()))?; + write_words(&mut m, 0, &b.index); + write_words(&mut m, b.ops_at as usize, &b.op_heads); + } + ibuf.unmap(); + // Bindings can't be empty: pad to one vec4. + let pad = [[0f32; 4]]; + let geo: &[[f32; 4]] = if b.geo.is_empty() { &pad } else { &b.geo }; + let gbuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("geo"), contents: bytemuck::cast_slice(geo), usage: wgpu::BufferUsages::STORAGE }); + Ok((ibuf, gbuf)) + } + /// Uploads the binned scene and records the fine pass into `target`. #[allow(clippy::too_many_arguments)] - fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) { + fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, ibuf: &wgpu::Buffer, gbuf: &wgpu::Buffer, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) { let bg = view.background.map_or([0.0; 4], premultiply); let mut uniform = [0u32; 12]; uniform[..4].copy_from_slice(&[view.width, view.height, b.tiles_x, u32::from(output == Output::Float)]); @@ -627,15 +743,7 @@ impl GpuRenderer { for (u, f) in uniform[8..].iter_mut().zip(bg) { *u = f.to_bits(); } - let storage = |label: &str, bytes: &[u8]| { - // Bindings can't be empty: pad to one vec4. - let pad = [0u8; 16]; - let contents = if bytes.is_empty() { &pad[..] } else { bytes }; - self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE }) - }; let ubuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("params"), contents: bytemuck::cast_slice(&uniform), usage: wgpu::BufferUsages::UNIFORM }); - let ibuf = storage("index", bytemuck::cast_slice(&b.index)); - let gbuf = storage("geo", bytemuck::cast_slice(&b.geo)); let mut entries = vec![ wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: ibuf.as_entire_binding() }, @@ -695,6 +803,30 @@ impl GpuRenderer { }) } + /// The tile lists the GPU bins for `dl` (forced, however small), read back as a + /// [`binning::Binned`] like the CPU's: `None` when the scene isn't one the GPU bins. + #[cfg(test)] + pub(crate) fn gpu_lists(&self, dl: &DisplayList, view: &View) -> Result, GpuError> { + let (scene, _) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; + let lim = gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }; + let mut b = binning::bin_with(&scene, view.width, view.height, Some(&lim)).map_err(GpuError::NeedsFull)?; + let Some(plan) = b.gpu.take() else { return Ok(None) }; + let scopes = Scopes::push(&self.device); + let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-bin-test") }); + let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?; + let (isize, gsize) = (ibuf.size(), gbuf.size()); + let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: isize + gsize, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + enc.copy_buffer_to_buffer(&ibuf, 0, &read, 0, isize); + enc.copy_buffer_to_buffer(&gbuf, 0, &read, isize, gsize); + self.queue.submit([enc.finish()]); + let bytes = self.map(&read, scopes)?; + let words: Vec = bytes.as_chunks::<4>().0.iter().map(|w| u32::from_le_bytes(*w)).collect(); + let n = isize as usize / 4; + b.index = words.get(..b.ops_at as usize).unwrap_or(&[]).to_vec(); + b.geo = words.get(n..).unwrap_or(&[]).as_chunks::<4>().0.iter().map(|v| v.map(f32::from_bits)).collect(); + Ok(Some(b)) + } + /// Waits for `read`'s copy, pops the error scopes and returns its bytes. fn map(&self, read: &wgpu::Buffer, scopes: Scopes) -> Result, GpuError> { let (tx, rx) = std::sync::mpsc::channel(); @@ -766,6 +898,14 @@ pub(crate) fn describe(e: &wgpu::Error) -> String { } } +/// Writes `words` at word `at` of a mapped buffer, if they fit. +pub(crate) fn write_words(m: &mut wgpu::BufferViewMut, at: usize, words: &[u32]) { + let (a, b) = (4 * at, 4 * (at + words.len())); + if !words.is_empty() && b <= m.len() { + m.slice(a..b).copy_from_slice(bytemuck::cast_slice(words)); + } +} + fn ms(t: Instant) -> f32 { t.elapsed().as_secs_f32() * 1000.0 } diff --git a/crates/gpu/src/scan.wgsl b/crates/gpu/src/scan.wgsl new file mode 100644 index 00000000..82be5c04 --- /dev/null +++ b/crates/gpu/src/scan.wgsl @@ -0,0 +1,83 @@ +// AniCraft GPU stage: the prefix sum for the GPU binning (ADR 0048, bin.wgsl). +// +// An exclusive scan of `n` values in `values` (the binning's working buffer): each workgroup +// scans 1024 of them (four per invocation, then the invocations' totals in workgroup memory) +// and leaves its total; the totals are scanned the same way, level by level, and added back. +// The public work-efficient scan (Blelloch's "Prefix sums and their applications", 1990), in +// its simplest form. + +// `src`, `dst` and the workgroups' totals (`sums`) in `work`, and how many values. +struct ScanParams { + src: u32, + dst: u32, + sums: u32, + n: u32, +} + +@group(0) @binding(0) var sp: ScanParams; +@group(0) @binding(1) var values: array; + +var sh: array; + +fn load(i: u32) -> u32 { + if i < sp.n { + return values[sp.src + i]; + } + return 0u; +} + +fn store(i: u32, v: u32) { + if i < sp.n { + values[sp.dst + i] = v; + } +} + +// Each workgroup scans 1024 values (four per invocation), exclusive, and leaves its total. +@compute @workgroup_size(256) +fn scan_blocks(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) nw: vec3, @builtin(local_invocation_id) lid: vec3) { + let block = wg.y * nw.x + wg.x; + let base = block * 1024u + lid.x * 4u; + // Four values by name, not a loop over an array: FXC (Direct3D's compiler) must unroll + // loops that index local arrays. + let v0 = load(base); + let v1 = load(base + 1u); + let v2 = load(base + 2u); + let v3 = load(base + 3u); + let total = v0 + v1 + v2 + v3; + sh[lid.x] = total; + workgroupBarrier(); + for (var off = 1u; off < 256u; off <<= 1u) { + var t = 0u; + if lid.x >= off { + t = sh[lid.x - off]; + } + workgroupBarrier(); + sh[lid.x] += t; + workgroupBarrier(); + } + let acc = sh[lid.x] - total; + store(base, acc); + store(base + 1u, acc + v0); + store(base + 2u, acc + v0 + v1); + store(base + 3u, acc + v0 + v1 + v2); + // (A dispatch spread over x and y may have a few workgroups past the end.) + if lid.x == 255u && block * 1024u < sp.n { + values[sp.sums + block] = sh[255]; + } +} + +// Adds each workgroup's scanned total to its values. +@compute @workgroup_size(256) +fn scan_add(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) nw: vec3, @builtin(local_invocation_id) lid: vec3) { + let block = wg.y * nw.x + wg.x; + if block * 1024u >= sp.n { + return; + } + let add = values[sp.sums + block]; + for (var i = 0u; i < 4u; i++) { + let at = block * 1024u + lid.x * 4u + i; + if at < sp.n { + values[sp.dst + at] += add; + } + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index adce571b..0bbb4730 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -294,9 +294,9 @@ fn emulate(b: &Binned, v: &View) -> Vec { } k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"), } - let hd = b.ops_at as usize + op * 4; - let mut cov = entry_cover(&b.geo[first..first + n], bd, b.index[hd + 1], lx, ly); - let flags = b.index[hd + 3]; + let hd = op * 4; + let mut cov = entry_cover(&b.geo[first..first + n], bd, b.op_heads[hd + 1], lx, ly); + let flags = b.op_heads[hd + 3]; if flags & bn::ART != 0 { let k = cov.clamp(0.0, 1.0); level = level + k - level * k; @@ -308,7 +308,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { if cov <= 1e-4 { continue; } - let s = match b.index[hd] { + let s = match b.op_heads[hd] { 0 => solid_of(b, op), kind => { let base = op * PAINT_VEC4S; @@ -318,7 +318,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { let d = q - Vec2::new(nn[2], nn[3]); let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { d.length() * g[2] }; let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255; - b.paints[b.index[hd + 2] as usize + i] + b.paints[b.op_heads[hd + 2] as usize + i] } }; let sa = s[3] * cov; @@ -977,3 +977,97 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() { } } + +// ----- binning on the GPU (ADR 0048) ---------------------------------------------------------- + +/// Scenes the GPU bins (no fill in a mask or a group): the analytic ones, the sample, stress +/// frames at awkward scales and offsets, and onion-skin style outlines over them. +fn gpu_binned_scenes() -> Vec<(String, DisplayList, View)> { + let plain = |dl: &DisplayList| dl.items.iter().all(|i| i.clip.is_none() && i.group.is_none()); + let mut out: Vec<(String, DisplayList, View)> = scenes().into_iter().filter(|(_, dl, _)| plain(dl)).map(|(n, dl, v)| (n.to_string(), dl, v)).collect(); + let demo = sample::demo(); + out.push(("sample".into(), anicraft_doc::evaluate(&demo, 13), View::stage(&demo, 0.37))); + let doc = sample::stress(20, 100, 48); + for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] { + let dl = anicraft_doc::evaluate(&doc, f); + let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) }; + out.push((format!("stress frame {f} at {s}"), dl, v)); + } + // Onion skin's outlines: the frames before and after as hairlines, under the playhead's. + let mut dl = DisplayList::default(); + for f in [25u32, 27, 33, 35] { + let mut part = anicraft_doc::evaluate(&doc, f); + for i in &mut part.items { + i.outline = Some(Rgba::hex(if f < 30 { 0x4f8dff } else { 0x4cd07d }).with_alpha(0.4)); + } + dl.append(part); + } + dl.append(anicraft_doc::evaluate(&doc, 30)); + out.push(("stress with outlined frames".into(), dl, View::stage(&doc, 0.8))); + out +} + +/// What an entry covers in each of its tile's 256 pixels. +fn entry_pixels(b: &Binned, e: usize) -> [f32; 256] { + let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]); + let rule = b.op_heads[4 * op + 1]; + let pieces = b.geo.get(first..first + n).unwrap_or(&[]); + std::array::from_fn(|i| entry_cover(pieces, bd, rule, i % 16, i / 16)) +} + +#[test] +fn gpu_binning_produces_the_cpus_tile_lists() { + let Some(g) = gpu() else { return }; + for (name, dl, v) in gpu_binned_scenes() { + let Some(gb) = g.gpu_lists(&dl, &v).unwrap() else { panic!("{name}: the GPU should bin this") }; + let (scene, _) = prepare_scene(&dl, &v).unwrap(); + let cb = binning::bin(&scene, v.width, v.height).unwrap(); + assert_eq!((gb.tiles_x, gb.tiles_y, &gb.op_heads), (cb.tiles_x, cb.tiles_y, &cb.op_heads), "{name}"); + let (mut entries, mut pieces) = (0usize, 0usize); + for t in 0..(cb.tiles_x * cb.tiles_y) as usize { + let list = |b: &Binned| -> Vec<(u32, [f32; 256])> { + let (s, n) = (b.index[2 * t] as usize, b.index[2 * t + 1] as usize); + (s..s + n).map(|i| b.entries_at as usize + 4 * i).map(|e| (b.index[e], entry_pixels(b, e))).collect() + }; + let (a, c) = (list(&gb), list(&cb)); + let ops = |l: &[(u32, [f32; 256])]| l.iter().map(|x| x.0).collect::>(); + assert_eq!(ops(&a), ops(&c), "{name}: tile {t}'s fills"); + for ((op, pa), (_, pc)) in a.iter().zip(&c) { + let worst = pa.iter().zip(pc).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "{name}: tile {t}, op {op}: coverage off by {worst}"); + } + entries += a.len(); + let (s, n) = (gb.index[2 * t] as usize, gb.index[2 * t + 1] as usize); + pieces += (s..s + n).map(|i| gb.index[gb.entries_at as usize + 4 * i + 2] as usize).sum::(); + } + assert_eq!(entries, cb.entries, "{name}"); + assert!(pieces <= gb.pieces && entries <= gb.entries, "{name}: within the room made for them"); + // And the fine pass's arithmetic over the GPU's lists draws the oracle's picture. + let (oracle, _) = render(&dl, &v).unwrap(); + let eg = emulate(&gb, &v); + let (mean, max) = f32_diff(&eg, &oracle.data); + assert!(mean < 1e-4 && max < 4e-3, "{name}: mean {mean:e}, max {max:e}"); + } +} + +#[test] +fn gpu_binned_frames_match_the_oracle() { + let Some(g) = gpu() else { return }; + for (name, dl, v) in gpu_binned_scenes() { + let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); + assert!(f.gpu_binned, "{name}"); + let (oracle, _) = render(&dl, &v).unwrap(); + let d = compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap(); + assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{name}: {d:?}"); + let t = g.render_texture_with(&dl, &v, Binning::Gpu).unwrap(); + assert!(t.gpu_binned && g.read_texture(&t).unwrap() == f.premul8, "{name}: the texture holds the read-back bytes"); + } + // Masks and groups stay on the CPU's binning, and still draw right. + for (name, dl, v) in composited_scenes() { + let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); + let uses = |dl: &DisplayList| dl.items.iter().any(|i| i.clip.is_some() || i.group.is_some()); + assert_eq!(f.gpu_binned, !uses(&dl), "{name}: binned on the GPU {}", f.gpu_binned); + let (oracle, _) = render(&dl, &v).unwrap(); + assert!(compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap().max <= 2, "{name}"); + } +} From f375849413376bb9282c6bb47b76565069767285 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:14:10 -0700 Subject: [PATCH 022/402] perf(gpu): upload only the tile headers when the GPU bins, bin from 32,768 edges, cheap hairline rejects (M3) Mapping the GPU-binned index at creation zeroed and copied its whole room for entries on the CPU; the headers and op headers now go through the queue and the rest starts zeroed on the GPU. 50k shapes at 4K, direct: 50 -> 24 ms (CPU-binned: 121 ms). Auto bins on the GPU from 32,768 edges: forcing it on every 512 px stage tile made the 1,000-shape 4K stage 1.9x slower and the 10k-shape one 1.3x (per-tile pass set-up); with the threshold the tiled stage never loses (10k at 4K 10.5 -> 10.0 ms, 50k 63.6 -> 38.4 ms). A hairline segment whose box is out of reach of a pixel is skipped before the distance (same coverage). gpu_bench compares CPU and Auto binning and checks budgets (--check). --- crates/gpu/examples/gpu_bench.rs | 156 ++++++++++++++++++------------- crates/gpu/src/fine.wgsl | 10 +- crates/gpu/src/gpu_binning.rs | 17 ++-- crates/gpu/src/lib.rs | 6 +- 4 files changed, 114 insertions(+), 75 deletions(-) diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index a8df5239..14c54690 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -1,19 +1,21 @@ -//! GPU stage timings and parity against the CPU oracle (ADR 0019, ADR 0029, ADR 0032; numbers +//! GPU stage timings and parity against the CPU oracle (ADR 0019, 0029, 0032, 0048; numbers //! in docs/performance.md). //! //! ```sh //! cargo run --release -p anicraft-gpu --example gpu_bench //! cargo run --release -p anicraft-gpu --example gpu_bench -- --layers 50 --shapes 200 +//! cargo run --release -p anicraft-gpu --example gpu_bench -- --only onion +//! cargo run --release -p anicraft-gpu --example gpu_bench -- --check # fails past a budget //! ``` -//! Prints the adapter, then for each scene and size: CPU ms; the first slice's read-back path -//! (prepare + bin + upload, compute, copy back); the direct path the window uses (into a -//! texture, no readback): what the calling thread spends, and until the GPU has finished; the -//! stage's way (512 px tiles drawn in parallel, as the render service does, until finished); -//! the work the fine pass did; and how far the GPU's picture is from the oracle's. +//! Prints the adapter, then for each scene and size: CPU ms; then, with the tiles binned on +//! the CPU and then on the GPU (ADR 0048), the direct path the window uses (into a texture, no +//! readback): what the calling thread spends, and until the GPU has finished; the stage's way +//! (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_geom::{FillRule, Path}; -use anicraft_gpu::{GpuRenderer, Output, compare_premul8}; +use anicraft_gpu::{Binning, GpuRenderer, compare_premul8}; use anicraft_geom::Affine; use anicraft_render::{View, render}; use rayon::prelude::*; @@ -190,7 +192,21 @@ fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList { dl } +/// Timing budgets for the stage on the GPU (docs/performance.md › Budgets), checked with +/// `--check` on a known machine: `(scene, width, what, limit in ms)`, `what` being the Auto +/// column's `direct` or `tiled` (the stage's way). +const BUDGETS: &[(&str, u32, &str, f64)] = &[ + ("1,000 shapes", 3840, "tiled", 16.7), + ("stress 50×200", 3840, "tiled", 16.7), + ("50,000 shapes", 1920, "tiled", 33.3), + ("50,000 shapes", 3840, "direct", 33.3), +]; +/// Outline mode against tinted onion skin (ADR 0048: no slower), at 1080p in stage tiles. +const OUTLINE_RATIO: f64 = 1.25; + fn main() { + let check = std::env::args().any(|a| a == "--check"); + let mut measured: Vec<(String, u32, &str, f64)> = Vec::new(); let gpu = match GpuRenderer::new() { Ok(g) => g, Err(e) => { @@ -217,9 +233,12 @@ fn main() { ("onion ±5 tinted".into(), onion_doc.clone(), Onion::Tinted), ("onion ±5 outlines".into(), onion_doc, Onion::Outlines), ]; + println!("Per scene and size: the CPU oracle, then the GPU stage with the tiles binned on the CPU, then as Binning::Auto bins them (on the GPU with --forced):"); + println!("direct = the calling thread's time with render_texture (prepare + bin + upload/submit), waited = until the GPU has finished,"); + println!("tiled = 512 px stage tiles in parallel until finished. Parity: the GPU-binned picture against the oracle (mean / max / px)."); println!( - "{:<20} {:>10} {:>8} {:>9} {:>9} {:>9} {:>7} {:>22} {:>8} {:>8} parity (mean / max / differing px)", - "scene", "size", "CPU ms", "readback", "direct", "direct+", "tiled", "prepare + bin + submit", "entries", "pieces" + "{:<20} {:>10} {:>7} | {:>7} {:>7} {:>7} {:>19} | {:>7} {:>7} {:>7} {:>19} | parity", + "scene", "size", "CPU", "direct", "waited", "tiled", "prep + bin + gpu", "direct", "waited", "tiled", "prep + bin + gpu" ); for (name, doc, onion) in scenes.iter().filter(|(n, ..)| only.as_ref().is_none_or(|o| n.contains(o.as_str()))) { for scale in [1.0f32, 2.0] { @@ -227,77 +246,88 @@ fn main() { let frames = doc.frame_count().max(1); let evaluate = |doc: &Document, f: u32| onion_list(doc, f, *onion); let dl0 = evaluate(doc, if *onion == Onion::Off { 0 } else { 30 }); - // Warm-up (pipeline caches, allocations). - let _ = gpu.render(&dl0, &v, Output::Premul8); - let _ = gpu.render_texture(&dl0, &v); - let _ = gpu.wait_idle(); - let _ = render(&dl0, &v); let lists: Vec<_> = (0..runs).map(|i| evaluate(doc, (i * 20) % frames)).collect(); let per = |t: Instant| t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs); + let _ = render(&dl0, &v); let t = Instant::now(); for dl in &lists { let _ = render(dl, &v); } let cpu_ms = per(t); - let t = Instant::now(); - for dl in &lists { - let _ = gpu.render(dl, &v, Output::Premul8); - } - let readback_ms = per(t); - // Direct: what the calling thread spends (the stage's cost per tile), then each frame - // waited for to the end (the latency until the window can show it). - let mut sum = [0.0f32; 3]; - let mut work = (0, 0); - let t = Instant::now(); - let mut keep = Vec::with_capacity(lists.len()); - for dl in &lists { - if let Ok(f) = gpu.render_texture(dl, &v) { - sum[0] += f.timings.prepare; - sum[1] += f.timings.bin; - sum[2] += f.timings.gpu; - work = (f.entries, f.pieces); - keep.push(f); - } - } - let direct_ms = per(t); - let _ = gpu.wait_idle(); - drop(keep); - let t = Instant::now(); - for dl in &lists { - let _ = gpu.render_texture(dl, &v); - let _ = gpu.wait_idle(); - } - let done_ms = per(t); - // The stage: 512 px tiles of the same frame, in parallel, then waited for. + // The stage's tiles: 512 px of the same frame, drawn in parallel. let tiles: Vec = (0..v.height.div_ceil(512)) .flat_map(|ty| (0..v.width.div_ceil(512)).map(move |tx| (tx, ty))) .map(|(tx, ty)| View { transform: Affine::translate(-((tx * 512) as f32), -((ty * 512) as f32)).mul(&v.transform), width: 512.min(v.width - tx * 512), height: 512.min(v.height - ty * 512), background: v.background }) .collect(); - let t = Instant::now(); - for dl in &lists { - let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture(dl, tv).ok()).collect(); + let mut cols = Vec::new(); + let mut binned_on_gpu = false; + let second = if std::env::args().any(|a| a == "--forced") { Binning::Gpu } else { Binning::Auto }; + for binning in [Binning::Cpu, second] { + // Warm-up (pipeline caches, allocations). + let _ = gpu.render_texture_with(&dl0, &v, binning); let _ = gpu.wait_idle(); + let mut sum = [0.0f32; 3]; + let t = Instant::now(); + let mut keep = Vec::with_capacity(lists.len()); + for dl in &lists { + if let Ok(f) = gpu.render_texture_with(dl, &v, binning) { + sum[0] += f.timings.prepare; + sum[1] += f.timings.bin; + sum[2] += f.timings.gpu; + binned_on_gpu |= f.gpu_binned; + keep.push(f); + } + } + let direct = per(t); + let _ = gpu.wait_idle(); + drop(keep); + let t = Instant::now(); + for dl in &lists { + let _ = gpu.render_texture_with(dl, &v, binning); + let _ = gpu.wait_idle(); + } + let waited = per(t); + let t = Instant::now(); + for dl in &lists { + let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture_with(dl, tv, binning).ok()).collect(); + let _ = gpu.wait_idle(); + } + let tiled = per(t); + let n = runs as f32; + if binning == Binning::Auto { + measured.push((name.clone(), v.width, "direct", direct)); + measured.push((name.clone(), v.width, "tiled", tiled)); + } + cols.push(format!("{direct:>7.2} {waited:>7.2} {tiled:>7.2} {:>19}", format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n))); } - let tiled_ms = per(t); - let n = runs as f32; - let parity = match (gpu.render_texture(&dl0, &v).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) { + let parity = match (gpu.render_texture_with(&dl0, &v, Binning::Gpu).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) { (Ok(g), Ok((c, _))) => compare_premul8(&g, &c.to_premul_rgba8()).map_or("size mismatch".into(), |d| format!("{:.4} / {} / {}", d.mean, d.max, d.differing)), (Err(e), _) => format!("GPU: {e}"), (_, Err(e)) => format!("CPU: {e}"), }; - println!( - "{:<20} {:>10} {:>8.2} {:>9.2} {:>9.2} {:>9.2} {:>7.2} {:>22} {:>8} {:>8} {parity}", - name, - format!("{}×{}", v.width, v.height), - cpu_ms, - readback_ms, - direct_ms, - done_ms, - tiled_ms, - format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n), - work.0, - work.1 - ); + let note = if binned_on_gpu { "" } else { " (binned on the CPU: masks, groups or few edges)" }; + println!("{:<20} {:>10} {:>7.2} | {} | {} | {parity}{note}", name, format!("{}×{}", v.width, v.height), cpu_ms, cols[0], cols[1]); } } + if !check { + return; + } + let get = |scene: &str, w: u32, what: &str| measured.iter().find(|m| m.0 == scene && m.1 == w && m.2 == what).map(|m| m.3); + let mut missed = 0; + println!(); + println!("budgets (the means above; run on a quiet machine)"); + for &(scene, w, what, limit) in BUDGETS { + let got = get(scene, w, what); + let ok = got.is_some_and(|g| g <= limit); + missed += usize::from(!ok); + println!(" {} {scene} at {w} px, {what}: {} (budget {limit} ms)", if ok { "ok " } else { "MISS" }, got.map_or("not measured".into(), |g| format!("{g:.2} ms"))); + } + let ratio = get("onion ±5 outlines", 1920, "tiled").zip(get("onion ±5 tinted", 1920, "tiled")).map(|(o, t)| o / t); + let ok = ratio.is_some_and(|r| r <= OUTLINE_RATIO); + missed += usize::from(!ok); + println!(" {} onion outlines / tinted at 1920 px, tiled: {} (budget {OUTLINE_RATIO})", if ok { "ok " } else { "MISS" }, ratio.map_or("not measured".into(), |r| format!("{r:.2}"))); + if missed > 0 { + println!("{missed} budget(s) missed"); + std::process::exit(1); + } } diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 9a81fc4c..c95ed41e 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -383,7 +383,15 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { var d = 2.0; let pc = vec2(px + 0.5, py + 0.5); for (var k = 0u; k < pieces; k++) { - d = min(d, seg_dist(pc, geo[first + k])); + let sg = geo[first + k]; + // Out of reach of the segment's box: at least 1 away, so it can't be nearest + // within reach (the coverage comes out the same, without the division). + let lo = min(sg.xy, sg.zw) - vec2(1.0); + let hi = max(sg.xy, sg.zw) + vec2(1.0); + if any(pc < lo) || any(pc > hi) { + continue; + } + d = min(d, seg_dist(pc, sg)); } cov = clamp(1.0 - d, 0.0, 1.0); } else { diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs index 7e9390ee..106488b7 100644 --- a/crates/gpu/src/gpu_binning.rs +++ b/crates/gpu/src/gpu_binning.rs @@ -321,18 +321,19 @@ fn groups(n: u32, width: u32) -> (u32, u32) { } /// The fine pass's index and pieces, binned on the GPU into `enc` from `plan`: the index with -/// `heads` (the tile headers) at 0 and `op_heads` at `ops_at`. +/// the tile headers at 0 and `op_heads` at `ops_at`. Only those are uploaded (through `queue`, +/// ahead of `enc`'s submission): the entries' room starts zeroed on the GPU. #[allow(clippy::too_many_arguments)] -pub(crate) fn record(device: &wgpu::Device, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> { +pub(crate) fn record(device: &wgpu::Device, queue: &wgpu::Queue, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> { use wgpu::util::DeviceExt; let index_len = (ops_at as usize + op_heads.len()).max(4); - let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: true }); - { - let mut m = index.slice(..).get_mapped_range_mut().map_err(|e| e.to_string())?; - crate::write_words(&mut m, 0, &plan.headers); - crate::write_words(&mut m, ops_at as usize, op_heads); + let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + if !plan.headers.is_empty() && plan.headers.len() <= index_len { + queue.write_buffer(&index, 0, bytemuck::cast_slice(&plan.headers)); + } + if !op_heads.is_empty() && ops_at as usize + op_heads.len() <= index_len { + queue.write_buffer(&index, 4 * u64::from(ops_at), bytemuck::cast_slice(op_heads)); } - index.unmap(); let geo = device.create_buffer(&wgpu::BufferDescriptor { label: Some("geo"), size: 16 * u64::from(plan.piece_cap.max(1)), usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); if plan.op_rows == 0 { return Ok((index, geo)); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 1d1921ad..c1b9dd15 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -120,7 +120,7 @@ impl Binning { /// Fewer edges than this are binned on the CPU in [`Binning::Auto`]: below it the CPU bins a /// frame in less time than the GPU's passes take to set up (measured, docs/performance.md). -pub const AUTO_MIN_EDGES: u64 = 4096; +pub const AUTO_MIN_EDGES: u64 = 32_768; /// A frame rendered into a texture on the renderer's device: premultiplied RGBA8 /// (`Rgba8Unorm`, the bytes [`Pixmap::to_premul_rgba8`] gives), sampleable, ready for the window @@ -709,7 +709,7 @@ impl GpuRenderer { } let views = self.images.lock().unwrap_or_else(PoisonError::into_inner).views(&self.device, &self.queue, self.limits.max_texture_dimension_2d, &b.images)?; let (ibuf, gbuf) = match &b.gpu { - Some(plan) => gpu_binning::record(&self.device, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?, + Some(plan) => gpu_binning::record(&self.device, &self.queue, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?, None => self.upload_lists(b)?, }; self.fine_pass(enc, b, &ibuf, &gbuf, &pbuf, &views, view, output, target); @@ -813,7 +813,7 @@ impl GpuRenderer { let Some(plan) = b.gpu.take() else { return Ok(None) }; let scopes = Scopes::push(&self.device); let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-bin-test") }); - let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?; + let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.queue, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?; let (isize, gsize) = (ibuf.size(), gbuf.size()); let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: isize + gsize, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); enc.copy_buffer_to_buffer(&ibuf, 0, &read, 0, isize); From ba34521d0cfb9f7b696790179e2571af344a4317 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:19:22 -0700 Subject: [PATCH 023/402] perf(gpu): hairlines reach only the tiles they can touch, and bound in O(1) (M3) A hairline segment went into every tile within 2 px of it; 1.25 px is enough (a pixel centre within its reach is within 1 px of a point of it, plus rounding). The room for its pieces is its padded box's tiles, row by row only for long segments. Onion outlines against tinted, GPU stage, best of three: 1080p tiles 10.2 vs 9.5 ms, 4K tiles 15.1 vs 15.4 ms, one texture 7.2 vs 7.1 ms. --- crates/gpu/src/bin.wgsl | 4 ++-- crates/gpu/src/binning.rs | 7 ++++--- crates/gpu/src/gpu_binning.rs | 24 ++++++++++++++++++++---- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/gpu/src/bin.wgsl b/crates/gpu/src/bin.wgsl index e062c6b0..817e92ee 100644 --- a/crates/gpu/src/bin.wgsl +++ b/crates/gpu/src/bin.wgsl @@ -43,8 +43,8 @@ struct Params { const T: f32 = 16.0; // gpu_binning.rs › HAIRLINE_BIT: the op is a hairline. const HAIRLINE_BIT: u32 = 0x80000000u; -// Margins of a hairline's reach (binning.rs › hairline_tiles). -const M: f32 = 2.0; +// How far around a hairline segment its tiles are taken (binning.rs › HAIRLINE_MARGIN). +const M: f32 = 1.25; // What to do with a piece. const COUNT: u32 = 0u; diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 809f68c4..14cda964 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -51,9 +51,10 @@ const T: f32 = TILE as f32; pub const NONE: u32 = u32::MAX; /// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd). pub const HAIRLINE: u32 = 2; -/// How far from a hairline segment its tiles reach: pixel centres within its reach lie within -/// this of it (`bin.wgsl` › `M`). -pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 1.0; +/// How far around a hairline segment its tiles are taken (`bin.wgsl` › `M`): a pixel centre +/// within its reach is within `REACH` of a point of it, so the tile holding that centre holds a +/// point within `REACH` of the segment's box; a quarter pixel more absorbs rounding. +pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 0.25; /// `vec4`s of paint data per fill. pub const PAINT_VEC4S: usize = 4; /// Gradient table entries (the oracle's LUT size). diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs index 106488b7..31cc3dcb 100644 --- a/crates/gpu/src/gpu_binning.rs +++ b/crates/gpu/src/gpu_binning.rs @@ -75,10 +75,7 @@ fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info { for poly in &f.polys { if f.hairline { let mut seg = |a, b| { - // With a pixel more reach than the binning's, whatever the GPU's rounding. - let mut n = 0u64; - hairline_tiles(a, b, &r, HAIRLINE_MARGIN + 1.0, |_, _| n += 1); - pieces += n; + pieces += hairline_pieces(a, b, &r); edges += 1; }; match poly.as_slice() { @@ -103,6 +100,25 @@ fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info { Info { range: Some(r), polys: f.polys.len() as u32, points, edges, pieces } } +/// At most how many tiles a hairline segment reaches (`binning.rs` › `hairline_tiles`), with a +/// pixel more reach than the binning's, whatever the GPU's rounding: the tiles of its padded +/// box (most segments are short), or row by row for a long one, where the box would be loose. +fn hairline_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 { + if !(a.is_finite() && b.is_finite()) { + return 0; + } + let (t, m) = (TILE as f32, HAIRLINE_MARGIN + 1.0); + let span = |lo: f32, hi: f32, base: f32, n: i32| (((hi + m - base) / t).floor().min((n - 1) as f32) - ((lo - m - base) / t).floor().max(0.0) + 1.0).max(0.0); + let rows = span(a.y.min(b.y), a.y.max(b.y), r.ylo, r.nrows); + let cols = span(a.x.min(b.x), a.x.max(b.x), r.xlo, r.ncols); + if rows * cols <= 16.0 { + return (rows * cols) as u64; + } + let mut n = 0u64; + hairline_tiles(a, b, r, m, |_, _| n += 1); + n +} + /// At most how many pieces edge `a → b` gives (`binning.rs` › `split_edge` and `steps`): one /// per tile row it spans, one more per column boundary it crosses, a left-edge step per column /// boundary it passes, and one for where it meets the next edge; with slack for rounding. From 750c90edeccadbde8048fc8042393f67a09aebf7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:23:00 -0700 Subject: [PATCH 024/402] fix(gpu): a device whose GPU binning fails its self-test bins on the CPU; Auto bins on the GPU on Vulkan only (M3) The start-up self-test checks the GPU binning apart: if it comes back wrong only the binning stays on the CPU (gpu_binning_off says why), instead of the whole GPU stage switching off; the tests require it to work wherever the GPU stage runs (lavapipe in CI). On Direct3D 12 the binning passes cost more per stage tile than the CPU binning (onion +-5 at 1080p in tiles: 9.7 -> 14.4 ms, measured twice), so Auto keeps the CPU's there and on backends not yet measured; ANICRAFT_GPU_BINNING=gpu still forces it. --- crates/gpu/src/lib.rs | 51 ++++++++++++++++++++++++++++++----------- crates/gpu/src/tests.rs | 2 ++ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index c1b9dd15..0bbec69a 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -82,8 +82,9 @@ pub struct GpuFrame { /// Where a frame's edges are sorted into tiles (ADR 0048). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Binning { - /// On the GPU when the scene can take it (no fill inside a mask or a group, for now) and - /// has enough edges to be worth the passes ([`AUTO_MIN_EDGES`]); otherwise on the CPU. + /// On the GPU when the scene can take it (no fill inside a mask or a group, for now), has + /// enough edges to be worth the passes ([`AUTO_MIN_EDGES`]) and the device runs Vulkan + /// (where it was measured to win); otherwise on the CPU. Auto, /// Always on the CPU (the reference). Cpu, @@ -185,6 +186,13 @@ pub struct GpuRenderer { bins: gpu_binning::Pipelines, /// [`Binning`], as its code. binning: AtomicU8, + /// Why the GPU doesn't bin on this device (its self-test came back wrong); then every + /// frame bins on the CPU, and the rest of the GPU stage still runs. + no_gpu_binning: Mutex>, + /// Whether [`Binning::Auto`] bins on the GPU on this backend: on Vulkan, where it was + /// measured to win in the stage's tiles. On Direct3D 12 the passes cost more per stage tile + /// than the CPU's binning (ADR 0048), and other backends aren't measured yet. + auto_bins: bool, /// Bound where a texture slot or a buffer is unused. blank: wgpu::TextureView, /// Placeholders for a filter pass's coverage (written) and ramp (read): one buffer can't be @@ -301,7 +309,7 @@ impl GpuRenderer { } let limits = device.limits(); check(adapter, &limits, &name)?; - Self::build(device, queue, limits, name, true, Arc::new(Mutex::new(None))) + Self::build(device, queue, limits, name, info.backend, true, Arc::new(Mutex::new(None))) })) .unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into()))) } @@ -339,10 +347,10 @@ impl GpuRenderer { g.get_or_insert_with(|| format!("device lost: {msg}")); }); } - Self::build(device, queue, want, name, false, broken) + Self::build(device, queue, want, name, info.backend, false, broken) } - fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, shared: bool, broken: Arc>>) -> Result { + fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, backend: wgpu::Backend, shared: bool, broken: Arc>>) -> Result { let scopes = Scopes::push(&device); let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("anicraft-fine"), source: wgpu::ShaderSource::Wgsl(include_str!("fine.wgsl").into()) }); let entry = |binding: u32, ty: wgpu::BindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }; @@ -398,6 +406,8 @@ impl GpuRenderer { filters, bins, binning: AtomicU8::new(Binning::from_env().code()), + no_gpu_binning: Mutex::new(None), + auto_bins: backend == wgpu::Backend::Vulkan, blank, blank_coverage, blank_ramp, @@ -457,17 +467,29 @@ impl GpuRenderer { let off = d.map_or("a wrong size".to_string(), |d| format!("{} of {} pixels off, by up to {}/255{at}", d.differing, d.pixels, d.max)); Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong {how} ({off})", self.adapter))) }; - check("read back", &self.render(&dl, &view, Output::Premul8)?.premul8)?; - let t = self.render_texture(&dl, &view)?; + check("read back", &self.render_with(&dl, &view, Output::Premul8, Binning::Cpu)?.premul8)?; + let t = self.render_texture_with(&dl, &view, Binning::Cpu)?; check("through a texture", &self.read_texture(&t)?)?; - // And binned on the GPU (the plain fills; the bitmap and the symbol stay on the CPU's). + // Binned on the GPU (the plain fills; the bitmap and the symbol bin on the CPU): if that + // comes back wrong, only the binning stays on the CPU here. let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; - let got = self.render_with(&plain, &view, Output::Premul8, Binning::Gpu)?; - match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { - Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => Ok(()), - d => Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong binned on the GPU ({d:?})", self.adapter))), - } + let why = match self.render_with(&plain, &view, Output::Premul8, Binning::Gpu) { + Ok(got) => match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { + Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => None, + Some(d) if got.gpu_binned => Some(format!("{} of {} pixels off, by up to {}/255", d.differing, d.pixels, d.max)), + _ => Some("it wasn't binned on the GPU".to_string()), + }, + Err(GpuError::Device(e)) => return Err(GpuError::Unavailable(format!("{}: the GPU binning failed: {e}", self.adapter))), + Err(e) => Some(e.to_string()), + }; + *self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner) = why.map(|w| format!("{}: the self-test came back wrong binned on the GPU ({w}); binning on the CPU", self.adapter)); + Ok(()) + } + + /// Why the GPU doesn't bin on this device, if it doesn't (for Preferences and reports). + pub fn gpu_binning_off(&self) -> Option { + self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).clone() } /// Where frames' edges are sorted into tiles from now on. @@ -620,8 +642,11 @@ impl GpuRenderer { fn plan(&self, dl: &DisplayList, view: &View, depth: usize, binning: Binning, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { let (mut scene, stats) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; let t = Instant::now(); + let off = self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).is_some(); let lim = match binning { + _ if off => None, Binning::Cpu => None, + Binning::Auto if !self.auto_bins => None, Binning::Auto => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: AUTO_MIN_EDGES }), Binning::Gpu => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }), }; diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0bbb4730..1f11e14e 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1053,6 +1053,8 @@ fn gpu_binning_produces_the_cpus_tile_lists() { #[test] fn gpu_binned_frames_match_the_oracle() { let Some(g) = gpu() else { return }; + // Where the GPU stage runs (lavapipe in CI included), its binning must too. + assert_eq!(g.gpu_binning_off(), None); for (name, dl, v) in gpu_binned_scenes() { let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); assert!(f.gpu_binned, "{name}"); From 340512ef4fe387a3317d31f6ab43a0df6c5492e7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:23:52 -0700 Subject: [PATCH 025/402] docs: ADR 0048 GPU binning and hairlines, performance, roadmap, changelog, attribution (M3) --- ATTRIBUTION.md | 4 +- CHANGELOG.md | 17 ++ docs/adr/0048-gpu-binning-and-hairlines.md | 179 +++++++++++++++++++++ docs/adr/README.md | 1 - docs/architecture.md | 17 +- docs/performance.md | 60 ++++++- docs/roadmap.md | 6 +- 7 files changed, 270 insertions(+), 14 deletions(-) create mode 100644 docs/adr/0048-gpu-binning-and-hairlines.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 0ee9d2b8..241beff1 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -78,7 +78,9 @@ OR Apache-2.0) is noted in the table. | Technique | Where | Reference | Notes | |---|---|---|---| | Signed-area coverage accumulation rasterizer | `crates/render/src/raster.rs` | Raph Levien, *font-rs* (2016), , Apache-2.0; also stb_truetype v2 (public domain) | Our implementation follows the published accumulate-and-prefix-sum approach. Credited here; Apache-2.0 includes a patent licence. | -| Tile binning with per-row backdrops; per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019). | +| Tile binning with integer backdrops and left-edge steps ("y-edges"); per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019, ADR 0048). | +| 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. | | 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 | | diff --git a/CHANGELOG.md b/CHANGELOG.md index 19a9b140..2543557a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +* **The GPU stage sorts heavy frames into tiles on the graphics card, and outlines are cheap** + (ADR 0048, M3). + * Frames with many shapes are binned on the GPU (count, prefix sum, scatter and tile-list + compute passes) instead of on the CPU: the CPU only lays out the shapes' points, and every + buffer is sized up front, so nothing is read back. On Vulkan, a 10,000-shape 4K frame + drawn as one texture takes about 5 ms instead of 22, a 50,000-shape one about 23 ms + instead of 122, and the 50,000-shape 4K stage about 37 ms instead of 75. Frames with few + shapes, shapes inside masks or faded symbols, and Direct3D 12 (where the passes cost more + per stage tile) are still binned on the CPU, which stays the reference + (`ANICRAFT_GPU_BINNING=cpu|gpu|auto` to compare). + * **Outline mode** (an outlined layer, and onion skin's Outlines) draws true one-pixel + hairlines, one edge per segment where the old half-pixel strokes had four and a disc at + every bend, in the CPU renderer and on the GPU alike. On a 2,000-shape scene with ±5 onion + frames, outlines are now as fast as tinted onion frames: 10 ms on the GPU stage at 1080p + (was 73) and 17 ms on the CPU stage (was 34–39). Lines look the same, with smoother joins. + * Parity with the CPU renderer is unchanged (at most 1/255 on every test scene), and a test + checks that the GPU's tile lists are the CPU's, entry by entry and pixel by pixel. * **Motion path points pinned to frames** (ADR 0049, M2). As in Animate, a motion tween's position keyframes are now points on its path: move the object at a frame and the path gets a point there that the object passes exactly on that frame, whatever else you do to the path. diff --git a/docs/adr/0048-gpu-binning-and-hairlines.md b/docs/adr/0048-gpu-binning-and-hairlines.md new file mode 100644 index 00000000..9cf75094 --- /dev/null +++ b/docs/adr/0048-gpu-binning-and-hairlines.md @@ -0,0 +1,179 @@ +# ADR 0048: GPU stage, fourth slice: tile binning on the GPU, and hairlines + +* Status: accepted (2026-11-10) +* Relates to: roadmap M3, ADR 0019 (GPU stage), ADR 0029 (no readback, masks and groups; binning + kept on the CPU), ADR 0032 (bitmaps, filters, the default), ADR 0047 (onion skin outlines), + ADR 0002 (the oracle's coverage), AGENTS.md rule 4 (the CPU renderer is the oracle) + +## Context + +Two costs were left in the GPU stage: + +* **Binning on the CPU.** The CPU split every prepared edge into 16 × 16 tile pieces, summed + 16 floats of backdrop per tile, and uploaded it all. ADR 0029 kept it there because stage tiles + spread it over every core; it was still the largest term of a heavy frame (10k shapes: 4.0 ms + of 8.8 at 1080p, 10.6 of 16.7 at 4K; 50k shapes: 17–76 ms) and grew with every shape. +* **Outlines.** Outline mode (an outlined layer, and onion skin's Outlines, ADR 0047) drew each + item as a stroke of half a pixel: four edges per segment and a hexagon at every bend, all + overlapping, so an outlined item had 5–10× the edges of its fill. On the 2,000-item stress + scene with ±5 onion frames, outlines took 34–39 ms on the CPU stage against 16–17 tinted, and + 73 ms against 12.6 on the GPU stage. + +## Decision + +### 1. One tile format the GPU can compute: integer backdrops and left-edge steps + +The per-row float backdrop (the winding of everything left of a tile, per pixel row) needed a +float sum in a fixed order; on the GPU that means float atomics (which WGSL doesn't have) or +serial work. The binning now describes the same winding as **Vello's tiles do** (its public +design notes: a backdrop and "y-edges"): + +* **Backdrop:** one integer per tile, the winding number just below its top-left corner. It is + the sum of the directions of the pieces further left in the tile row that start on the row's + top edge (exactly the edges crossing it). +* **Left-edge steps:** where the outline passes from one tile column to another inside a row + (consecutive pieces in different columns), each tile boundary between them gets one more + piece, a vertical line on that tile's left edge from the crossing down to the row's bottom: + upwards where the outline runs right (the winding left of the tile drops by one), downwards + where it runs left. The fine shader treats it like any piece, so its coverage formula is + unchanged. + +Both come **from the split pieces themselves**, so they can never disagree. A first version +computed the crossings geometrically, apart from the split; near a tile corner a rounding +could count one crossing twice, which a stress frame showed (543 pixels off by up to 133/255). +A test on stress frames at awkward scales now catches it. + +Integers add up the same in any order, the CPU binning (the reference) and the GPU produce the +same lists, and the CPU's own binning got smaller (no 64-byte backdrops). + +### 2. Binning on the GPU + +The CPU lays out only what is proportional to the fills and their points (`gpu_binning.rs`): + +* the prepared polygons' points, one flat buffer, and each fill's tile range; +* one GPU invocation per **row of tiles of each fill** (an op-row), with room for each tile of + each fill's bounds (an op-tile); +* per tile row, the fills overlapping it in drawing order (from their bounds), and per tile + room for every fill whose bounds cover it (a 2D running sum over the bounds' corners); +* an **upper bound of the pieces** per edge (its rows, twice its columns, slack), so every + buffer is sized before the GPU runs and **nothing is read back**. + +`bin.wgsl` then runs, in one compute pass: + +1. `count`: each op-row walks its fill's edges, splits the ones in its row (the CPU's + `split_edge`/`split_row`, line for line), adds the left-edge steps, and counts pieces per + op-tile; the backdrop deltas are summed along the row. An op-row belongs to one invocation, + so **no atomics**: counts and backdrops are exact. +2. `scan_blocks`/`scan_add` (`scan.wgsl`): an exclusive prefix sum of the counts (the public + work-efficient scan, Blelloch 1990: per workgroup, then the workgroups' totals, added back). +3. `scatter`: the same walk, writing each piece at its op-tile's place, in walk order (the + same every frame). +4. `tiles`: one invocation per tile walks its row's fills in drawing order and keeps those + with pieces or a backdrop there, as the entries the fine pass reads. + +This is the count, prefix-sum and scatter structure of Vello's and Pathfinder's binning stages +(public descriptions; no code or shaders copied), arranged per op-row instead of per segment +so that it needs no atomics and is deterministic. The binding layout uses four storage buffers +per stage, the smallest any device offers. + +**Scope.** Fills inside a mask or a group still bin on the CPU: their tile streams carry clip +and group control entries whose number depends on which fills reach each tile, which needs +either a CPU pass over the candidates or a GPU stream pass with counted room. That is the next +step. The CPU binning stays the reference and this fallback. + +**When.** `Binning::Auto` (the default) bins on the GPU when the scene can take it, has at +least 32,768 edges and the device runs Vulkan (below, Direct3D 12 measured slower in stage +tiles; other backends aren't measured yet). Below that many edges the CPU bins a stage tile faster than the GPU's passes set up +(measured: forcing the GPU on every 512 px tile made the 1,000-shape 4K stage 1.9× slower, and +the 10k-shape one 1.3× slower). `ANICRAFT_GPU_BINNING=cpu|gpu|auto` overrides it for +comparisons; `render_with`/`render_texture_with` take it per call (tests, the bench). The +start-up self-test also renders its rectangles binned on the GPU; if that comes back wrong, +only the binning stays on the CPU on that device (`gpu_binning_off` says why), and the tests +require it to work wherever the GPU stage runs (lavapipe in CI included). + +Limits: at most `MAX_VISITS` (2²⁶) edge visits by the per-row passes (a fill with very many +edges over very many rows bins on the CPU, which splits each edge once), and every buffer +within the device's binding size; otherwise the CPU bins. The work bound (`MAX_WORK`) counts +the room made, an upper bound. + +### 3. Hairlines in both renderers + +Outline mode draws **hairlines**: the oracle's prepared fill carries the flattened polylines +(closed ones repeat their first point) and `Fill::hairline`. A pixel's coverage is +`1 − d`, clamped, where `d` is the distance from its centre to the nearest segment +(`render::hairline`). That is exactly the area a one-pixel line covers for horizontal and +vertical lines (a line through pixel centres covers them fully, one on a boundary half each +side), a tent-filtered line in other directions (diagonals look up to about 12 % heavier), +with round ends and joins and no darkening where segments overlap. Each segment is one piece +to bin and test, where the stroked hairline was four plus a disc at every bend. + +* The oracle computes it per segment over the rows and columns within reach (a direct-coverage + mode of its accumulation buffer); the GPU's fine shader takes the nearest of the tile's + segments (with a cheap box reject first) by the same steps (`seg_dist`). +* The binning puts each segment, whole, into every tile with a pixel centre within reach + (conservatively: two pixels around it); no backdrops. +* This changes the oracle's outline mode slightly (anti-aliasing of 1 px lines); it is an + editing aid, never exported (vector exports draw outlines as their own strokes), and the + engine's tests and goldens are unchanged. + +Not hairlines (yet): strokes thinner than a pixel. They keep a one-pixel stroke polygon faded +by their width; drawing them as hairlines would change exported pictures and the XFL goldens, +which is its own decision. + +## Measured (2026-11-10, release, RTX 5090, 32 threads, a machine shared with other builds) + +`cargo run --release -p anicraft-gpu --example gpu_bench`: *direct* is what the calling thread +spends with `render_texture` (prepare + bin + upload and submit), *tiled* is the stage's way +(512 px tiles in parallel until the GPU has finished). Before: binned on the CPU; after: as +`Binning::Auto` bins (the GPU from 32,768 edges, on Vulkan). Best of three runs, Vulkan. + +| Scene | Size | CPU oracle | Before: direct / tiled | After, binned on the CPU: direct / tiled | After, Auto: direct / tiled | Parity (mean / max, 1/255) | +|---|---|---|---|---|---|---| +| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 9.8 ms | 9.0 / 7.4 ms | 8.6 / 5.5 ms | **3.9** / 5.5 ms | < 0.0001 / 1 | +| Stress, 50 × 200 | 3840×2160 | 25.9 ms | 21.7 / 10.9 ms | 16.4 / 10.1 ms | **4.7** / 10.1 ms | < 0.0001 / 1 | +| 1,000 shapes (binned on the CPU: few edges) | 3840×2160 | 16.9 ms | 2.2 / 4.5 ms | 1.6 / 4.2 ms | 1.7 / 4.5 ms | < 0.0001 / 1 | +| 50,000 shapes (250 × 200) | 1920×1080 | 31.7 ms | 52.2 / 32.4 ms | 33.5 / 26.8 ms | **17.7** / 24.8 ms | < 0.0001 / 1 | +| 50,000 shapes | 3840×2160 | 73.1 ms | 122.1 / 75.3 ms | 103.9 / 61.5 ms | **22.5** / **36.7** ms | < 0.0001 / 1 | +| Masked stress (binned on the CPU: masks) | 3840×2160 | 72.4 ms | 13.8 / 12.3 ms | 12.0 / 10.7 ms | 11.3 / 10.5 ms | < 0.0001 / 1 | +| Onion skin off (stress 20 × 100) | 1920×1080 | 5.0 ms | 2.1 / 2.7 ms | 1.8 / 2.2 ms | 1.1 / 2.3 ms | < 0.0001 / 1 | +| Onion ±5, tinted (22,000 items) | 1920×1080 | 15.1 ms | 15.7 / 12.6 ms | 12.8 / 10.5 ms | 7.1 / 9.8 ms | < 0.0001 / 1 | +| Onion ±5, tinted | 3840×2160 | 37.3 ms | 32.1 / 25.1 ms | 20.3 / 22.0 ms | 8.5 / 16.5 ms | 0.0001 / 1 | +| Onion ±5, **outlines** | 1920×1080 | 20.0 ms (was 36.0) | 74.7 / 73.0 ms | 12.9 / 10.4 ms | 7.3 / **10.1** ms | < 0.0001 / 1 | +| Onion ±5, **outlines** | 3840×2160 | 37.9 ms (was 60.2) | 135.4 / 95.4 ms | 20.3 / 18.1 ms | 8.6 / **15.3** ms | < 0.0001 / 1 | + +*Before* is `main` before this slice (CPU binning with float backdrops, stroked hairlines), +measured the same day on the same machine. In stage tiles the GPU binning wins once frames are +heavy (50k shapes: 61.5 → 36.7 ms at 4K) and never loses below `AUTO_MIN_EDGES`; a whole frame +in one texture gains most (10k shapes at 4K: 16.4 → 4.7 ms). **Outline mode is as fast as +tinted onion skin** on the GPU stage: 10.1 vs 9.8 ms at 1080p in tiles, 15.3 vs 16.5 ms at 4K, +7.3 vs 7.1 ms in one texture (it was 73 vs 12.6 ms in tiles). + +On **Direct3D 12** (same card, `WGPU_BACKEND=dx12`, two runs) the GPU binning still wins in +one texture (10k shapes at 4K: 17.5 → 6.3 ms; 50k: 154 → 30 ms) but loses in stage tiles +(onion ±5 at 1080p: 9.7 → 14.4 ms tinted, 10.0 → 15.4 ms outlines; the passes cost more per +dispatch there, as ADR 0032 saw for the fine pass), so `Binning::Auto` bins on the GPU on +Vulkan only. With CPU binning, DX12's onion outlines take 10.1 ms in tiles against 10.0 tinted. + +The CPU stage (the oracle through the render service's 256 px tiles, `onion_timings`, best of +frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14.8 tinted at +1080p (was 34–39 against 16.2–17.2). + +## Not in this slice + +* GPU binning for fills inside masks and groups (their tile streams, ADR 0029). +* Flattening and stroking on the GPU (preparation is now the largest CPU term of a heavy + frame: 8–9 ms of 50k shapes). +* Fewer, larger dispatches for the stage's tiles (each 512 px tile is its own submission, so the + binning passes' set-up repeats per tile). +* Hairlines for strokes thinner than a pixel (above). +* Guide lines and selection outlines: the stage never renders guides, and selection outlines + are drawn by the shell's painter, not the stage renderer. + +## Consequences + +* The tile format is one integer backdrop per tile plus left-edge steps, on the CPU and the GPU + alike; `Binned` carries the op headers apart (`op_heads`) and, when the GPU bins, the plan. +* A test compares the GPU's tile lists with the CPU's, tile by tile, entry by entry and pixel + by pixel, on stress frames, outlined onion frames and the analytic scenes; GPU-binned frames + are checked against the oracle read back and through a texture; on Vulkan and Direct3D 12. +* `gpu_bench --check` enforces the GPU stage's timing budgets (docs/performance.md). diff --git a/docs/adr/README.md b/docs/adr/README.md index f974a6d8..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 | -| 0048 | m3/gpu-binning | GPU stage, fourth slice: tile binning on the GPU, cheap outlines | diff --git a/docs/architecture.md b/docs/architecture.md index 5f1cad2d..9c8a78b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,7 +36,7 @@ app/ workspace root; the root package is the desktop app doc L1 Document model + timeline evaluation (keyframes, tweens, easing, symbols) + player render L2 CPU oracle rasterizer, paints/gradients, compositor, PNG encode engine L3 Session (document + history + selection + playhead), command registry, file format - gpu L3 wgpu stage renderer over the oracle's prepared fills (ADR 0019, 0029, 0031; shell feature `gpu-stage`, on by default) + gpu L3 wgpu stage renderer over the oracle's prepared fills (ADR 0019, 0029, 0032, 0048; shell feature `gpu-stage`, on by default) cli L4 `anicraft-cli`: info / render / render-seq / commands / run / serve (JSON-lines) src/ L5 egui shell: menus (from registry), tools, stage, timeline, properties, library docs/ requirements, architecture, roadmap @@ -185,11 +185,16 @@ DisplayList ──► for each item: Output is bit-identical to serial. Numbers are in [performance.md](performance.md). **GPU stage** ([ADR 0019](adr/0019-gpu-stage.md), [ADR 0029](adr/0029-gpu-stage-direct-masks-groups.md), -[ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md); the shell's `gpu-stage` feature, on -by default, and the default stage renderer): `render::prepare_scene` hands the oracle's own -prepared fills, with their clips, groups, bitmap shaders and filtered layers, to `anicraft-gpu`, which bins edge pieces into -16 × 16 tiles with per-row backdrops (CPU, parallel) and writes each tile's stream of entries -in drawing order, with clip-coverage and group open/close entries. One compute pass computes +[ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md), [ADR 0048](adr/0048-gpu-binning-and-hairlines.md); +the shell's `gpu-stage` feature, on by default, and the default stage renderer): +`render::prepare_scene` hands the oracle's own prepared fills, with their clips, groups, bitmap +shaders and filtered layers, to `anicraft-gpu`, which bins edge pieces into 16 × 16 tiles with +an integer backdrop per tile and steps on the tiles' left edges, and writes each tile's stream +of entries in drawing order. Heavy scenes without masks or groups are binned on the GPU (count, +prefix sum, scatter and tile-list passes; the CPU only lays out the points and the fills' +ranges, and sizes every buffer up front, so nothing is read back); the rest, with their +clip-coverage and group open/close entries, on the CPU, which is also the reference. Outline +mode's hairlines are one piece per segment, covered by distance in both renderers. One compute pass computes each pixel's exact area coverage and composites it as the oracle's band compositor does (clip coverage, a per-pixel group stack, the W3C blend modes). On the window's wgpu device it draws each stage tile into a texture egui shows as it is (no readback); otherwise on a headless diff --git a/docs/performance.md b/docs/performance.md index f10e5bb3..e034b22c 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -37,6 +37,11 @@ The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k elemen | UI frame while rendering | never blocked | worker thread ✅ | design (ADR 0002) | | Autosave: time on the editing thread | < 1 ms | 7–15 µs ✅ | `bench --check` | | Autosave of the 65 MB file, in the background | < 2 s | 183–184 ms ✅ | `bench --check` | +| GPU stage, 1,000 shapes at 4K, stage tiles (M3 exit) | < 16.7 ms | 4.5–4.7 ms ✅ (2026-11-10, RTX 5090) | `gpu_bench --check` | +| GPU stage, 10k shapes at 4K, stage tiles | < 16.7 ms | 10.1–10.4 ms ✅ | `gpu_bench --check` | +| GPU stage, 50k shapes at 1080p, stage tiles | < 33.3 ms (30 fps) | 24.8–26.3 ms ✅ | `gpu_bench --check` | +| GPU stage, 50k shapes at 4K, one texture | < 33.3 ms | 22.5–23.8 ms ✅ | `gpu_bench --check` | +| GPU stage, onion ±5 outlines / tinted at 1080p, stage tiles | ≤ 1.25 | 1.03–1.06 ✅ | `gpu_bench --check` | **1080p render, back under budget (2026-11-06).** It had drifted to 19.4–20.2 ms (v0.1.0 measured 18.0–18.9 ms on the same machine; the 16.5 ms of 2026-10-28 didn't reproduce). @@ -68,8 +73,16 @@ order (an append, then a reorder). One k-way merge by layer, each item moved onc to 0.85 ms, and evaluating the extra frames in parallel brought the whole to 3.0–3.3 ms. Output is unchanged (the onion tests compare items and pixels). The settings are part of every tile's key, so the frame cache keeps working: looking at the same frame again is 40 hits in 0.02 ms, -and other settings are other pictures. Hairline outlines cost more to rasterize than fills, so -outline mode on very heavy scenes is the slow case. +and other settings are other pictures. + +**Outlines as hairlines (2026-11-10, ADR 0048).** Outline mode drew half-pixel strokes (four +edges per segment and a disc at every bend); it now draws hairlines, one edge per segment, +covered by distance. Same test, same machine: + +| Scene | Off | ±5 tinted, fading | ±5 outlines | Keyframes only ±5 | Edit Multiple Frames ±5 | +|---|---|---|---|---|---| +| Sample | 5.7 ms | 5.9 ms | 5.5 ms | 5.9 ms | 5.7 ms | +| Stress 20 × 100 | 7.6 ms | 14.8 ms | **17.1 ms** (was 34–39) | 7.3 ms | 7.2 ms | **Crash-recovery autosave (2026-11-09, ADR 0015).** `bench` now runs one autosave the way the app does: an `Autosaver` in a scratch recovery folder. The editing thread only hands over an @@ -147,6 +160,44 @@ layer across a frame's tiles is next. The one large difference is a single pixel falls within float rounding of a non-repeating bitmap's edge (ADR 0032). Bitmaps are uploaded once per image and cached (256 MB budget), so after the first frame they cost no transfer. +### GPU stage, fourth slice: binning on the GPU, hairlines (M3, ADR 0048) + +`cargo run --release -p anicraft-gpu --example gpu_bench` (2026-11-10, RTX 5090 over Vulkan, +32 threads, a machine shared with other builds: best of three runs). *Direct* is the calling +thread's time with `render_texture`, *tiled* the stage's way (512 px tiles in parallel until +the GPU has finished). + +| Scene | Size | CPU oracle | Before: direct / tiled | After, binned on the CPU: direct / tiled | After, Auto: direct / tiled | Parity (mean / max, 1/255) | +|---|---|---|---|---|---|---| +| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 9.8 ms | 9.0 / 7.4 ms | 8.6 / 5.5 ms | **3.9** / 5.5 ms | < 0.0001 / 1 | +| Stress, 50 × 200 | 3840×2160 | 25.9 ms | 21.7 / 10.9 ms | 16.4 / 10.1 ms | **4.7** / 10.1 ms | < 0.0001 / 1 | +| 1,000 shapes (binned on the CPU: few edges) | 3840×2160 | 16.9 ms | 2.2 / 4.5 ms | 1.6 / 4.2 ms | 1.7 / 4.5 ms | < 0.0001 / 1 | +| 50,000 shapes (250 × 200) | 1920×1080 | 31.7 ms | 52.2 / 32.4 ms | 33.5 / 26.8 ms | **17.7** / 24.8 ms | < 0.0001 / 1 | +| 50,000 shapes | 3840×2160 | 73.1 ms | 122.1 / 75.3 ms | 103.9 / 61.5 ms | **22.5** / **36.7** ms | < 0.0001 / 1 | +| Masked stress (binned on the CPU: masks) | 3840×2160 | 72.4 ms | 13.8 / 12.3 ms | 12.0 / 10.7 ms | 11.3 / 10.5 ms | < 0.0001 / 1 | +| Onion skin off (stress 20 × 100) | 1920×1080 | 5.0 ms | 2.1 / 2.7 ms | 1.8 / 2.2 ms | 1.1 / 2.3 ms | < 0.0001 / 1 | +| Onion ±5, tinted (22,000 items) | 1920×1080 | 15.1 ms | 15.7 / 12.6 ms | 12.8 / 10.5 ms | 7.1 / 9.8 ms | < 0.0001 / 1 | +| Onion ±5, tinted | 3840×2160 | 37.3 ms | 32.1 / 25.1 ms | 20.3 / 22.0 ms | 8.5 / 16.5 ms | 0.0001 / 1 | +| Onion ±5, **outlines** | 1920×1080 | 20.0 ms (was 36.0) | 74.7 / 73.0 ms | 12.9 / 10.4 ms | 7.3 / **10.1** ms | < 0.0001 / 1 | +| Onion ±5, **outlines** | 3840×2160 | 37.9 ms (was 60.2) | 135.4 / 95.4 ms | 20.3 / 18.1 ms | 8.6 / **15.3** ms | < 0.0001 / 1 | + +*Before* is `main` before this slice (CPU binning with float backdrops, stroked hairlines), +measured the same day on the same machine. In stage tiles the GPU binning wins once frames are +heavy (50k shapes: 61.5 → 36.7 ms at 4K) and never loses below `AUTO_MIN_EDGES`; a whole frame +in one texture gains most (10k shapes at 4K: 16.4 → 4.7 ms). **Outline mode is as fast as +tinted onion skin** on the GPU stage: 10.1 vs 9.8 ms at 1080p in tiles, 15.3 vs 16.5 ms at 4K, +7.3 vs 7.1 ms in one texture (it was 73 vs 12.6 ms in tiles). + +On **Direct3D 12** (same card, `WGPU_BACKEND=dx12`, two runs) the GPU binning still wins in +one texture (10k shapes at 4K: 17.5 → 6.3 ms; 50k: 154 → 30 ms) but loses in stage tiles +(onion ±5 at 1080p: 9.7 → 14.4 ms tinted, 10.0 → 15.4 ms outlines; the passes cost more per +dispatch there, as ADR 0032 saw for the fine pass), so `Binning::Auto` bins on the GPU on +Vulkan only. With CPU binning, DX12's onion outlines take 10.1 ms in tiles against 10.0 tinted. + +The CPU stage (the oracle through the render service's 256 px tiles, `onion_timings`, best of +frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14.8 tinted at +1080p (was 34–39 against 16.2–17.2). + ### How budgets are enforced * **Budgets that don't depend on the machine** (undo memory, snapshot sharing, file size, @@ -158,7 +209,8 @@ once per image and cached (256 MB budget), so after the first frame they cost no machine before a release and after performance work. A dedicated benchmark runner would let CI run it too. * The limits live in `TIME_BUDGETS` in `crates/cli/src/lib.rs`; keep that list and this - table in step. + table in step. The GPU stage's are `BUDGETS` in `crates/gpu/examples/gpu_bench.rs` + (`--check`; the CLI has no GPU). ## Sound (2026-11-09, ADR 0020) @@ -187,3 +239,5 @@ buffer is tiny; the stage never waits on sound. groups on the GPU, binning kept on the CPU * [ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md): bitmaps and filters on the GPU, Direct3D 12, and the GPU as the default stage renderer +* [ADR 0048](adr/0048-gpu-binning-and-hairlines.md): tile binning on the GPU, one tile format + for both binnings, and hairlines for outline mode diff --git a/docs/roadmap.md b/docs/roadmap.md index 87d4fec4..d5c8d175 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,7 +9,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Dimension | Status | |---|---| | 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). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | +| 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`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **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: a marquee across several layers, snapping while drawing, width profiles in the merge, deleting or adding raw anchors, smooth handle pairs. **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. | @@ -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); ~~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); ~~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 deferred (not the bottleneck as tiles); ~~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: shared filtered layers across tiles, an image atlas, GPU exports. | +| **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); not yet: `.fla` variants of the corpus, sound and video items; ~~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. | @@ -54,7 +54,7 @@ titled with its milestone. | Track | Next task | Depends on (all done) | |---|---|---| | M2 | Motion tweens with property curves and the Motion Editor | timeline evaluation, classic tweens | -| M3 | GPU stage: 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) | CPU oracle, tiled stage, GPU stage slices 1–3 | +| 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 | From a6df58e30da59d6c4d744dd22bc42425cacbb4f2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:40:02 -0700 Subject: [PATCH 026/402] fix(gpu): as_chunks_mut for the input layout (newer clippy) (M3) --- crates/gpu/src/gpu_binning.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs index 31cc3dcb..3212934a 100644 --- a/crates/gpu/src/gpu_binning.rs +++ b/crates/gpu/src/gpu_binning.rs @@ -209,11 +209,11 @@ pub fn plan(fills: &[Fill], tiles_x: u32, tiles_y: u32, lim: &Limits) -> Option< let flags = if f.hairline { HAIRLINE_BIT } else { 0 }; h.copy_from_slice(&[p0, i.polys, tx0, ty0, ncols, nrows, t0, flags]); let mut q = q0; - for (slot, poly) in pw.chunks_exact_mut(2).zip(&f.polys) { + for (slot, poly) in pw.as_chunks_mut::<2>().0.iter_mut().zip(&f.polys) { slot.copy_from_slice(&[q, poly.len() as u32]); q += poly.len() as u32; } - for (slot, p) in qw.chunks_exact_mut(2).zip(f.polys.iter().flatten()) { + for (slot, p) in qw.as_chunks_mut::<2>().0.iter_mut().zip(f.polys.iter().flatten()) { slot.copy_from_slice(&[p.x.to_bits(), p.y.to_bits()]); } }); From ac9a6ac351ec297eadc60bb7bed5b9512143fda8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:27:38 -0700 Subject: [PATCH 027/402] docs(adr): reserve ADR 0050 for library management (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..0390bd99 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 | +| 0050 | m2/library-management | Library folders, item management and Swap Symbol | From eb1037a6daedda5a1191fb3e320b018723c641a8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:31:17 -0700 Subject: [PATCH 028/402] feat(doc): Library folders, item placement, unique names, use counts and unused items (M2) --- crates/doc/src/bitmap.rs | 16 +- crates/doc/src/lib.rs | 18 +- crates/doc/src/library.rs | 523 ++++++++++++++++++++++++++++++++ crates/doc/src/library_tests.rs | 195 ++++++++++++ crates/doc/src/sample.rs | 6 +- crates/engine/src/history.rs | 2 +- 6 files changed, 751 insertions(+), 9 deletions(-) create mode 100644 crates/doc/src/library.rs create mode 100644 crates/doc/src/library_tests.rs diff --git a/crates/doc/src/bitmap.rs b/crates/doc/src/bitmap.rs index 0ec3c6ff..196de0bd 100644 --- a/crates/doc/src/bitmap.rs +++ b/crates/doc/src/bitmap.rs @@ -43,13 +43,25 @@ pub struct Bitmap { /// The image as PNG. #[serde(with = "base64_bytes")] pub png: Arc>, + /// Allow Smoothing (ADR 0050): scaled or turned, the image is filtered between its pixels; + /// off, each pixel stays a hard-edged square (pixel art). On unless a file says otherwise. + #[serde(default = "yes", skip_serializing_if = "is_yes")] + pub smoothing: bool, #[serde(skip)] decoded: Arc>>>, } +fn yes() -> bool { + true +} + +fn is_yes(b: &bool) -> bool { + *b +} + impl PartialEq for Bitmap { fn eq(&self, o: &Bitmap) -> bool { - self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png) + self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && self.smoothing == o.smoothing && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png) } } @@ -60,7 +72,7 @@ impl Bitmap { let (width, height) = (px.width, px.height); let decoded = OnceLock::new(); let _ = decoded.set(Some(Arc::new(px))); - Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), decoded: Arc::new(decoded) }) + Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), smoothing: true, decoded: Arc::new(decoded) }) } /// A bitmap from PNG or JPEG data (told apart by their signatures; JPEGs become PNG). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 086e9914..734961ac 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 library; pub mod motion; pub mod path_table; pub mod width; @@ -26,6 +27,7 @@ pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; pub use easing::Easing; 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 sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; @@ -1095,6 +1097,9 @@ pub struct Document { /// Sounds in the library, placed on keyframes through [`FrameSound`]. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sounds: Vec>, + /// The Library's folders and which folder each item is in (ADR 0050). + #[serde(default, skip_serializing_if = "library_tree_is_empty")] + pub library_tree: Arc, /// The class scripts run the main timeline as (Animate's "document class"), kept as text /// (ADR 0013 tier 1); empty when there is none. #[serde(default, skip_serializing_if = "String::is_empty")] @@ -1119,6 +1124,8 @@ struct DocumentFile { #[serde(default)] sounds: Vec>, #[serde(default)] + library_tree: Arc, + #[serde(default)] document_class: String, #[serde(default = "first_id")] next_id: u64, @@ -1130,7 +1137,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, 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, next_id: f.next_id } } } @@ -1138,18 +1145,22 @@ fn first_id() -> u64 { 1 } +fn library_tree_is_empty(t: &Arc) -> bool { + t.is_empty() +} + /// 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) + 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) } } 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(), 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(), next_id: 1 }; let id = LayerId(d.alloc_id()); d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1"))); d @@ -1280,6 +1291,7 @@ impl Document { for s in &self.sounds { max_id = max_id.max(s.id.0); } + self.sanitize_library_tree(&mut max_id); self.next_id = self.next_id.max(max_id.saturating_add(1)); } } diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs new file mode 100644 index 00000000..6d5f6b6e --- /dev/null +++ b/crates/doc/src/library.rs @@ -0,0 +1,523 @@ +//! How the Library is organised (ADR 0050): folders, the folder each item is in, names unique +//! within a folder, how often each item is used, and which items nothing reaches. +//! +//! The organisation is kept apart from the items themselves ([`Document::library_tree`]): moving +//! or renaming a folder touches one small table, never a symbol's timeline, and documents from +//! before folders open with every item at the top level. + +use crate::{BitmapId, Document, ElementId, ElementKind, LayerId, Paint, SoundId, Symbol, SymbolId, Timeline}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::Arc; + +/// Unique id of a Library folder (from the document's id counter). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct FolderId(pub u64); + +/// A symbol, bitmap or sound in the Library. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum LibraryItem { + Symbol(SymbolId), + Bitmap(BitmapId), + Sound(SoundId), +} + +impl LibraryItem { + /// The id inside, whatever the kind (ids are unique across kinds within a document). + pub fn raw(self) -> u64 { + match self { + LibraryItem::Symbol(i) => i.0, + LibraryItem::Bitmap(i) => i.0, + LibraryItem::Sound(i) => i.0, + } + } +} + +/// One row of the Library: an item or a folder. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum LibraryEntry { + Item(LibraryItem), + Folder(FolderId), +} + +/// A Library folder. Folders nest; `parent` is `None` at the top level. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LibraryFolder { + pub id: FolderId, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, +} + +/// The Library's folders and where each item is. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct LibraryTree { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub folders: Vec, + /// The folder each item is in. An item not listed is at the top level. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty", with = "placed_list")] + pub placed: BTreeMap, +} + +impl LibraryTree { + pub fn is_empty(&self) -> bool { + self.folders.is_empty() && self.placed.is_empty() + } +} + +/// `placed` as a list of `{"symbol": 3, "folder": 7}` (JSON object keys must be strings). +mod placed_list { + use super::{FolderId, LibraryItem}; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use std::collections::BTreeMap; + + #[derive(Serialize, Deserialize)] + struct Placed { + #[serde(flatten)] + item: LibraryItem, + folder: FolderId, + } + + pub fn serialize(m: &BTreeMap, s: S) -> Result { + s.collect_seq(m.iter().map(|(item, folder)| Placed { item: *item, folder: *folder })) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let v: Vec = Vec::deserialize(d)?; + Ok(v.into_iter().map(|p| (p.item, p.folder)).collect()) + } +} + +/// Most folders in a Library. +pub const MAX_FOLDERS: usize = 10_000; +/// Deepest folder nesting (a top-level folder is at depth 1). +pub const MAX_FOLDER_DEPTH: usize = 32; +/// Longest Library name (characters). +pub const MAX_NAME_CHARS: usize = 256; + +/// Why a name can't be used for a Library item or folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NameError { + Empty, + TooLong, + /// `/` separates folders in a path (`Characters/Ball`). + Slash, + /// The folder already holds an item or folder of that name (case aside). + Taken(String), +} + +impl std::fmt::Display for NameError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + NameError::Empty => write!(f, "a Library name can't be empty"), + NameError::TooLong => write!(f, "a Library name is at most {MAX_NAME_CHARS} characters"), + NameError::Slash => write!(f, "a Library name can't contain “/” (it separates folders)"), + NameError::Taken(n) => write!(f, "this folder already has an item named “{n}”"), + } + } +} + +/// Library names compare without case, as in Animate. +fn same_name(a: &str, b: &str) -> bool { + a == b || a.to_lowercase() == b.to_lowercase() +} + +/// A name trimmed and checked for the Library's rules (not for clashes). +pub fn clean_name(name: &str) -> Result { + let n = name.trim(); + if n.is_empty() { + return Err(NameError::Empty); + } + if n.chars().count() > MAX_NAME_CHARS { + return Err(NameError::TooLong); + } + if n.contains('/') { + return Err(NameError::Slash); + } + Ok(n.to_string()) +} + +impl Document { + /// Every item in the Library: symbols, then bitmaps, then sounds. + pub fn library_items(&self) -> impl Iterator + '_ { + self.library + .iter() + .map(|s| LibraryItem::Symbol(s.id)) + .chain(self.bitmaps.iter().map(|b| LibraryItem::Bitmap(b.id))) + .chain(self.sounds.iter().map(|s| LibraryItem::Sound(s.id))) + } + + pub fn has_item(&self, item: LibraryItem) -> bool { + self.item_name(item).is_some() + } + + pub fn item_name(&self, item: LibraryItem) -> Option<&str> { + match item { + LibraryItem::Symbol(id) => self.symbol(id).map(|s| s.name.as_str()), + LibraryItem::Bitmap(id) => self.bitmap(id).map(|b| b.name.as_str()), + LibraryItem::Sound(id) => self.sound(id).map(|s| s.name.as_str()), + } + } + + pub fn folder(&self, id: FolderId) -> Option<&LibraryFolder> { + self.library_tree.folders.iter().find(|f| f.id == id) + } + + pub fn has_entry(&self, e: LibraryEntry) -> bool { + match e { + LibraryEntry::Item(i) => self.has_item(i), + LibraryEntry::Folder(f) => self.folder(f).is_some(), + } + } + + pub fn entry_name(&self, e: LibraryEntry) -> Option<&str> { + match e { + LibraryEntry::Item(i) => self.item_name(i), + LibraryEntry::Folder(f) => self.folder(f).map(|f| f.name.as_str()), + } + } + + /// The folder `e` is in (`None`: the top level). + pub fn parent_of(&self, e: LibraryEntry) -> Option { + match e { + LibraryEntry::Item(i) => self.library_tree.placed.get(&i).copied(), + LibraryEntry::Folder(f) => self.folder(f).and_then(|f| f.parent), + } + } + + /// The folders from the top level down to `id` (inclusive). Bounded, so a damaged tree can't + /// loop. + pub fn folder_chain(&self, id: FolderId) -> Vec { + let mut out = Vec::new(); + let mut at = Some(id); + while let Some(f) = at.and_then(|i| self.folder(i)) { + if out.len() >= MAX_FOLDER_DEPTH || out.contains(&f.id) { + break; + } + out.push(f.id); + at = f.parent; + } + out.reverse(); + out + } + + /// `e`'s place as a path, `Characters/Hero/Ball` (`/` joins folder names). + pub fn entry_path(&self, e: LibraryEntry) -> String { + let mut parts: Vec<&str> = self.parent_of(e).map(|p| self.folder_chain(p)).unwrap_or_default().into_iter().filter_map(|f| self.folder(f).map(|x| x.name.as_str())).collect(); + parts.push(self.entry_name(e).unwrap_or("")); + parts.join("/") + } + + /// Whether `inner` is `outer` or inside it, at any depth. + pub fn folder_within(&self, inner: FolderId, outer: FolderId) -> bool { + self.folder_chain(inner).contains(&outer) + } + + /// The folders and items directly in `parent` (`None`: the top level), folders first. + pub fn library_children(&self, parent: Option) -> Vec { + let folders = self.library_tree.folders.iter().filter(|f| f.parent == parent).map(|f| LibraryEntry::Folder(f.id)); + let items = self.library_items().filter(|i| self.library_tree.placed.get(i).copied() == parent).map(LibraryEntry::Item); + folders.chain(items).collect() + } + + /// Everything inside folder `id` at any depth (not the folder itself): folders, then items. + pub fn folder_contents(&self, id: FolderId) -> Vec { + let inside: Vec = self.library_tree.folders.iter().filter(|f| f.id != id && self.folder_within(f.id, id)).map(|f| f.id).collect(); + let mut all = inside.clone(); + all.push(id); + let items = self.library_items().filter(|i| self.library_tree.placed.get(i).is_some_and(|f| all.contains(f))); + inside.into_iter().map(LibraryEntry::Folder).chain(items.map(LibraryEntry::Item)).collect() + } + + /// How deep folder `id` is (1 at the top level). + pub fn folder_depth(&self, id: FolderId) -> usize { + self.folder_chain(id).len() + } + + /// How many folder levels `id` holds, itself included (1 for a folder without subfolders). + pub fn folder_height(&self, id: FolderId) -> usize { + let base = self.folder_depth(id); + self.library_tree.folders.iter().filter(|f| self.folder_within(f.id, id)).map(|f| self.folder_depth(f.id) + 1 - base).max().unwrap_or(1) + } + + /// Whether folder `parent` already holds something named `name` (case aside), other than + /// `except`. + pub fn name_taken(&self, parent: Option, name: &str, except: Option) -> bool { + self.library_children(parent).into_iter().filter(|e| Some(*e) != except).any(|e| self.entry_name(e).is_some_and(|n| same_name(n, name))) + } + + /// `name` checked for the Library's rules and for a clash in `parent`. + pub fn check_name(&self, parent: Option, name: &str, except: Option) -> Result { + let n = clean_name(name)?; + if self.name_taken(parent, &n, except) { + return Err(NameError::Taken(n)); + } + Ok(n) + } + + /// `wanted`, or `wanted 2`, `wanted 3`, … whichever `parent` doesn't hold yet. + pub fn unique_name(&self, parent: Option, wanted: &str) -> String { + let base: String = wanted.trim().replace('/', "-").chars().take(MAX_NAME_CHARS - 8).collect(); + let base = if base.is_empty() { "Item".to_string() } else { base }; + if !self.name_taken(parent, &base, None) { + return base; + } + let siblings = self.library_children(parent).len() + 2; + (2..=siblings).map(|n| format!("{base} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or(base) + } + + /// `stem 1`, `stem 2`, … the first that `parent` doesn't hold, counting from `start`. + pub fn numbered_name(&self, parent: Option, stem: &str, start: usize) -> String { + let end = start + self.library_children(parent).len() + 1; + (start.max(1)..=end).map(|n| format!("{stem} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or_else(|| format!("{stem} {end}")) + } + + /// Moves `e` into folder `to` (`None`: the top level). No checks: see `library.move`. + pub fn place_entry(&mut self, e: LibraryEntry, to: Option) { + let tree = Arc::make_mut(&mut self.library_tree); + match e { + LibraryEntry::Item(i) => match to { + Some(f) => { + tree.placed.insert(i, f); + } + None => { + tree.placed.remove(&i); + } + }, + LibraryEntry::Folder(id) => { + if let Some(f) = tree.folders.iter_mut().find(|f| f.id == id) { + f.parent = to; + } + } + } + } + + /// The folder at `path` (`Characters/Hero`), made where missing. `None` for an empty path, + /// or when the Library can't hold more folders or nesting. + pub fn ensure_folder_path(&mut self, path: &str) -> Option { + let mut parent: Option = None; + for (depth, part) in path.split('/').map(str::trim).filter(|p| !p.is_empty()).enumerate() { + if depth >= MAX_FOLDER_DEPTH { + break; + } + let part: String = part.chars().take(MAX_NAME_CHARS).collect(); + let found = self.library_tree.folders.iter().find(|f| f.parent == parent && same_name(&f.name, &part)).map(|f| f.id); + parent = Some(match found { + Some(id) => id, + None => { + if self.library_tree.folders.len() >= MAX_FOLDERS { + return parent; + } + let id = FolderId(self.alloc_id()); + Arc::make_mut(&mut self.library_tree).folders.push(LibraryFolder { id, name: part, parent }); + id + } + }); + } + parent + } + + /// How many times each item is used: symbol instances, shapes filled with a bitmap and + /// keyframes playing a sound, counted once per keyframe on every timeline (scenes and + /// symbols). Items used nowhere are left out. + pub fn library_uses(&self) -> HashMap { + let mut uses: HashMap = HashMap::new(); + for tl in self.timelines() { + visit_refs(tl, |item| *uses.entry(item).or_default() += 1); + } + uses + } + + /// The items nothing in the movie reaches: not placed in any scene, nor inside a symbol + /// that is (at any depth). Symbols with a linkage class count as reached, since scripts + /// can make them by name. In Library order. + pub fn unused_items(&self) -> Vec { + let mut reached: HashSet = HashSet::new(); + let mut stack: Vec = self.library.iter().filter(|s| s.linkage.is_some()).map(|s| s.id).collect(); + for s in &stack { + reached.insert(LibraryItem::Symbol(*s)); + } + let reach = |item: LibraryItem, reached: &mut HashSet, stack: &mut Vec| { + if reached.insert(item) + && let LibraryItem::Symbol(id) = item + { + stack.push(id); + } + }; + for scene in &self.scenes { + visit_refs(&scene.timeline, |item| reach(item, &mut reached, &mut stack)); + } + // Each symbol is walked at most once (it enters the stack when first reached). + while let Some(id) = stack.pop() { + if let Some(sym) = self.symbol(id) { + visit_refs(&sym.timeline, |item| reach(item, &mut reached, &mut stack)); + } + } + self.library_items().filter(|i| !reached.contains(i)).collect() + } + + /// Whether symbol `outer` is `inner` or holds an instance of it at any depth (so placing + /// `inner` inside `outer` would make a symbol contain itself). + pub fn symbol_contains(&self, outer: SymbolId, inner: SymbolId) -> bool { + let mut seen: HashSet = HashSet::new(); + let mut stack = vec![outer]; + while let Some(id) = stack.pop() { + if id == inner { + return true; + } + if !seen.insert(id) { + continue; + } + if let Some(sym) = self.symbol(id) { + visit_refs(&sym.timeline, |item| { + if let LibraryItem::Symbol(s) = item { + stack.push(s); + } + }); + } + } + false + } + + /// A copy of symbol `id` named `name`, with fresh layer and element ids, in the same + /// folder, right after it in the Library. Its linkage class stays with the original (a + /// class names one symbol). The new symbol's id, or `None` if there is no such symbol. + pub fn duplicate_symbol(&mut self, id: SymbolId, name: String) -> Option { + let at = self.library.iter().position(|s| s.id == id)?; + 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 }; + 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); + } + Some(new_id) + } + + /// Repairs a loaded Library tree: folders with unique ids and usable names, parents that + /// exist, no cycles, nesting within [`MAX_FOLDER_DEPTH`], and only placements of items and + /// folders that exist. Touches the tree only if something needs it. + pub(crate) fn sanitize_library_tree(&mut self, max_id: &mut u64) { + let ok = |d: &Document| { + let t = &d.library_tree; + let mut ids = HashSet::new(); + t.folders.len() <= MAX_FOLDERS + && t.folders.iter().all(|f| ids.insert(f.id) && clean_name(&f.name).as_deref() == Ok(f.name.as_str()) && f.parent.is_none_or(|p| p != f.id && d.folder(p).is_some())) + && t.folders.iter().all(|f| d.folder_chain(f.id).first().is_some_and(|top| d.folder(*top).is_some_and(|x| x.parent.is_none()))) + && t.placed.iter().all(|(i, f)| d.has_item(*i) && d.folder(*f).is_some()) + }; + for f in &self.library_tree.folders { + *max_id = (*max_id).max(f.id.0); + } + if ok(self) { + return; + } + let mut tree = (*self.library_tree).clone(); + let mut seen = HashSet::new(); + tree.folders.retain(|f| seen.insert(f.id)); + tree.folders.truncate(MAX_FOLDERS); + for (i, f) in tree.folders.iter_mut().enumerate() { + let name: String = f.name.trim().replace('/', "-").chars().take(MAX_NAME_CHARS).collect(); + f.name = if name.is_empty() { format!("Folder {}", i + 1) } else { name }; + } + let ids: HashSet = tree.folders.iter().map(|f| f.id).collect(); + for f in &mut tree.folders { + if f.parent.is_some_and(|p| p == f.id || !ids.contains(&p)) { + f.parent = None; + } + } + // Cycles and over-deep chains: the first folder found on one goes to the top level. + for i in 0..tree.folders.len() { + let Some(start) = tree.folders.get(i).map(|f| f.id) else { continue }; + let mut at = tree.folders.get(i).and_then(|f| f.parent); + let mut steps = 1; + let mut bad = false; + while let Some(p) = at { + steps += 1; + if p == start || steps > MAX_FOLDER_DEPTH { + bad = true; + break; + } + at = tree.folders.iter().find(|f| f.id == p).and_then(|f| f.parent); + } + if bad && let Some(f) = tree.folders.get_mut(i) { + f.parent = None; + } + } + let items: HashSet = self.library_items().collect(); + tree.placed.retain(|i, f| items.contains(i) && ids.contains(f)); + self.library_tree = Arc::new(tree); + } +} + +/// Calls `f` once per Library reference on each keyframe of `tl`: symbol instances, bitmap +/// fills and the keyframe's sound. +pub fn visit_refs(tl: &Timeline, mut f: impl FnMut(LibraryItem)) { + for l in &tl.layers { + for k in &l.keyframes { + for e in &k.elements { + match &e.kind { + ElementKind::Symbol { symbol, .. } => f(LibraryItem::Symbol(*symbol)), + ElementKind::Shape(s) => { + if let Some(Paint::Bitmap { bitmap, .. }) = &s.fill { + f(LibraryItem::Bitmap(*bitmap)); + } + } + ElementKind::Text(_) | ElementKind::Camera => {} + } + } + if let Some(s) = &k.sound { + f(LibraryItem::Sound(s.sound)); + } + } + } +} + +/// `tl` with new layer and element ids from `alloc`, every reference to them (layer parents, +/// motion tween targets, bone ends) following. An element keeps one id across keyframes, as +/// tweens need. +pub fn fresh_ids(tl: &Timeline, alloc: &mut dyn FnMut() -> u64) -> Timeline { + let mut layers: HashMap = HashMap::new(); + let mut elements: HashMap = HashMap::new(); + for l in &tl.layers { + layers.entry(l.id).or_insert_with(|| LayerId(alloc())); + for k in &l.keyframes { + for e in &k.elements { + elements.entry(e.id).or_insert_with(|| ElementId(alloc())); + } + } + } + let el = |id: ElementId| elements.get(&id).copied().unwrap_or(id); + let out = tl + .layers + .iter() + .map(|l| { + let mut l = (**l).clone(); + l.id = layers.get(&l.id).copied().unwrap_or(l.id); + l.parent = l.parent.map(|p| layers.get(&p).copied().unwrap_or(p)); + if let Some(a) = &mut l.armature { + for b in &mut Arc::make_mut(a).bones { + b.parent = el(b.parent); + b.child = el(b.child); + } + } + for k in &mut l.keyframes { + let k = Arc::make_mut(k); + for e in &mut k.elements { + Arc::make_mut(e).id = el(e.id); + } + if let Some(m) = &mut k.motion { + m.target = el(m.target); + } + } + Arc::new(l) + }) + .collect(); + Timeline { layers: out } +} + +#[cfg(test)] +#[path = "library_tests.rs"] +mod tests; diff --git a/crates/doc/src/library_tests.rs b/crates/doc/src/library_tests.rs new file mode 100644 index 00000000..f5a66bbe --- /dev/null +++ b/crates/doc/src/library_tests.rs @@ -0,0 +1,195 @@ +use super::*; +use crate::{Element, Layer, Linkage, Symbol, SymbolKind, sample}; + +fn instance(d: &mut Document, symbol: SymbolId) -> Arc { + Arc::new(Element { + id: ElementId(d.alloc_id()), + name: String::new(), + transform: Default::default(), + color: Default::default(), + kind: ElementKind::Symbol { symbol, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + }) +} + +/// A symbol named `name` holding instances of `inside`. +fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId { + let id = SymbolId(d.alloc_id()); + let mut layer = Layer::new(LayerId(d.alloc_id()), "Layer 1"); + let els: Vec<_> = inside.iter().map(|s| instance(d, *s)).collect(); + 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)] } })); + id +} + +fn sym(d: &Document, name: &str) -> SymbolId { + d.library.iter().find(|s| s.name == name).map(|s| s.id).unwrap_or(SymbolId(0)) +} + +#[test] +fn folders_round_trip_and_older_files_open_without_them() { + let mut d = sample::demo(); + let plain = serde_json::to_string(&d).unwrap(); + assert!(!plain.contains("library_tree"), "a Library without folders writes nothing new"); + let back: Document = serde_json::from_str(&plain).unwrap(); + assert!(back.library_tree.is_empty()); + + let chars = d.ensure_folder_path("Characters/Hero").unwrap(); + let ball = sym(&d, "Ball"); + d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(ball)), Some(chars)); + let json = serde_json::to_string(&d).unwrap(); + assert!(json.contains(&format!("{{\"symbol\":{},\"folder\":{}}}", ball.0, chars.0)), "{json}"); + let mut back: Document = serde_json::from_str(&json).unwrap(); + back.sanitize(); + assert_eq!(back.library_tree, d.library_tree); + assert_eq!(back.entry_path(LibraryEntry::Item(LibraryItem::Symbol(ball))), "Characters/Hero/Ball"); +} + +#[test] +fn folder_paths_are_made_once_and_matched_without_case() { + let mut d = Document::default(); + let a = d.ensure_folder_path("Characters/Hero").unwrap(); + let b = d.ensure_folder_path(" characters / HERO ").unwrap(); + assert_eq!(a, b); + assert_eq!(d.library_tree.folders.len(), 2); + assert_eq!(d.folder_depth(a), 2); + assert_eq!(d.ensure_folder_path(""), None); + assert_eq!(d.ensure_folder_path("//"), None); + let top = d.folder_chain(a)[0]; + assert_eq!(d.folder_height(top), 2); + assert!(d.folder_within(a, top) && !d.folder_within(top, a)); + // Nesting stops at the limit instead of growing without end. + let deep = vec!["x"; MAX_FOLDER_DEPTH + 10].join("/"); + let f = d.ensure_folder_path(&deep).unwrap(); + assert_eq!(d.folder_depth(f), MAX_FOLDER_DEPTH); +} + +#[test] +fn names_are_unique_per_folder_without_case() { + let mut d = sample::demo(); + let f = d.ensure_folder_path("Props").unwrap(); + let ball = LibraryEntry::Item(LibraryItem::Symbol(sym(&d, "Ball"))); + assert_eq!(d.check_name(None, "ball", None), Err(NameError::Taken("ball".into()))); + assert_eq!(d.check_name(None, " Ball ", Some(ball)).as_deref(), Ok("Ball"), "an item may keep its own name"); + assert_eq!(d.check_name(Some(f), "Ball", None).as_deref(), Ok("Ball"), "another folder may hold the same name"); + assert_eq!(d.check_name(None, "a/b", None), Err(NameError::Slash)); + assert_eq!(d.check_name(None, " ", None), Err(NameError::Empty)); + assert_eq!(d.check_name(None, &"x".repeat(MAX_NAME_CHARS + 1), None), Err(NameError::TooLong)); + assert_eq!(d.check_name(None, "props", None), Err(NameError::Taken("props".into())), "folders and items share a folder's names"); + assert_eq!(d.unique_name(None, "Ball"), "Ball 2"); + assert_eq!(d.unique_name(None, "Ball copy"), "Ball copy"); + assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 1"); + add_symbol(&mut d, "Symbol 1", &[]); + assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 2"); +} + +#[test] +fn damaged_trees_are_repaired_on_load() { + let mut d = sample::demo(); + let ball = LibraryItem::Symbol(sym(&d, "Ball")); + let t = Arc::make_mut(&mut d.library_tree); + let f = |id: u64, name: &str, parent: Option| LibraryFolder { id: FolderId(id), name: name.into(), parent: parent.map(FolderId) }; + t.folders = vec![f(900, "A", Some(901)), f(901, "B", Some(900)), f(902, " ", Some(902)), f(903, "C/D", Some(999)), f(900, "Dup", None)]; + t.placed.insert(ball, FolderId(901)); + t.placed.insert(LibraryItem::Sound(SoundId(12345)), FolderId(900)); + t.placed.insert(LibraryItem::Symbol(SymbolId(77777)), FolderId(900)); + d.sanitize(); + let t = &d.library_tree; + assert_eq!(t.folders.len(), 4, "the duplicate id is dropped"); + assert!(t.folders.iter().all(|f| d.folder_chain(f.id).len() <= 2), "the cycle is broken"); + assert!(t.folders.iter().all(|f| f.parent != Some(f.id) && f.parent.is_none_or(|p| d.folder(p).is_some()))); + assert!(t.folders.iter().all(|f| clean_name(&f.name).is_ok()), "{:?}", t.folders); + assert_eq!(t.placed.len(), 1, "only items that exist stay placed"); + assert!(d.next_id > 903, "folder ids stay unique"); + // A sane tree is left alone (same Arc). + let before = d.library_tree.clone(); + d.sanitize(); + assert!(Arc::ptr_eq(&before, &d.library_tree)); +} + +#[test] +fn uses_count_every_keyframe_and_unused_follows_reachability() { + let mut d = sample::demo(); + let (ball, star) = (sym(&d, "Ball"), sym(&d, "Star")); + let uses = d.library_uses(); + assert!(uses.get(&LibraryItem::Symbol(ball)).copied().unwrap_or(0) > 0); + assert!(uses.get(&LibraryItem::Symbol(star)).copied().unwrap_or(0) > 0); + assert!(d.unused_items().is_empty(), "the sample uses everything"); + + // Inner is used only inside Outer, which nothing places: both are unused, though Inner + // has a use. + let inner = add_symbol(&mut d, "Inner", &[]); + let outer = add_symbol(&mut d, "Outer", &[inner, inner]); + assert_eq!(d.library_uses().get(&LibraryItem::Symbol(inner)), Some(&2)); + assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(inner), LibraryItem::Symbol(outer)]); + // A linkage class makes a symbol reachable (scripts make it by name), and what it holds. + if let Some(s) = d.library.iter_mut().find(|s| s.id == outer) { + Arc::make_mut(s).linkage = Some(Linkage { class: "Outer".into(), base: String::new() }); + } + assert!(d.unused_items().is_empty()); + // Cycles terminate. + let a = add_symbol(&mut d, "A", &[]); + let b = add_symbol(&mut d, "B", &[a]); + if let Some(s) = d.library.iter_mut().find(|s| s.id == a) { + let layer = Arc::make_mut(&mut Arc::make_mut(s).timeline.layers[0]); + let e = Arc::new(Element { id: ElementId(5_000_000), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: b, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } }); + layer.keyframe_mut(0).unwrap().elements.push(e); + } + assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(a), LibraryItem::Symbol(b)]); + assert!(d.symbol_contains(a, b) && d.symbol_contains(b, a) && d.symbol_contains(a, a)); + assert!(!d.symbol_contains(inner, outer) && d.symbol_contains(outer, inner)); +} + +#[test] +fn a_duplicate_has_fresh_ids_and_keeps_its_folder() { + let mut d = sample::demo(); + let star = sym(&d, "Star"); + let f = d.ensure_folder_path("FX").unwrap(); + d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(star)), Some(f)); + if let Some(s) = d.library.iter_mut().find(|s| s.id == star) { + Arc::make_mut(s).linkage = Some(Linkage { class: "Star".into(), base: String::new() }); + } + let copy = d.duplicate_symbol(star, "Star copy".into()).unwrap(); + let (a, b) = (d.symbol(star).unwrap(), d.symbol(copy).unwrap()); + assert_eq!(b.name, "Star copy"); + assert_eq!(b.kind, a.kind); + assert!(b.linkage.is_none(), "a class names one symbol"); + assert_eq!(d.parent_of(LibraryEntry::Item(LibraryItem::Symbol(copy))), Some(f)); + let ids = |s: &Symbol| -> HashSet { s.timeline.layers.iter().flat_map(|l| std::iter::once(l.id.0).chain(l.keyframes.iter().flat_map(|k| k.elements.iter().map(|e| e.id.0)))).collect() }; + assert!(ids(a).is_disjoint(&ids(b))); + assert_eq!(ids(a).len(), ids(b).len()); + // Same artwork: only ids differ, and an element keeps one id across its keyframes. + for (la, lb) in a.timeline.layers.iter().zip(&b.timeline.layers) { + assert_eq!(la.keyframes.len(), lb.keyframes.len()); + for (ka, kb) in la.keyframes.iter().zip(&lb.keyframes) { + for (ea, eb) in ka.elements.iter().zip(&kb.elements) { + assert_eq!((&ea.kind, ea.transform), (&eb.kind, eb.transform)); + } + } + let first: Vec = lb.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect(); + if first.len() > 1 && la.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect::>().len() == 1 { + assert!(first.windows(2).all(|w| w[0] == w[1])); + } + } + let order: Vec = d.library.iter().map(|s| s.id).collect(); + let at = order.iter().position(|s| *s == star).unwrap(); + assert_eq!(order[at + 1], copy, "the copy sits right after its original"); + assert_eq!(d.duplicate_symbol(SymbolId(424242), "x".into()), None); +} + +#[test] +fn folder_contents_reach_every_depth() { + let mut d = sample::demo(); + let a = d.ensure_folder_path("A").unwrap(); + let ab = d.ensure_folder_path("A/B").unwrap(); + let c = d.ensure_folder_path("C").unwrap(); + let ball = LibraryItem::Symbol(sym(&d, "Ball")); + d.place_entry(LibraryEntry::Item(ball), Some(ab)); + let inside = d.folder_contents(a); + assert_eq!(inside, vec![LibraryEntry::Folder(ab), LibraryEntry::Item(ball)]); + assert!(d.folder_contents(c).is_empty()); + assert_eq!(d.library_children(Some(ab)), vec![LibraryEntry::Item(ball)]); + assert!(d.library_children(None).starts_with(&[LibraryEntry::Folder(a), LibraryEntry::Folder(c)])); + assert!(!d.library_children(None).contains(&LibraryEntry::Item(ball))); +} diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 2d94e4c7..4633a16b 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(), 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(), 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(), 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(), 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(), 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(), 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 bc77a119..3ada0b02 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(), 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(), next_id: doc.next_id }; unique_bytes(doc, &empty) } From e6c0f5a91aabe576473a1079cc0339a4ce1dc649 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:36:51 -0700 Subject: [PATCH 029/402] feat(engine): library.* folder, rename, move, duplicate, delete and unused commands, element.swap_symbol, smoothing (M2) --- crates/engine/src/cmds_draw.rs | 4 +- crates/engine/src/cmds_library.rs | 396 +++++++++++++++++++++++++++++ crates/engine/src/confirm.rs | 47 ++++ crates/engine/src/lib.rs | 2 + crates/engine/src/library_tests.rs | 269 ++++++++++++++++++++ crates/engine/src/tests.rs | 23 +- 6 files changed, 737 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmds_library.rs create mode 100644 crates/engine/src/library_tests.rs diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index b7df7971..6a980d01 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -648,8 +648,8 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { let Some(&top) = layers.first() else { return Err(EngineError::State("select something to convert".into())); }; - let n = s.doc.library.len() + 1; - let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}")); + // The next free “Symbol n” at the Library's top level, where new symbols go (ADR 0050). + let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| s.doc.numbered_name(None, "Symbol", s.doc.library.len() + 1)); let bounds = s.selection_bounds(); let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; let sym_id = SymbolId(s.doc.alloc_id()); diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs new file mode 100644 index 00000000..9ff8a965 --- /dev/null +++ b/crates/engine/src/cmds_library.rs @@ -0,0 +1,396 @@ +//! Library management (ADR 0050): folders, renaming, moving, duplicating and deleting items, +//! use counts and unused items, bitmap smoothing, and Swap Symbol. +//! +//! An item or folder is named in params as `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` +//! or `{"folder": id}`. Sorting and filtering the list are views (the shell's); `library.items` +//! gives a script everything it needs to do the same. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::library::{MAX_FOLDER_DEPTH, MAX_FOLDERS}; +use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryFolder, LibraryItem, Paint, SoundId, SymbolId, SymbolKind, Timeline}; +use serde_json::{Value, json}; +use std::collections::HashSet; +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("library.items", "List Library", "", None, "{} every folder (id, name, parent, path) and item (symbol | bitmap | sound id, kind, name, folder, path, uses, unused) in Library order; `uses` counts instances, bitmap fills and keyframe sounds once per keyframe", false, items as crate::RunFn), + c("library.new_folder", "New Folder", "", None, "{name? (default: the next free “Folder n”), parent?: folder id} → {folder, name}; names are unique within a folder (case aside) and can't hold “/”", true, new_folder), + c("library.rename", "Rename", "", None, "{symbol | bitmap | sound | folder: id, name} renames a Library item or folder; the name must be free in its folder (case aside) and can't hold “/”", true, rename), + c("library.move", "Move to Folder", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..], to: folder id | null (the top level)} moves items and folders (with what they hold) into a folder; a folder can't go inside itself, and a name the folder already has stops the move", true, move_to), + c("library.duplicate", "Duplicate Symbol", "", None, "{symbol, name? (default: “ copy”)} → {symbol, name}: a copy in the same folder, with its own layers and elements and no linkage class", true, duplicate), + c("library.delete", "Delete", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..]} deletes items and folders with everything in them; instances of deleted symbols, shapes filled with deleted bitmaps and keyframes' deleted sounds go too (asks first when anything deleted is in use or a folder isn't empty)", true, delete), + c("library.unused", "Select Unused Items", "", None, "{} → {items: [..]} the items nothing in the movie reaches: not in a scene, nor inside a symbol that is; symbols with a linkage class count as used", false, unused), + c("library.delete_unused", "Delete Unused Items", "", None, "{} deletes every item `library.unused` lists (asks first)", true, delete_unused), + c("library.set_smoothing", "Allow Smoothing", "", None, "{bitmap, on?: bool (default: toggle)} whether the bitmap is filtered when scaled or turned (off: hard-edged pixels)", true, set_smoothing), + c("element.swap_symbol", "Swap Symbol", "", None, "{symbol} the selected instances show another symbol, keeping their transform, colour effect, blending, filters, looping, actions and instance name", true, |s, p| s.each_layer(false, |s| swap_symbol(s, p))), + ] +} + +/// Most entries one command takes. +const MAX_ENTRIES: usize = 100_000; + +/// The entry a JSON object names: `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` or +/// `{"folder": id}`. +pub(crate) fn entry_of(v: &Value) -> Result { + let id = |k: &str| v.get(k).and_then(Value::as_u64); + match (id("symbol"), id("bitmap"), id("sound"), id("folder")) { + (Some(i), None, None, None) => Ok(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(i)))), + (None, Some(i), None, None) => Ok(LibraryEntry::Item(LibraryItem::Bitmap(BitmapId(i)))), + (None, None, Some(i), None) => Ok(LibraryEntry::Item(LibraryItem::Sound(SoundId(i)))), + (None, None, None, Some(i)) => Ok(LibraryEntry::Folder(FolderId(i))), + _ => Err(EngineError::Param("name one Library entry: {\"symbol\" | \"bitmap\" | \"sound\" | \"folder\": id}".into())), + } +} + +/// `entry` as params name it. +pub fn entry_json(e: LibraryEntry) -> Value { + match e { + LibraryEntry::Item(LibraryItem::Symbol(i)) => json!({"symbol": i.0}), + LibraryEntry::Item(LibraryItem::Bitmap(i)) => json!({"bitmap": i.0}), + LibraryEntry::Item(LibraryItem::Sound(i)) => json!({"sound": i.0}), + LibraryEntry::Folder(f) => json!({"folder": f.0}), + } +} + +/// The entries in list `key`, each checked to exist (no repeats). +pub(crate) fn entries_of(s: &Session, p: &Value, key: &str) -> Result> { + let list = p.get(key).and_then(Value::as_array).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a list of Library entries")))?; + if list.len() > MAX_ENTRIES { + return Err(EngineError::Param(format!("at most {MAX_ENTRIES} entries"))); + } + let mut out = Vec::with_capacity(list.len()); + let mut seen = HashSet::new(); + for v in list { + let e = entry_of(v)?; + if !s.doc.has_entry(e) { + return Err(EngineError::State(format!("the Library has no {}", describe(e)))); + } + if seen.insert(e) { + out.push(e); + } + } + Ok(out) +} + +fn describe(e: LibraryEntry) -> String { + match e { + LibraryEntry::Item(LibraryItem::Symbol(i)) => format!("symbol {}", i.0), + LibraryEntry::Item(LibraryItem::Bitmap(i)) => format!("bitmap {}", i.0), + LibraryEntry::Item(LibraryItem::Sound(i)) => format!("sound {}", i.0), + LibraryEntry::Folder(f) => format!("folder {}", f.0), + } +} + +fn opt_folder(s: &Session, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let id = v.as_u64().map(FolderId).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a folder id or null")))?; + if s.doc.folder(id).is_none() { + return Err(EngineError::State(format!("the Library has no folder {}", id.0))); + } + Ok(Some(id)) + } + } +} + +fn kind_key(k: SymbolKind) -> &'static str { + match k { + SymbolKind::Graphic => "graphic", + SymbolKind::MovieClip => "movie_clip", + SymbolKind::Button => "button", + } +} + +fn items(s: &mut Session, _: &Value) -> Result { + let d = &s.doc; + let uses = d.library_uses(); + let unused: HashSet = d.unused_items().into_iter().collect(); + let folders: Vec = d + .library_tree + .folders + .iter() + .map(|f| json!({"folder": f.id.0, "name": f.name, "parent": f.parent.map(|p| p.0), "path": d.entry_path(LibraryEntry::Folder(f.id))})) + .collect(); + let items: Vec = d + .library_items() + .map(|i| { + let e = LibraryEntry::Item(i); + let mut v = entry_json(e); + v["name"] = json!(d.item_name(i)); + v["folder"] = json!(d.parent_of(e).map(|f| f.0)); + v["path"] = json!(d.entry_path(e)); + v["uses"] = json!(uses.get(&i).copied().unwrap_or(0)); + v["unused"] = json!(unused.contains(&i)); + match i { + LibraryItem::Symbol(id) => { + if let Some(sym) = d.symbol(id) { + v["kind"] = json!(kind_key(sym.kind)); + v["frames"] = json!(sym.timeline.frame_count()); + v["linkage"] = json!(sym.linkage.as_ref().map(|l| &l.class)); + } + } + LibraryItem::Bitmap(id) => { + if let Some(b) = d.bitmap(id) { + v["kind"] = json!("bitmap"); + v["width"] = json!(b.width); + v["height"] = json!(b.height); + v["smoothing"] = json!(b.smoothing); + } + } + LibraryItem::Sound(id) => { + if let Some(x) = d.sound(id) { + v["kind"] = json!("sound"); + v["seconds"] = json!(x.seconds()); + } + } + } + v + }) + .collect(); + Ok(json!({"folders": folders, "items": items, "unused": unused.len()})) +} + +fn new_folder(s: &mut Session, p: &Value) -> Result { + let parent = opt_folder(s, p, "parent")?; + if s.doc.library_tree.folders.len() >= MAX_FOLDERS { + return Err(EngineError::State(format!("the Library holds at most {MAX_FOLDERS} folders"))); + } + if parent.is_some_and(|f| s.doc.folder_depth(f) >= MAX_FOLDER_DEPTH) { + return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep"))); + } + let name = match opt_str(p, "name")? { + Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?, + None => s.doc.numbered_name(parent, "Folder", 1), + }; + let id = FolderId(s.doc.alloc_id()); + Arc::make_mut(&mut s.doc.library_tree).folders.push(LibraryFolder { id, name: name.clone(), parent }); + Ok(json!({"folder": id.0, "name": name})) +} + +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)))); + } + let name = s.doc.check_name(s.doc.parent_of(e), str_req(p, "name")?, Some(e)).map_err(|err| EngineError::Param(err.to_string()))?; + let d = &mut s.doc; + match e { + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + if let Some(x) = d.library.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Item(LibraryItem::Bitmap(id)) => { + if let Some(x) = d.bitmaps.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Item(LibraryItem::Sound(id)) => { + if let Some(x) = d.sounds.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Folder(id) => { + if let Some(f) = Arc::make_mut(&mut d.library_tree).folders.iter_mut().find(|f| f.id == id) { + f.name = name.clone(); + } + } + } + let mut v = entry_json(e); + v["name"] = json!(name); + Ok(v) +} + +fn move_to(s: &mut Session, p: &Value) -> Result { + let list = entries_of(s, p, "items")?; + if p.get("to").is_none() { + return Err(EngineError::Param("param 'to' is required: a folder id, or null for the top level".into())); + } + let to = opt_folder(s, p, "to")?; + let mut moved = 0; + for e in list { + if s.doc.parent_of(e) == to { + continue; + } + if let LibraryEntry::Folder(f) = e { + if to.is_some_and(|t| s.doc.folder_within(t, f)) { + return Err(EngineError::State(format!("“{}” can't go inside itself", s.doc.entry_name(e).unwrap_or("")))); + } + if to.map_or(0, |t| s.doc.folder_depth(t)) + s.doc.folder_height(f) > MAX_FOLDER_DEPTH { + return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep"))); + } + } + let name = s.doc.entry_name(e).unwrap_or("").to_string(); + if s.doc.name_taken(to, &name, Some(e)) { + let place = to.and_then(|t| s.doc.folder(t)).map_or_else(|| "The top level of the Library".to_string(), |f| format!("“{}”", f.name)); + return Err(EngineError::State(format!("{place} already has an item named “{name}”; rename one of them first"))); + } + s.doc.place_entry(e, to); + moved += 1; + } + Ok(json!({"moved": moved, "to": to.map(|f| f.0)})) +} + +fn duplicate(s: &mut Session, p: &Value) -> Result { + let id = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?); + let Some(src) = s.doc.symbol(id) else { + return Err(EngineError::State(format!("no symbol with id {}", id.0))); + }; + let parent = s.doc.parent_of(LibraryEntry::Item(LibraryItem::Symbol(id))); + let name = match opt_str(p, "name")? { + Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?, + None => s.doc.unique_name(parent, &format!("{} copy", src.name)), + }; + let copy = s.doc.duplicate_symbol(id, name.clone()).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + Ok(json!({"symbol": copy.0, "name": name})) +} + +/// What deleting `entries` takes: the items (folders expanded into what they hold) and the +/// folders. +pub(crate) fn deletion(s: &Session, entries: &[LibraryEntry]) -> (Vec, Vec) { + let mut items: Vec = Vec::new(); + let mut folders: Vec = Vec::new(); + let add = |e: LibraryEntry, items: &mut Vec, folders: &mut Vec| match e { + LibraryEntry::Item(i) if !items.contains(&i) => items.push(i), + LibraryEntry::Folder(f) if !folders.contains(&f) => folders.push(f), + _ => {} + }; + for &e in entries { + add(e, &mut items, &mut folders); + if let LibraryEntry::Folder(f) = e { + for inner in s.doc.folder_contents(f) { + add(inner, &mut items, &mut folders); + } + } + } + (items, folders) +} + +/// Takes every reference to `gone` off `tl` (instances, bitmap-filled shapes, keyframe sounds), +/// un-sharing only the layers and keyframes that had one. How many references went. +fn strip(tl: &mut Timeline, gone: &HashSet) -> usize { + let refers = |e: &anicraft_doc::Element| match &e.kind { + ElementKind::Symbol { symbol, .. } => gone.contains(&LibraryItem::Symbol(*symbol)), + ElementKind::Shape(sh) => matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if gone.contains(&LibraryItem::Bitmap(*bitmap))), + ElementKind::Text(_) | ElementKind::Camera => false, + }; + let sounds = |k: &anicraft_doc::Keyframe| k.sound.as_ref().is_some_and(|f| gone.contains(&LibraryItem::Sound(f.sound))); + let hit = |k: &anicraft_doc::Keyframe| sounds(k) || k.elements.iter().any(|e| refers(e)); + let mut n = 0; + for l in tl.layers.iter_mut().filter(|l| l.keyframes.iter().any(|k| hit(k))) { + for k in Arc::make_mut(l).keyframes.iter_mut().filter(|k| hit(k)) { + let k = Arc::make_mut(k); + if sounds(k) { + k.sound = None; + n += 1; + } + let before = k.elements.len(); + k.elements.retain(|e| !refers(e)); + n += before - k.elements.len(); + } + } + n +} + +/// Deletes `items` and `folders` from the Library and every use of the items from the movie. +fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value { + let gone: HashSet = items.iter().copied().collect(); + let mut uses = 0; + if !gone.is_empty() { + for scene in &mut s.doc.scenes { + if strip_needed(&scene.timeline, &gone) { + uses += strip(&mut Arc::make_mut(scene).timeline, &gone); + } + } + s.doc.library.retain(|x| !gone.contains(&LibraryItem::Symbol(x.id))); + s.doc.bitmaps.retain(|x| !gone.contains(&LibraryItem::Bitmap(x.id))); + s.doc.sounds.retain(|x| !gone.contains(&LibraryItem::Sound(x.id))); + for sym in &mut s.doc.library { + if strip_needed(&sym.timeline, &gone) { + uses += strip(&mut Arc::make_mut(sym).timeline, &gone); + } + } + // The fill swatch may hold a deleted bitmap (picked with the Eyedropper). + if let Some(Paint::Bitmap { bitmap, .. }) = &s.style.fill_paint + && gone.contains(&LibraryItem::Bitmap(*bitmap)) + { + s.style.fill_paint = None; + } + } + let dead: HashSet = folders.iter().copied().collect(); + if !dead.is_empty() || s.doc.library_tree.placed.keys().any(|i| gone.contains(i)) { + let t = Arc::make_mut(&mut s.doc.library_tree); + t.placed.retain(|i, f| !gone.contains(i) && !dead.contains(f)); + t.folders.retain(|f| !dead.contains(&f.id)); + // A folder whose parent went (it was named on its own) goes to the top level. + let ids: HashSet = t.folders.iter().map(|f| f.id).collect(); + for f in &mut t.folders { + if f.parent.is_some_and(|p| !ids.contains(&p)) { + f.parent = None; + } + } + } + json!({"deleted": items.len(), "folders": folders.len(), "uses": uses}) +} + +fn strip_needed(tl: &Timeline, gone: &HashSet) -> bool { + let mut any = false; + anicraft_doc::library::visit_refs(tl, |i| any |= gone.contains(&i)); + any +} + +fn delete(s: &mut Session, p: &Value) -> Result { + let list = entries_of(s, p, "items")?; + if list.is_empty() { + return Err(EngineError::State("nothing to delete".into())); + } + let (items, folders) = deletion(s, &list); + Ok(remove(s, &items, &folders)) +} + +fn unused(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.doc.unused_items().into_iter().map(|i| entry_json(LibraryEntry::Item(i))).collect(); + Ok(json!({"items": list})) +} + +fn delete_unused(s: &mut Session, _: &Value) -> Result { + let items = s.doc.unused_items(); + Ok(remove(s, &items, &[])) +} + +fn set_smoothing(s: &mut Session, p: &Value) -> Result { + let id = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?); + let on = opt_bool(p, "on")?; + let b = s.doc.bitmaps.iter_mut().find(|b| b.id == id).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", id.0)))?; + let on = on.unwrap_or(!b.smoothing); + if b.smoothing != on { + Arc::make_mut(b).smoothing = on; + } + Ok(json!({"bitmap": id.0, "smoothing": on})) +} + +fn swap_symbol(s: &mut Session, p: &Value) -> Result { + let to = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?); + if s.doc.symbol(to).is_none() { + return Err(EngineError::State(format!("no symbol with id {}", to.0))); + } + let mut swapped = 0; + for e in s.selected_elements_mut()? { + if let ElementKind::Symbol { symbol, .. } = &mut e.kind { + *symbol = to; + swapped += 1; + } + } + if swapped == 0 { + return Err(EngineError::State("select a symbol instance to swap".into())); + } + Ok(json!({"swapped": swapped, "symbol": to.0})) +} + +#[cfg(test)] +#[path = "library_tests.rs"] +mod tests; diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 66410e71..57de4cc9 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -144,6 +144,53 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { 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). + let list = crate::cmds_library::entries_of(s, p, "items").ok()?; + let (items, folders) = crate::cmds_library::deletion(s, &list); + let uses = s.doc.library_uses(); + let used: Vec<&anicraft_doc::LibraryItem> = items.iter().filter(|i| uses.get(i).is_some_and(|n| *n > 0)).collect(); + let n_uses: usize = used.iter().filter_map(|i| uses.get(*i)).sum(); + let inside = items.len() + folders.len() - list.len(); + if used.is_empty() && inside == 0 { + return None; + } + let what = match list.as_slice() { + [one] => format!("“{}”", s.doc.entry_name(*one).unwrap_or("")), + _ => plural(list.len(), "item"), + }; + let mut parts = Vec::new(); + if inside > 0 { + parts.push(format!("{what} {} {}, deleted with {}.", if list.len() == 1 { "holds" } else { "hold" }, plural(inside, "item"), if list.len() == 1 { "it" } else { "them" })); + } + if !used.is_empty() { + parts.push(format!("{} used {} in the movie; {} go too.", if used.len() == 1 { "One of them is".to_string() } else { format!("{} of them are", used.len()) }, plural(n_uses, "time"), if n_uses == 1 { "that use" } else { "those uses" })); + } + parts.push("You can undo this.".into()); + Some(Confirmation { + title: if inside > 0 && list.len() == 1 { "Delete folder?".into() } else { "Delete from Library?".into() }, + message: parts.join(" "), + action: "Delete".into(), + irreversible: false, + }) + } + "library.delete_unused" => { + let unused = s.doc.unused_items(); + let names: Vec = unused.iter().take(5).filter_map(|i| s.doc.item_name(*i)).map(|n| format!("“{n}”")).collect(); + let more = unused.len().saturating_sub(names.len()); + (!unused.is_empty()).then(|| Confirmation { + title: "Delete unused items?".into(), + message: format!( + "Nothing in the movie uses {}: {}{}. They leave the Library. You can undo this.", + if unused.len() == 1 { "this item".to_string() } else { format!("these {} items", unused.len()) }, + names.join(", "), + if more > 0 { format!(" and {more} more") } else { String::new() } + ), + action: "Delete Unused".into(), + irreversible: false, + }) + } "draw.erase_all" => { // Double-clicking the Eraser: everything on the stage at this frame (ADR 0034). let layers = crate::cmds_erase::erasable_layers(s); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 399dc279..1ff53205 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ mod cmds_frames; mod cmds_modify; mod cmds_motion; mod cmds_hints; +pub mod cmds_library; mod cmds_paint; mod cmds_path; pub mod cmds_raw; @@ -116,6 +117,7 @@ pub fn commands() -> Vec { v.extend(cmds_frames::specs()); v.extend(onion::specs()); v.extend(cmds_draw::specs()); + v.extend(cmds_library::specs()); v.extend(merge::specs()); v.extend(cmds_modify::specs()); v.extend(cmds_path::specs()); diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs new file mode 100644 index 00000000..89e7d9d3 --- /dev/null +++ b/crates/engine/src/library_tests.rs @@ -0,0 +1,269 @@ +//! Library management end to end (ADR 0050): folders, names, moves, duplicates, Swap Symbol, +//! deletion with its confirmations, unused items, smoothing, the file format and undo. + +use crate::Session; +use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryItem, SymbolId, sample}; +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(), + } +} + +fn sym(s: &Session, name: &str) -> u64 { + s.doc.library.iter().find(|x| x.name == name).map(|x| x.id.0).unwrap_or_else(|| panic!("no symbol {name}")) +} + +fn folder(v: &Value) -> u64 { + v["folder"].as_u64().unwrap() +} + +fn path(s: &Session, symbol: u64) -> String { + s.doc.entry_path(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(symbol)))) +} + +/// Instances of `symbol` on every timeline. +fn instances(s: &Session, symbol: u64) -> usize { + s.doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter(|e| matches!(e.kind, ElementKind::Symbol { symbol: x, .. } if x.0 == symbol)).count() +} + +#[test] +fn folders_are_made_named_and_nested() { + let mut s = Session::new(sample::demo()); + let a = run(&mut s, "library.new_folder", json!({})); + assert_eq!(a["name"], "Folder 1"); + let b = run(&mut s, "library.new_folder", json!({})); + assert_eq!(b["name"], "Folder 2"); + let inner = run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": folder(&a)})); + assert_eq!(s.doc.entry_path(LibraryEntry::Folder(FolderId(folder(&inner)))), "Folder 1/Hero"); + // Names: unique per folder without case, no slashes, not empty. + assert!(err(&mut s, "library.new_folder", json!({"name": "folder 1"})).contains("already has")); + assert!(err(&mut s, "library.new_folder", json!({"name": "a/b"})).contains("/")); + assert!(err(&mut s, "library.new_folder", json!({"name": " "})).contains("empty")); + assert!(err(&mut s, "library.new_folder", json!({"parent": 999_999})).contains("no folder")); + run(&mut s, "library.new_folder", json!({"name": "Hero"})); + // Renaming. + run(&mut s, "library.rename", json!({"folder": folder(&a), "name": "Characters"})); + assert_eq!(s.doc.folder(FolderId(folder(&a))).unwrap().name, "Characters"); + let ball = sym(&s, "Ball"); + assert!(err(&mut s, "library.rename", json!({"symbol": ball, "name": "star"})).contains("already has")); + run(&mut s, "library.rename", json!({"symbol": ball, "name": "BALL"})); + run(&mut s, "library.rename", json!({"symbol": ball, "name": "Ball"})); + assert!(err(&mut s, "library.rename", json!({"symbol": ball, "folder": 1, "name": "x"})).contains("one Library entry")); + // One undo step each. + s.undo().unwrap(); + assert_eq!(s.doc.symbol(SymbolId(ball)).unwrap().name, "BALL"); +} + +#[test] +fn items_move_in_and_out_of_folders() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let chars = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + let hero = folder(&run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": chars}))); + let v = run(&mut s, "library.move", json!({"items": [{"symbol": ball}, {"symbol": star}], "to": hero})); + assert_eq!(v["moved"], 2); + assert_eq!(path(&s, ball), "Characters/Hero/Ball"); + // Out again, one step for the whole move. + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null})); + assert_eq!(path(&s, ball), "Ball"); + s.undo().unwrap(); + assert_eq!(path(&s, ball), "Characters/Hero/Ball"); + // A folder moves with what it holds, but never into itself. + let props = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"}))); + run(&mut s, "library.move", json!({"items": [{"folder": hero}], "to": props})); + assert_eq!(path(&s, star), "Props/Hero/Star"); + assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": hero})).contains("inside itself")); + assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": props})).contains("inside itself")); + // A name clash stops the move and leaves everything where it was. + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null})); + let star2 = run(&mut s, "library.duplicate", json!({"symbol": star, "name": "Ball"})); + let before = s.doc.library_tree.clone(); + let e = err(&mut s, "library.move", json!({"items": [{"symbol": star}, {"symbol": star2["symbol"]}], "to": null})); + assert!(e.contains("already has an item named “Ball”"), "{e}"); + assert_eq!(s.doc.library_tree, before); + assert!(err(&mut s, "library.move", json!({"items": [{"symbol": ball}]})).contains("'to'")); + assert!(err(&mut s, "library.move", json!({"items": [{"symbol": 424_242}], "to": null})).contains("no symbol")); +} + +#[test] +fn folders_survive_save_and_open() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = Session::new(crate::format::from_json(&text).unwrap()); + assert_eq!(path(&back, ball), "Characters/Ball"); + assert_eq!(back.doc.library_tree, s.doc.library_tree); + assert!(back.doc.next_id > f); +} + +#[test] +fn duplicates_are_named_after_their_original() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let a = run(&mut s, "library.duplicate", json!({"symbol": ball})); + assert_eq!(a["name"], "Ball copy"); + let b = run(&mut s, "library.duplicate", json!({"symbol": ball})); + assert_eq!(b["name"], "Ball copy 2"); + assert_eq!(path(&s, a["symbol"].as_u64().unwrap()), "Props/Ball copy"); + assert!(err(&mut s, "library.duplicate", json!({"symbol": ball, "name": "ball COPY"})).contains("already has")); + assert!(err(&mut s, "library.duplicate", json!({"symbol": 424_242})).contains("no symbol")); + assert_eq!(instances(&s, a["symbol"].as_u64().unwrap()), 0, "a copy isn't placed"); + s.undo().unwrap(); + assert!(s.doc.symbol(SymbolId(b["symbol"].as_u64().unwrap())).is_none()); +} + +#[test] +fn swap_symbol_keeps_everything_but_the_symbol() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let el = run(&mut s, "library.place", json!({"symbol": ball, "x": 100, "y": 50}))["element"].as_u64().unwrap(); + run(&mut s, "symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"})); + run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 30})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]})); + run(&mut s, "element.rename", json!({"name": "hero"})); + let find = |s: &Session| s.elements_on(s.layer).iter().find(|e| e.id.0 == el).map(|e| (**e).clone()).unwrap(); + let before = find(&s); + let v = run(&mut s, "element.swap_symbol", json!({"symbol": star})); + assert_eq!(v["swapped"], 1); + let after = find(&s); + assert_eq!((after.transform, after.color, &after.name), (before.transform, before.color, &before.name)); + match (&before.kind, &after.kind) { + (ElementKind::Symbol { symbol: a, loop_mode: la, filters: fa, blend: ba, .. }, ElementKind::Symbol { symbol: b, loop_mode: lb, filters: fb, blend: bb, .. }) => { + assert_eq!((a.0, b.0), (ball, star)); + assert_eq!((la, fa, ba), (lb, fb, bb)); + } + _ => panic!("still an instance"), + } + assert_eq!(s.selection.on(s.layer).first().map(|e| e.0), Some(el), "it stays selected"); + assert!(err(&mut s, "element.swap_symbol", json!({"symbol": 424_242})).contains("no symbol")); + assert!(err(&mut s, "element.swap_symbol", json!({})).contains("'symbol'")); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("element.swap_symbol", &json!({"symbol": ball})).is_err(), "nothing selected"); + s.undo().unwrap(); + assert!(matches!(find(&s).kind, ElementKind::Symbol { symbol, .. } if symbol.0 == ball)); +} + +#[test] +fn deleting_asks_when_it_takes_uses_or_folder_contents() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + assert!(instances(&s, star) > 0, "the sample places Star (inside Ball too)"); + // An unused item goes without asking. + let copy = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + let p = json!({"items": [{"symbol": copy}]}); + assert!(s.confirmation("library.delete", &p).is_none()); + run(&mut s, "library.delete", p); + assert!(s.doc.symbol(SymbolId(copy)).is_none()); + // A used one asks (undoable tier), and its instances go everywhere, inside symbols too. + let p = json!({"items": [{"symbol": star}]}); + let c = s.confirmation("library.delete", &p).expect("asks"); + assert!(!c.irreversible && c.message.contains("used") && c.message.contains("undo"), "{c:?}"); + run(&mut s, "library.delete", p); + assert_eq!(instances(&s, star), 0); + assert!(s.doc.symbol(SymbolId(ball)).is_some()); + s.undo().unwrap(); + assert!(instances(&s, star) > 0); + // A folder that holds items asks, and takes them with it. + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Old"}))); + let inner = folder(&run(&mut s, "library.new_folder", json!({"name": "Older", "parent": f}))); + let spare = run(&mut s, "library.duplicate", json!({"symbol": ball}))["symbol"].as_u64().unwrap(); + run(&mut s, "library.move", json!({"items": [{"symbol": spare}], "to": inner})); + let p = json!({"items": [{"folder": f}]}); + let c = s.confirmation("library.delete", &p).expect("asks"); + assert!(c.title.contains("folder") && c.message.contains("holds 2 items"), "{c:?}"); + let v = run(&mut s, "library.delete", p); + assert_eq!((v["deleted"].as_u64(), v["folders"].as_u64()), (Some(1), Some(2))); + assert!(s.doc.library_tree.is_empty() && s.doc.symbol(SymbolId(spare)).is_none()); + // An empty folder goes without asking. + let empty = folder(&run(&mut s, "library.new_folder", json!({}))); + assert!(s.confirmation("library.delete", &json!({"items": [{"folder": empty}]})).is_none()); + assert!(err(&mut s, "library.delete", json!({"items": []})).contains("nothing")); + assert!(err(&mut s, "library.delete", json!({"items": [{"folder": 1}]})).contains("no folder")); +} + +#[test] +fn deleting_a_bitmap_or_a_sound_takes_its_uses() { + let mut s = Session::new(sample::demo()); + let id = BitmapId(s.doc.alloc_id()); + let mut px = Vec::new(); + for _ in 0..4 { + px.extend_from_slice(&[255, 0, 0, 255]); + } + let bytes = anicraft_render::encode_png(2, 2, &px).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(id, "red.png", bytes).unwrap())); + let el = run(&mut s, "library.place", json!({"bitmap": id.0}))["element"].as_u64().unwrap(); + let item = LibraryItem::Bitmap(id); + assert_eq!(s.doc.library_uses().get(&item), Some(&1)); + // Smoothing toggles, is one undo step, and is kept by the file. + assert_eq!(run(&mut s, "library.set_smoothing", json!({"bitmap": id.0}))["smoothing"], false); + let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap(); + assert!(!back.bitmap(id).unwrap().smoothing); + s.undo().unwrap(); + assert!(s.doc.bitmap(id).unwrap().smoothing); + assert!(!crate::format::to_json(&s.doc).unwrap().contains("smoothing"), "the default is written as nothing"); + run(&mut s, "library.delete", json!({"items": [{"bitmap": id.0}]})); + assert!(s.doc.bitmap(id).is_none()); + assert!(s.elements_on(s.layer).iter().all(|e| e.id.0 != el), "the placed bitmap goes with it"); + assert!(err(&mut s, "library.set_smoothing", json!({"bitmap": id.0})).contains("no bitmap")); +} + +#[test] +fn unused_items_are_listed_and_deleted_after_asking() { + let mut s = Session::new(sample::demo()); + let star = sym(&s, "Star"); + assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([])); + assert!(s.confirmation("library.delete_unused", &json!({})).is_none()); + let a = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + let b = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + // In Library order: each copy sits right after its original, so the later one comes first. + assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([{"symbol": b}, {"symbol": a}])); + let c = s.confirmation("library.delete_unused", &json!({})).expect("asks"); + assert!(c.message.contains("these 2 items") && c.message.contains("Star copy"), "{c:?}"); + let v = run(&mut s, "library.delete_unused", json!({})); + assert_eq!(v["deleted"], 2); + assert!(s.doc.symbol(SymbolId(a)).is_none() && s.doc.symbol(SymbolId(star)).is_some()); + s.undo().unwrap(); + assert!(s.doc.symbol(SymbolId(a)).is_some()); +} + +#[test] +fn the_listing_has_paths_kinds_and_uses() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let v = run(&mut s, "library.items", json!({})); + assert_eq!(v["folders"], json!([{"folder": f, "name": "Characters", "parent": null, "path": "Characters"}])); + let b = v["items"].as_array().unwrap().iter().find(|i| i["symbol"] == ball).unwrap(); + assert_eq!((b["path"].as_str(), b["folder"].as_u64(), b["kind"].as_str(), b["unused"].as_bool()), (Some("Characters/Ball"), Some(f), Some("graphic"), Some(false))); + assert!(b["uses"].as_u64().unwrap() > 0); + assert_eq!(v["unused"], 0); +} + +#[test] +fn convert_to_symbol_picks_a_free_name() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let first = run(&mut s, "modify.convert_to_symbol", json!({})); + assert_eq!(first["name"], "Symbol 1"); + run(&mut s, "library.rename", json!({"symbol": first["symbol"], "name": "Symbol 2"})); + run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10})); + let second = run(&mut s, "modify.convert_to_symbol", json!({})); + assert_eq!(second["name"], "Symbol 3", "“Symbol 2” is taken"); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c85b61fb..fe754a44 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -513,7 +513,7 @@ fn save_load_round_trip() { /// Adversarial params for every command: must return Ok or Err, never panic. #[test] fn panic_hunt_every_command() { - let hostile: Vec = vec![ + let mut hostile: Vec = vec![ Value::Null, json!({}), json!([]), @@ -691,7 +691,22 @@ fn panic_hunt_every_command() { in_symbol.execute(id, &p).unwrap(); } assert_eq!(in_symbol.editing.len(), 1, "the fuzz starts inside a symbol"); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol] { + // Library folders, nested, with items in them (ADR 0050); the fuzz moves, renames and + // deletes them, folders into themselves, names that clash or hold a slash. + let mut library = Session::new(sample::demo()); + let outer = library.execute("library.new_folder", &json!({"name": "Characters"})).unwrap()["folder"].as_u64().unwrap(); + let inner = library.execute("library.new_folder", &json!({"name": "Hero", "parent": outer})).unwrap()["folder"].as_u64().unwrap(); + let ball = library.doc.library.first().map(|x| x.id.0).unwrap(); + library.execute("library.move", &json!({"items": [{"symbol": ball}], "to": inner})).unwrap(); + library.execute("library.duplicate", &json!({"symbol": ball})).unwrap(); + hostile.extend([ + json!({"items": [{"folder": outer}], "to": inner, "folder": outer, "name": "Hero", "parent": inner, "confirm": true}), + json!({"items": [{"folder": inner}, {"symbol": ball}, {"folder": inner}], "to": null, "folder": inner, "name": "a/b", "symbol": ball}), + json!({"items": [{"symbol": ball, "folder": outer}, "x", {"sound": u64::MAX}], "to": u64::MAX, "parent": "x", "name": " "}), + json!({"items": (0..200).map(|i| json!({"folder": i})).collect::>(), "to": outer, "symbol": ball, "name": "x".repeat(300), "on": "x", "bitmap": 1}), + json!({"items": [{"symbol": ball}], "to": outer, "symbol": ball, "name": "Ball copy", "confirm": true}), + ]); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, library] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -713,6 +728,10 @@ fn panic_hunt_every_command() { let voices = anicraft_doc::sound::voices(&s.doc, 8000); let mut out = vec![0.0; 2 * 4096]; anicraft_doc::audio::mix(&voices, 8000, Default::default(), 0, &mut out); + // ...and its Library tree stays whole: nothing a load would have to repair. + let mut loaded = s.doc.clone(); + loaded.sanitize(); + assert_eq!(loaded.library_tree, s.doc.library_tree); } } From 18b07fffe0424f38cb424a27b1a1176276350ce4 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:41:49 -0700 Subject: [PATCH 030/402] feat(render): bitmaps without Allow Smoothing keep hard pixel edges in the oracle, the GPU stage, SVG and HTML (M2) --- crates/doc/src/eval.rs | 8 ++++++ crates/gpu/src/binning.rs | 7 ++--- crates/gpu/src/fine.wgsl | 10 +++++-- crates/gpu/src/lib.rs | 1 + crates/gpu/src/tests.rs | 7 +++++ crates/render/src/html.rs | 3 +++ crates/render/src/html/canvas.js | 4 +++ crates/render/src/html_tests.rs | 9 +++++++ crates/render/src/lib.rs | 3 ++- crates/render/src/paint.rs | 46 +++++++++++++++++++++++++++----- crates/render/src/svg.rs | 20 ++++++++------ 11 files changed, 97 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 9fbf3a82..a543eb38 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -37,6 +37,9 @@ pub struct DisplayItem { pub group: Option, /// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied). pub image: Option>, + /// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050); + /// off, each pixel is a hard-edged square. + pub smooth: bool, } /// Back-to-front list of shapes. @@ -440,6 +443,10 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut 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(), @@ -456,6 +463,7 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut guide, group: cx.group, image: None, + smooth: true, }), ElementKind::Camera => {} ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => { diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index c944a57d..be61e540 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -336,8 +336,8 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let m = inv.m; (RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]]) } - // The oracle's bilinear sample of a bitmap (crates/render/src/paint.rs › sample). - (Shader::Bitmap { inv, pixels, repeat, fx }, _) => { + // The oracle's sample of a bitmap (crates/render/src/paint.rs › sample). + (Shader::Bitmap { inv, pixels, repeat, fx, smooth }, _) => { if pixels.width == 0 || pixels.height == 0 { (SOLID, [[0.0; 4]; 4]) } else { @@ -351,7 +351,8 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result }; let m = inv.m; let (k, alpha, tint, keep) = colour_effect(fx); - (BITMAP, [[u(slot as u32), u(u32::from(*repeat)), 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)]]) + // 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)]]) } } // `prepare_scene` never hands these over; draw nothing rather than guess. diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 60ead56f..a9f40943 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -160,14 +160,17 @@ fn rem_euclid(u: f32, n: f32) -> f32 { return select(r, r + n, r < 0.0); } -// The oracle's bilinear sample of a bitmap at pixel centre `p` (paint.rs › sample). +// 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 { let h0 = paints[base]; let m = paints[base + 1u]; let n = paints[base + 2u]; let tint = paints[base + 3u]; let slot = bitcast(h0.x); - let repeat = bitcast(h0.y) != 0u; + let flags = bitcast(h0.y); + let repeat = (flags & 1u) != 0u; + let nearest = (flags & 2u) != 0u; let size = vec2(i32(bitcast(h0.z)), i32(bitcast(h0.w))); let w = f32(size.x); let h = f32(size.y); @@ -182,6 +185,9 @@ fn bitmap(base: u32, p: vec2) -> vec4 { } else if u < 0.0 || v < 0.0 || u >= w || v >= h { return vec4(0.0); } + if nearest { + return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, n, tint); + } let fx_ = u - 0.5; let fy_ = v - 0.5; let x0 = floor(fx_); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ce7251c2..4d814c63 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -376,6 +376,7 @@ impl GpuRenderer { guide: false, group: None, image: None, + smooth: true, }; let solid = |x: f32, c: Rgba| item(Path::rect(x, 2.0, 8.0, 16.0), Paint::Solid(c)); let mut bitmap = item(Path::rect(2.0, 18.0, 20.0, 2.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::scale(3.0, 1.0) }); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 005fcf68..f59b0a6a 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -31,6 +31,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem { guide: false, group: None, image: None, + smooth: true, } } @@ -734,6 +735,12 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0); let dl = DisplayList { items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; out.push(("bitmap masked and multiplied", dl, view(80, 60, white))); + // Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated. + let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned); + hard.smooth = false; + let mut hard_tiled = bitmap_item(Path::ellipse(50.0, 40.0, 45.0, 35.0), &c, true, Affine::scale(4.0, 3.0)); + hard_tiled.smooth = false; + out.push(("bitmaps without smoothing", list(vec![hard_tiled, hard]), view(100, 80, white))); out } diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index d8716d93..21cb4b25 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -354,6 +354,9 @@ impl<'a> Bake<'a> { self.images.push(format!("data:image/png;base64,{}", base64_encode(&b.png))); } let mut o = json!({"b": i, "rep": repeat}); + if !b.smoothing { + o["px"] = json!(true); + } if let Some(m) = matrix(m) { o["m"] = m; } diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 7858c20f..6cda20cf 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -153,7 +153,11 @@ g.globalAlpha = bitmap ? Math.min(Math.max(it.c[0], 0), 1) : 1; set(g, it.m); g.fillStyle = style; + // A bitmap without Allow Smoothing keeps hard pixel edges (ADR 0050). + const hard = bitmap && movie.paints[it.f].px === true; + if (hard) g.imageSmoothingEnabled = false; g.fill(path, it.eo ? "evenodd" : "nonzero"); + if (hard) g.imageSmoothingEnabled = true; g.globalAlpha = 1; } } diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 015a5f76..84b22ce7 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -548,6 +548,15 @@ fn bitmaps_and_sounds_are_embedded_once() { assert_eq!(js.eval("P.start().sounds"), json!([[0, "event", 1, false, 1, 1, null]])); let silent = movie(&doc, &HtmlOptions { sound: false, ..Default::default() }); assert_eq!((silent.stats.sounds, silent.json["timelines"][0].get("snd")), (0, None)); + // A bitmap without Allow Smoothing says so; the page draws it with hard pixel edges, and + // an SVG frame marks its image pixelated (ADR 0050). + if let Some(b) = doc.bitmaps.first_mut() { + Arc::make_mut(b).smoothing = false; + } + let hard = movie(&doc, &HtmlOptions::default()); + assert_eq!(hard.json["paints"][0], json!({"b": 0, "rep": true, "m": [2, 0, 0, 2, 0, 0], "px": true})); + let svg = crate::svg::to_svg(&anicraft_doc::evaluate(&doc, 0), &doc.stage); + assert!(svg.contains("image-rendering=\"pixelated\""), "{svg}"); } #[test] diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b79f4e11..38fdcf78 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -808,7 +808,7 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { }); if let Some(fill) = &item.fill { let polys: Vec> = lines.into_iter().map(|l| l.points).collect(); - push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref())); + push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref()).smoothed(item.smooth)); } if let Some((polys, shader)) = stroke { push(polys, FillRule::NonZero, shader); @@ -893,6 +893,7 @@ mod tests { guide: false, group: None, image: None, + smooth: true, } } diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index f33175fe..4b675cf9 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -18,8 +18,9 @@ pub enum Shader { Solid(Premul), Linear { inv: Affine, start: Vec2, dir: Vec2, lut: Box<[Premul; LUT]> }, Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> }, - /// Bilinear samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid. - Bitmap { inv: Affine, pixels: Arc, repeat: bool, fx: ColorEffect }, + /// 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 }, /// 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 }, @@ -75,7 +76,7 @@ impl Shader { } (Paint::Bitmap { repeat, matrix, .. }, Some(inv)) => match (image, matrix.inverse()) { // Pixel → shape space → image pixels. - (Some(px), Some(to_image)) => Shader::Bitmap { inv: to_image.mul(&inv), pixels: px.clone(), repeat: *repeat, fx: *fx }, + (Some(px), Some(to_image)) => Shader::Bitmap { inv: to_image.mul(&inv), pixels: px.clone(), repeat: *repeat, fx: *fx, smooth: true }, // A collapsed image matrix shows nothing. (Some(_), None) => Shader::Solid([0.0; 4]), (None, _) => Shader::Solid(premultiply(fx.apply(paint.primary_color()))), @@ -84,6 +85,14 @@ impl Shader { } } + /// This shader with a bitmap's Allow Smoothing (other shaders are unchanged). + pub fn smoothed(mut self, on: bool) -> Shader { + if let Shader::Bitmap { smooth, .. } = &mut self { + *smooth = on; + } + self + } + #[inline] pub fn is_solid(&self) -> Option { match self { @@ -104,7 +113,7 @@ impl Shader { Shader::Solid(c) => *c, Shader::Linear { inv, start, dir, lut } => lookup(lut, (inv.apply(p) - *start).dot(*dir)), Shader::Radial { inv, center, inv_radius, lut } => lookup(lut, (inv.apply(p) - *center).length() * inv_radius), - Shader::Bitmap { inv, pixels, repeat, fx } => sample(pixels, inv.apply(p), *repeat, fx), + Shader::Bitmap { inv, pixels, repeat, fx, smooth } => sample(pixels, inv.apply(p), *repeat, *smooth, fx), Shader::Image { data, x0, y0, w } => { let (dx, dy) = (x - x0, y - y0); if dx < 0 || dy < 0 || dx as usize >= *w { @@ -116,9 +125,10 @@ impl Shader { } } -/// A bilinear sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), with the -/// colour effect applied and premultiplied. Outside a non-repeating bitmap: transparent. -fn sample(px: &Pixels, q: Vec2, repeat: bool, fx: &ColorEffect) -> Premul { +/// 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 { 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]; @@ -130,6 +140,10 @@ fn sample(px: &Pixels, q: Vec2, repeat: bool, fx: &ColorEffect) -> Premul { } else if u < 0.0 || v < 0.0 || u >= w || v >= h { return [0.0; 4]; } + if !smooth { + let c = px.at(u.floor() as i64, v.floor() as i64); + return premultiply(fx.apply(Rgba::new(c[0], c[1], c[2], c[3]))); + } let (fx_, fy_) = (u - 0.5, v - 0.5); let (x0, y0) = (fx_.floor(), fy_.floor()); let (tx, ty) = (fx_ - x0, fy_ - y0); @@ -168,6 +182,24 @@ mod tests { assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02); } + #[test] + fn bitmaps_without_smoothing_keep_hard_pixel_edges() { + // A 2×1 image, black then white, drawn 10× larger: smoothed, the middle is a ramp; + // 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); + 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]); + assert_eq!(hard.at(0, 0), [0.0, 0.0, 0.0, 1.0]); + 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()); + } + #[test] fn bitmaps_sample_bilinear_once_or_tiled() { // 2×1: black, white. diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 4859cb31..55ea01dc 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -28,7 +28,7 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { let mut body = String::new(); let mut grad = 0usize; // Each bitmap is embedded once (by its pixels), then used by every fill that shows it. - let mut images: Vec<(usize, String)> = Vec::new(); + let mut images: Vec<(usize, bool, String)> = Vec::new(); // Clips, in order (a parent always precedes its children; anything else clips all). for (i, parent) in dl.clip_parents.iter().enumerate() { @@ -82,7 +82,7 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { continue; } if let Some(fill) = &item.fill - && let Some(paint) = paint_attr(fill, &item.transform, &item.color, &mut defs, &mut grad, item.image.as_ref(), &mut images) + && let Some(paint) = paint_attr(fill, &item.transform, &item.color, &mut defs, &mut grad, item.image.as_ref().map(|px| (px, item.smooth)), &mut images) { let _ = write!(body, "", rule_attr("fill-rule", item.fill_rule)); } @@ -340,7 +340,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>, images: &mut Vec<(usize, String)>) -> Option { +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 { let stops = match paint { Paint::Solid(c) => { let c = fx.apply(*c).sanitized(); @@ -351,15 +351,17 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n // 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.) - let px = image?; + // 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; - let img_id = match images.iter().find(|(k, _)| *k == key) { - Some((_, id)) => id.clone(), + let img_id = match images.iter().find(|(k, sm, _)| *k == key && *sm == smooth) { + Some((_, _, id)) => id.clone(), None => { let png = crate::encode_png(px.width, px.height, &px.rgba).ok()?; let id = format!("img{}", images.len()); - let _ = write!(defs, "", px.width, px.height, anicraft_doc::base64_encode(&png)); - images.push((key, id.clone())); + let look = if smooth { "" } else { " image-rendering=\"pixelated\"" }; + let _ = write!(defs, "", px.width, px.height, anicraft_doc::base64_encode(&png)); + images.push((key, smooth, id.clone())); id } }; @@ -435,6 +437,7 @@ mod tests { guide: false, group: None, image: None, + smooth: true, } } @@ -554,6 +557,7 @@ mod group_tests { guide: false, group: g, image: None, + smooth: true, }; let dl = DisplayList { items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }; let svg = to_svg(&dl, &Stage { width: 4, height: 4, fps: 24.0, background: Rgba::WHITE }); From 721e1ddffb1abe97da41119699342a45b02969fe Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:43:44 -0700 Subject: [PATCH 031/402] feat(import): XFL library folders and Allow Smoothing come across; the checker golden is drawn unsmoothed as its file asks (M2) --- crates/xfl/src/import.rs | 28 ++++++++++++++++++ crates/xfl/src/tests.rs | 16 ++++++++-- crates/xfl/tests/corpus.rs | 2 +- .../tests/corpus/bitmaps/golden/frame-000.png | Bin 9064 -> 7962 bytes 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index e97c96c5..870fd762 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -707,6 +707,9 @@ impl<'a> Builder<'a> { match bitmap { Some(mut b) => { b.id = BitmapId(self.doc.alloc_id()); + // Animate leaves out the default (smoothing on in current versions). + b.smoothing = item.bool("allowSmoothing").unwrap_or(true); + self.place_in_folder(name, anicraft_doc::LibraryItem::Bitmap(b.id)); self.bitmaps.insert(name.to_string(), b.id); self.doc.bitmaps.push(Arc::new(b)); } @@ -801,6 +804,27 @@ impl<'a> Builder<'a> { }; let short = name.rsplit('/').next().unwrap_or(&name).to_string(); self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, timeline })); + self.place_in_folder(&name, anicraft_doc::LibraryItem::Symbol(id)); + } + } + + /// The Library's folders (``, so empty ones come across too), each a path such as + /// `Characters/Hero` (ADR 0050). + fn register_folders(&mut self, root: &X) { + for f in root.list("folders").iter().filter(|f| f.name == "DOMFolderItem").take(anicraft_doc::library::MAX_FOLDERS) { + if let Some(path) = f.attr("name") { + self.doc.ensure_folder_path(path); + } + } + } + + /// Puts `item` in the folder its library name's path names (`Characters/Ball` is in + /// `Characters`), made if `` didn't list it. + fn place_in_folder(&mut self, name: &str, item: anicraft_doc::LibraryItem) { + if let Some((dir, _)) = name.rsplit_once('/') + && let Some(f) = self.doc.ensure_folder_path(dir) + { + self.doc.place_entry(anicraft_doc::LibraryEntry::Item(item), Some(f)); } } } @@ -837,6 +861,7 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0), background: color(&root, "backgroundColor", "__none"), }; + b.register_folders(&root); b.register_bitmaps(&root)?; b.register_symbols(&root)?; b.build_symbols(); @@ -847,6 +872,9 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do let timeline = b.timeline(tl); b.doc.scenes.push(Arc::new(Scene { name, timeline })); } + if !b.doc.library_tree.folders.is_empty() { + b.report.keep("library folders"); + } if b.doc.scenes.is_empty() { let timeline = Timeline { layers: vec![Arc::new(Layer::new(LayerId(b.doc.alloc_id()), "Layer 1"))] }; b.doc.scenes.push(Arc::new(Scene { name: "Scene 1".into(), timeline })); diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 0cfb1d90..a8ea11f3 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -101,7 +101,9 @@ fn stage_layers_frames_and_tweens() { // Frame scripts, on the scene's frames and inside symbols, are kept verbatim (ADR 0013 // tier 1); these are in the subset that runs (tier 2). assert_eq!(report.runs.get("frame scripts in ActionScript 3.0"), Some(&2)); - assert!(report.kept.is_empty(), "{report:?}"); + // The symbol's path puts it in a Library folder (ADR 0050). + assert_eq!(report.kept.keys().collect::>(), ["library folders"], "{report:?}"); + assert_eq!(doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(doc.library[0].id))), "Characters/Ball"); assert!(report.skipped.keys().all(|k| !k.contains("script")), "{report:?}"); assert_eq!(ball.keyframes[1].script.as_ref().and_then(|s| s.source()).map(|s| s.text.as_str()), Some("stop();")); let inner = &doc.library[0].timeline.layers[0].keyframes[0]; @@ -257,9 +259,10 @@ fn png_2x1() -> Vec { } const BITMAP_DOC: &str = r##" + - + @@ -309,6 +312,15 @@ fn bitmaps_come_across_when_their_image_is_png_or_jpeg() { // The renderer gets the pixels with the items. let list = evaluate(&doc, 0); assert_eq!(list.items.iter().filter(|i| i.image.is_some()).count(), 3); + // Library folders come across (ADR 0050): the item's path places it, empty ones are kept, + // and Allow Smoothing is read (on unless the file turns it off). + let path = |i| doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Bitmap(i))); + assert_eq!((path(doc.bitmaps[0].id).as_str(), path(doc.bitmaps[1].id).as_str()), ("Art/photo.png", "packed.png")); + let folders: Vec = doc.library_tree.folders.iter().map(|f| doc.entry_path(anicraft_doc::LibraryEntry::Folder(f.id))).collect(); + assert_eq!(folders, ["Art", "Empty", "Empty/Inner"]); + assert_eq!(report.kept.get("library folders"), Some(&1)); + assert_eq!((doc.bitmaps[0].smoothing, doc.bitmaps[1].smoothing), (true, false)); + assert!(list.items.iter().any(|i| i.image.is_some() && !i.smooth)); } /// A square (0, 0)–(100, 100) shape-tweening to a triangle (200, 0), (300, 50), (200, 100), diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index 44e019d6..87843e84 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -83,7 +83,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)])] = &[("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)])]; +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)])]; /// The frame scripts each package brings that run (ADR 0013 tier 2: in the subset). const RUNS: &[(&str, &[(&str, usize)])] = &[ diff --git a/crates/xfl/tests/corpus/bitmaps/golden/frame-000.png b/crates/xfl/tests/corpus/bitmaps/golden/frame-000.png index 62510fb12cf83e506b874e92c672eab1f962ec35..6a80390f5284e2feda2c7e4621045839ebb2a3c7 100644 GIT binary patch literal 7962 zcmd5>2~<;O77nr~0)k5gMGYbqt(HXG2P9xoKpj(S9a>8XP+M0-iWS0=$D&0i77YoDLX;&(DJlg?*pg8M5(0#nm-ihH~C4AegsQYjwX zafDZq@$K5LF8bHyJpI~!n3=LBi)p{mxYu?{-v&;%3**~b^dZY>pyVFfp{5V3Olu$efdY{d%{;a6l?tPZD&dt%Ee=d5Ru1{J9 z+La*tG30V5x}!t>MM9{(JnXcsQ?yc5qGT+RhYkPvJ@%hVC0>dCvaD`Dfue>@=JuSo zl@+tACK8K`WTu_U+idbRfeb?ve1p;o?blzrUfr9-M<3`iIRW#3FyvW>KkU&_Tthyv1<|!WYo=mmco}d1M-8`(wwwA3JbQnu|b^y-xsO zhWKKQ5ft^&O`75|O7$&NW4L*dd;Pve(w~rsqjjdXW{Gk7b3<;CR5m0YDC3~v38q~6 z#@M5v%HIHOnJMjwAxgEjEVuZ0>RPqgUB?lGm`nVp&6#zD79m|(=p+&^0+INRRB-bI zFXv(?Jp@r5U=`yw)(d=$w>#H!rYTO^*57C^H?%xv7#U@Y-=a#R>*b?~rEi;hZR`3w z=*z(BZzKHHK}u4Cm!012mTJ6o2RX&y9jW@Yn z8`)NJRZ(o<)5iC5cwS||-+$aownI<|>N1E9CW7|~Q0;VISTzR}0A}W*lb%Wg^)K)% zd=WB1$H16p5_v5}SFpFuzdnEJrJ3%=_eE;ctJzkti4K47cm>=gV5B&jZ>e)kg*~C) zT+j&m{ea!_fZ{Y23&%1pnHbDEY`B!ru{ld|w~kqKI&(3>#n1Slt*T3n8TS2P#^P7} zt6^$_1K$ouIGC1RgY*?mPtO&Xm-E!_paLaBNgmwz7?udjGGW$bu4bh|;ure^9xTp7uXh&`<+-*-V z7(&_=LSDeKCbuf5qra7mCmhi;^l*HbikvdPp*@N~M)L(Da1J0Wj^33nhJ52CPN-p9 zz&AFT(#;X@@HvwYmLJwx<}gEY)_g`;zLc=*6NA9oWTf?7f*f>YX+MwEW{9$aPQ?W^ zsVy93SZ*;ZJ*avnC10L;+?NLhg|8cQ^g{tsF`pxu32KLKQixFFDEhh6#z6 z3T^DYwv9$BZqoue(<6)4n^{TE(Xe+%xR~XDda%iWgh~cmf5Mv`!cFmHUTNglg}kPf z4np%%Zp+F#Hv_Vjvtwf_a@f2DINwjm-$g57EwJDl;bExrjcH32eRHDYE>Aebep zO`jnt#}@9B5vEw_=oB?058dc49m*Kf=HVpZ180x+h<;Y4-wKG~7X2I0APXF=S41hs zrx{GmCPYnm|8Xdb7Ek&5o{|?iVZK!eN>a^vXN=JchOB=P8ib`AHAu=7#8q+gw?s{t zvahx|_X(vXNj}r%cA?K`YF{f+tPd&B@b3_>B9d^-fmJRa^40$3UNeWD!XD6gQiYh) zK$THqbrSW*Y~$^TTZ>kq^89ma=jbf9`z@sS|GL3Awf&By;2v9an(P-J6D8S6uUT@- zXQX~S^^d%jj?z@*ka-Ir&G}lZ!0>Zj4XJ@U+Ym;Qm;MM4kf#-`MR0~lO!mB|%~GL1 z$^tF+`qt;q+u7?`-X@8*lrZAzM?MS$sp5rVff88|*v4?0c0h(*(-_!Nhf3%1ENyl; zQ0f}?jc=%29rx6R`>-fK1EVxx@CN(sb>zRzDc6tzzb-4fCKnnOwu^fU(KRl1b`*bQB zV)1o4c_;23UfWp12}}LY@g-AY>98qsnt;80#ZkfNqF=?z*cObHA!lc#fBA)a=u)c4LPVKoa2+wW@=H-_0=PN~{Nx(b@Cj?5X*PJ%?^;d9A<#(y>8 zgSKY?{kNr(|paX97>iIFhZz-)bWY0W&Go-Qgz)=IC z<{fRhIf|a(a0+$=hV5vuY8V*T>kMS$##A-kfo8@)-j= zM=X_bEYmwL3zJcVbyzQ-&<7gP=umhE(*joyaOM1U$kcUtIXy?FAM1uYj;6+*xl>WtA1KTsR zRg&Olfgwl+KeV0IN=cq?&a%_K+Lw(dG&A`Y_VRFG@cq}Em{txO72}?h+{5*uTCCV zL2+kZPW~hOa4=d+Y$8@YFe-$Z9)JK%{Hr7DJTP zfxpv4Otx`WU%DJ~$70ll^(&q{ZntWCN-#dTDo&FyO>M*CQPAaO9Aj43t*jde8Q6^c z`BNEU)MkVj6#`S)R)DJMN&pB=_xf>!azRf_A2o7UdL~B8lX$ZDJJFiSFGdA0VJsO2 z&eOYRG$(Cs+k2W8!lyo9|By^l{es%6_4iG9XLu1&HJQ@2pL=$>MtN_6QJ)Cy&TYU` zkt9+*X2N9E{*o%Xf0h!7yTWi4$Pj7mm732xGR~i(AJ1x}Ov(1Yc=b_Q6(%if%<*gf zd8uEUOTbOUUhUF%HM-LrRb{oIygC_8-9=Ed`<|78tYx4XiuEGx4p}zAbc&u9Q KdU2&s^#1@|f_nh~ literal 9064 zcmdT~3se*5)(rxpA|hZ7g<|l5)K(2*5iEf~Yefo@_Ig`wNHtvn?nwlcA!`oBLrjxvisWHWu2&r=xoa(1R)$O}w(K&Tdc5^d6j{PBT* zgY`JoPNIqi+E|Y>?S#Sz@?t7`ot*mQn3qsU!Yt7Q@2_vTztoGR?g+yr3eRUpT5l;W2Q>`sSCq?2aHm4IiIMKBqm_9FXB$n8M*2HC z+W4Pu=RWdR#pEYy*{XP*sKFn6fYHXMNgA};d+rh9{vWBt^w?IdwmrciFvk{?Iqx zsr+_o*Zdj@vIwdCS8!fXk!dZo{dom64cII6$Y>;)mH~Tp9ymOfce$GvRVM%1zZi!H zGXE{5-DP#L8MC>bkg5(NuuoM41|Ni$O|QO;vfAN$^S-V~XfOpOJtn*{&wXaD55e5T zl7686Ok#K-QgY@D#VK^}5;AOb#yp*AyFxeq=PRjK$q(rg^Icy zIT8W4{aY>fX>*}m4o8q7G^_)Me#l05W5l|1)UAq<3ywWNVdTEHZ7W{ydYIFU2GvW2 z0ow!ipH6n2!~~Dv;p9F4z~6-hl^S_>T`&zMdjH3SUOHQQGi*0slKx{+t)w5Pb{ZS^ zUwXS`iBm(X1%J6taI*g3LTJ&h78{$E{N}mLWFPeh0DWJ_4EOz>F7|Jzx=G+vV*c|$ zA_w)gij;ep`YB@z=;1kLn~5kt#E_1`<6nBa9?3b={z{_xHS+*7P@l^mi8T)>0x5K) zN@!*8TB@IpREh2kz6q{=N~pOr6MqWb+e$KA1_@j1;o6YBvqrS{9rf2h=J5_k@0t0B zY!^{(V@(UNEk`ot(W&FJ@H*q4<_SbN<)unS>qr`z3KHhI-*NrOEdmZka{>S`9L(AU zUq;ruQZ#IE7Pci5P;GrxiKvnMZ{B|6u^1#Xlu*S_yb^rf5VbR)R?56Avo-8XGtVNPJd;SrGXyS*uHl~j4!3RU>x+P% za`8nuf#cj(Px9F}sC7slk}` zW85D#a@$3R`qawfRUA~257;&Wn0_}T$AM~-TkbTz_i6-yPTq?{{&ZzVG%Lk zXqGnC{N1wtmitp0-4EOHB6%DmoY)pW_OJujhY#&w37`d&rn~05qtcex z)jfIGQIqPo<^6ouO9CV_)KKC;ApexnG#=IcJg9yZ-)C315be^IYU)z#a2ZKpuX&M5 zj?qv16hxh{ZOROdT#G-D=;OLIvc_t6d%A!l9-gj<`Oa#Jb8HCiNeOTm-Q85Dt*Ctt z-_JkF%hTBCKrQt23)T>2;CjADF2@Kd3`wMKxB-sb0-T^&*E7vAbKN`@8`=81fvmfa z`(K;9D&+v>9u}H7QWN$d3kd_{Ma(>gvqLRFJzzM%7)de9eF8#JUu_K$T_t-bBJlm-juL>5dmFesyjJ`+g8?*>K8 z$57;i&I1Oq4*b-7%V*2J{o9Tf2x_0?vqZ*Cch}l&DRQ-OM#!vi;>avTg2`~jwv6&$ zV+7`RomqzQdWJW2Zh`04ec^F6-_OvOp5u3A1fp`vJVOwGxxnOzkpB30$z$s5Sr4v4 zjMgt8LsT2?B}X-uW9aL5TTXXLCr!^(#T-kF5AUW-s)kVBah&tFEbhFqZ47 zGd1KT|JRuPZ$mZyf)k_NDXB-iKx(bhG59FDdz6Lwb8}NSl1R^jmhDxCSQ_jo`qOU17iP`d-`yQni@vGVrxJ=1o0%6 zrp0suGprppWQ81Z-pdoRn^;%+Gvh+0&Yp=gm(agJch}+dKEImHKW*m!hDZAaeb3k# zL4`USF_y}ez+ryyMiq!yPTjkEm?h%%8gTS0*%lLlZ9{WA8Cv{d=M62BynF|)+#(MF zEndp^v%lKcFoUVOgTFgr#`C4X7OWehpMq9S&srQ3@_ueaOjlYjU+A^@y{X?Mmo~Z3 z4c-&jc=AUQFhctj*a7(8v4!n`PzXDKh$Y3a9T;s7vcdX5U>de9o;NJi;14YhiMfz_ zFXo;XJx!MOv&{L!9JlC$-ewI!o&9_Z@Qi}SX$&x$;4EV>Wa1Pf9?at(M0a0H>i&9m zL}mYKCX3d5oWEgdP5c0b4*yTwc^P@pmfGmAPpQm)-s`{eVbaU=U2jdq^e)EI;-I@< zG$IKCowl7qk zF`8ssi_91x_Vb#i2!EX@zYGaL6%#aPxd<(r zpkY;o`PT0+-?P!l_{=LtrwpJ-7`@1(91ePdfLz;m5t`Fd{pt@?C(FhWYY_^4|5WlK z?xQqi;njN!Wj+K$4@Q0wdIQL4PXwhhD3_hd<4F0gR}zUfa=zBuKsd3`{`<&^h6Jdd z8k4gtWUXZ*;1fuFA+k=&pdZ0xc1f&MxsG%j($F<>GvE~0!JVQ2n;m8NbqU!%=Ud&l zYJ&J!g0#5iMiHR)uIZB~+|7LqYNH+gOxT$Kfwk$zI#xZr*Fa9)!Rw+|{e!A3p==1& zY$Kh3;^0x46RxKsI2Vd64RPh{cjGo;#m7GkS+TKx9sP-SZJ(r<2dHlus%Q%7Yn9gz z`KPzcr<}{fWfy536hSzty;;xEAB)GGknc^!s}6Cda}^2nccDXY|1eK)#2Qwam$!!7 zAN<#;?6i@x@_TQ7vv$2@&{;Xcp;~s!yrswHXx51TGnXM{HfGj!6X+#!c~I15X(oYX z_hkotiZ@XsGZ316#mNo$!M z4aX^YJe9bE)`W@K4i2U?So69+YYijPit_{yai>p`w1)?9T|oxN{m3PinSF8k^10>0`@?=>ro>APw6z^G;+7ls(p-W zy^FPLm>mS=9C?B=sIfGu>ncY_9UQctvz%n5YD7n=mc$dZpv9U%t1aP3jTtUb=|G6@ zp#p(iG_+}dQTS?KBn@2`(Sjzv!M8bQ6Ez7)uW2p%bU6`-M|KSC(jQ%eZ*V=AzjEVl zewZMdJ3MUVSn80`UR#7q_LJ9c=3f=C`7)!LY)N$*w?9qA3SacbydAR|(IjwN+$Hz@ zmLX^~Z@Yz*4TiJ!-uj1C<Dun3Z2%5Olp9g$gP?_(r`atOXbG#^5nygcUF>U z5$BOW~zil+EVprgI#Ego6*NXBb)%6tNWx_*MKSvXZPV&vQp{MOXbb zJo4}iFc4JijK(?T2jgan`(zS#C8dJ!$0Q%Jj~<5h0XC$^bE%jU7g0 zNf;;DwGw}ES}x`~<&1o91YUJ5&8lrO(q1H;cq$tlZJq{)AR!QBBW%q#Fi zm8=%N3jzQZG#TFjyyaD3`{PG05}vwoyYu0x@v8kK^Hlh5#9mt6@w0v?V#ejJtJRh) zGcTReUez%>2mVP-V)LtnVZ_wp_~{;e9$x^LPjb>l6xVP$BBT3i{F69l$AKcY;2cH^ zhc*`pZ3Ej>1;!WJ+H7C2P+u1-Aw*`a_CyA|v!Z!hFhlNmAsa7SgyXb77Rw|3)iN~W z{^B|Ri7eB%BnUNqo9skN-HdAeplJ#7+9`Es`h4zrHO`m6Z9%js7~WuovDGe4b3k9XVQs6L%c#k9%siIXgP(~!4PI^pOh+h< zO&&PTw#k;e8t%))NiZK^fJ(4>*qcA)bfA^<8Gib^P!){TI>nCFUGB=@+5 Date: Tue, 10 Nov 2026 23:44:42 -0700 Subject: [PATCH 032/402] feat(engine): Swap Symbol inside an open symbol never nests it in itself (M2) --- crates/engine/src/cmds_library.rs | 4 ++++ crates/engine/src/library_tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index 9ff8a965..0002b8d4 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -378,6 +378,10 @@ fn swap_symbol(s: &mut Session, p: &Value) -> Result { if s.doc.symbol(to).is_none() { return Err(EngineError::State(format!("no symbol with id {}", to.0))); } + // Inside a symbol open for editing (ADR 0045), never swap in that symbol or one that holds it. + if crate::editing::would_nest(s, to) { + return Err(EngineError::State("a symbol can't be placed inside itself".into())); + } let mut swapped = 0; for e in s.selected_elements_mut()? { if let ElementKind::Symbol { symbol, .. } = &mut e.kind { diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs index 89e7d9d3..cc350a87 100644 --- a/crates/engine/src/library_tests.rs +++ b/crates/engine/src/library_tests.rs @@ -267,3 +267,19 @@ fn convert_to_symbol_picks_a_free_name() { let second = run(&mut s, "modify.convert_to_symbol", json!({})); assert_eq!(second["name"], "Symbol 3", "“Symbol 2” is taken"); } + +#[test] +fn inside_an_open_symbol_swap_never_nests_and_deleting_it_closes_it() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let outer = run(&mut s, "modify.convert_to_symbol", json!({"name": "Outer"}))["symbol"].as_u64().unwrap(); + run(&mut s, "draw.rect", json!({"x": 40, "y": 0, "w": 10, "h": 10})); + let other = run(&mut s, "modify.convert_to_symbol", json!({"name": "Other"}))["symbol"].as_u64().unwrap(); + run(&mut s, "symbol.edit", json!({"symbol": outer})); + assert_eq!(s.editing.len(), 1); + run(&mut s, "library.place", json!({"symbol": other})); + assert!(err(&mut s, "element.swap_symbol", json!({"symbol": outer})).contains("inside itself")); + // Deleting the open symbol takes the editor back to the scene. + run(&mut s, "library.delete", json!({"items": [{"symbol": outer}], "confirm": true})); + assert!(s.editing.is_empty() && s.doc.symbol(SymbolId(outer)).is_none()); +} From f9004b2e813f599954a6e63704378b0e591d51a1 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:44:55 -0700 Subject: [PATCH 033/402] docs(adr): reserve ADR 0051 for Edit Multiple Frames, complete (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..8fb94da0 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 | +| 0051 | M1 track (multi-frame editing) | Edit Multiple Frames, complete; onion skin inside symbols | From 8a2ed97981e2da9fa80d5b74775e36ec1cec9dee Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:51:24 -0700 Subject: [PATCH 034/402] feat(ui): Library folders, inline rename, drag into folders, sort, search, use counts, unused items, preview and item properties; Swap Symbol in Properties (M2) --- src/a11y.rs | 2 +- src/app.rs | 42 ++- src/library.rs | 890 +++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 3 +- src/panels.rs | 162 ++------- 5 files changed, 954 insertions(+), 145 deletions(-) create mode 100644 src/library.rs diff --git a/src/a11y.rs b/src/a11y.rs index 15318b84..6b8f29b5 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"] { + 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"] { 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 5d04f74d..6c788c05 100644 --- a/src/app.rs +++ b/src/app.rs @@ -269,19 +269,7 @@ pub struct Shot { pub const SHOT_FRAMES: u32 = 120; /// The item picked in the Library panel (view state). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LibraryItem { - Symbol(anicraft_engine::doc::SymbolId), - Bitmap(anicraft_engine::doc::BitmapId), - Sound(anicraft_engine::doc::SoundId), -} - -impl LibraryItem { - /// The first item in the Library: its first symbol, else its first bitmap, else sound. - pub fn first(doc: &anicraft_engine::doc::Document) -> Option { - doc.library.first().map(|s| LibraryItem::Symbol(s.id)).or_else(|| doc.bitmaps.first().map(|b| LibraryItem::Bitmap(b.id))).or_else(|| doc.sounds.first().map(|s| LibraryItem::Sound(s.id))) - } -} +pub use anicraft_engine::doc::LibraryItem; pub struct App { pub s: Session, @@ -317,6 +305,8 @@ pub struct App { /// Folders shown closed on the timeline (view state: not saved, not undoable). pub tl_collapsed: HashSet, pub library_sel: Option, + /// The Library panel's folders, selection, sorting, search and preview (ADR 0050). + pub library: crate::library::LibraryView, /// Text being typed on the stage. pub text_edit: Option, /// Font families on this computer, listed once on first need. @@ -460,7 +450,7 @@ impl App { let prefs = if shot_mode { prefs::Prefs::default() } else { prefs::Prefs::load() }; let keymap = keymap::Keymap::new(&prefs.shortcuts); let shortcuts = keymap.table(); - let library_sel = LibraryItem::first(&session.doc); + let library_sel = crate::library::first_item(&session.doc); let (recovery, recovery_err) = autosave::Recovery::start(shot_mode); // Text lays out with the fonts on this computer plus the embedded interface font (so new // text has the same default everywhere). Scan them now, off the UI thread. @@ -500,6 +490,7 @@ impl App { tl_last_layer: None, tl_collapsed: HashSet::new(), library_sel, + library: Default::default(), text_edit: None, font_families: None, star_points: 5, @@ -784,6 +775,22 @@ impl App { self.scan_system_fonts(); } Some("confirm") => self.request("layer.delete", json!({})), + Some(which @ ("library" | "librarymenu")) => { + // Library folders with an item inside, a copy, the item previewed (ADR 0050). + let ball = self.s.doc.library.first().map(|s| s.id); + let folder = self.run("library.new_folder", json!({"name": "Characters"})).and_then(|v| v["folder"].as_u64()); + self.run("library.new_folder", json!({"name": "Props"})); + if let (Some(ball), Some(f)) = (ball, folder) { + self.run("library.duplicate", json!({"symbol": ball.0})); + self.run("library.move", json!({"items": [{"symbol": ball.0}], "to": f})); + self.library.expanded.insert(anicraft_engine::doc::FolderId(f)); + self.library_sel = Some(LibraryItem::Symbol(ball)); + self.library.sel = vec![anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Symbol(ball))]; + } + if which == "librarymenu" { + crate::library::select_unused(self); + } + } Some(which @ ("onion" | "onionmenu")) => { // Onion skin ±5 on a frame with frames before and after it, the markers on the // ruler; with its menu open, in outlines (ADR 0047). @@ -1341,7 +1348,7 @@ impl App { if let Some(session) = restored { self.view.fit = true; self.frame_sel = None; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); self.recovery.restored(&session); let name = self.s.path.as_deref().and_then(std::path::Path::file_name).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned()); @@ -1358,7 +1365,7 @@ impl App { match id { "file.new" | "file.new_sample" | "file.open" => { self.view.fit = true; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); match v.get("report").and_then(Value::as_str) { // An imported file: say what came across and what didn't, and that saving @@ -1370,7 +1377,7 @@ impl App { "file.recover" => { self.view.fit = true; self.frame_sel = None; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.recovery.restored(v["recovered"].as_str().unwrap_or("")); let name = v["name"].as_str().unwrap_or(tr!("Untitled")); self.status_ok(if v["original_newer"].as_bool() == Some(true) { @@ -1804,6 +1811,7 @@ impl App { crate::widthtool::consume_keys(self, ctx); crate::bone_tool::consume_keys(self, ctx); } + crate::library::consume_keys(self, ctx); let mut fire: Vec<&'static str> = Vec::new(); let mut tool = None; let mut play = false; diff --git a/src/library.rs b/src/library.rs new file mode 100644 index 00000000..02b61972 --- /dev/null +++ b/src/library.rs @@ -0,0 +1,890 @@ +//! The Library panel (ADR 0050): folders, sorting and search, inline rename, drag into and out +//! of folders, multiple selection, an item preview (a symbol's first frame, a bitmap, a +//! sound's waveform with play) and the item's properties. Every change is a `library.*` +//! command; what is sorted, filtered, expanded or selected is view state, kept here. + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::theme::{T, TARGET, Type, color, font, text, with_type}; +use anicraft_engine::StateId; +use anicraft_engine::cmds_library::entry_json; +use anicraft_engine::doc::library::MAX_FOLDER_DEPTH; +use anicraft_engine::doc::{Document, FolderId, LibraryEntry, LibraryItem, SymbolKind}; +use egui::{Align2, Key, Modifiers, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use serde_json::json; +use std::collections::{HashMap, HashSet}; + +/// How the list is ordered (folders always come first, by name). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sort { + #[default] + Name, + Type, + Uses, + /// When the item came into the Library (ids grow with time). + Added, +} + +impl Sort { + const ALL: [Sort; 4] = [Sort::Name, Sort::Type, Sort::Uses, Sort::Added]; + fn label(self) -> &'static str { + match self { + Sort::Name => tr!("Name"), + Sort::Type => tr!("Type"), + Sort::Uses => tr!("Use count"), + Sort::Added => tr!("Date added"), + } + } +} + +/// What the Library panel shows and holds between frames. +#[derive(Default)] +pub struct LibraryView { + /// The selected rows (items and folders). + pub sel: Vec, + /// Where a Shift-click range starts. + anchor: Option, + pub expanded: HashSet, + pub sort: Sort, + pub descending: bool, + pub filter: String, + /// The row being renamed and the text so far; `true` until the field has taken focus. + pub renaming: Option<(LibraryEntry, String, bool)>, + /// The list was clicked last: F2 and Delete act on it (not on the stage). + pub keys: bool, + /// Where the list was drawn last frame (`None` before the first). + list_rect: Option, + uses: Option<(StateId, HashMap, HashSet)>, + preview: Option, +} + +/// The current item's preview picture, and what it was made from. +struct Preview { + key: (LibraryItem, StateId), + texture: Option, +} + +/// The first item in the Library: its first symbol, else its first bitmap, else sound. +pub fn first_item(doc: &Document) -> Option { + doc.library_items().next() +} + +/// One visible row. +struct Row { + entry: LibraryEntry, + depth: usize, + name: String, + /// What it is, for the tooltip and screen readers (“Movie clip · 24 frames”). + detail: String, + uses: Option, + open: bool, +} + +impl LibraryView { + /// Use counts and unused items, worked out once per document state. + fn counts(&mut self, s: &anicraft_engine::Session) -> (HashMap, HashSet) { + match &self.uses { + Some((st, u, n)) if *st == s.state => (u.clone(), n.clone()), + _ => { + let (u, n): (HashMap, HashSet) = (s.doc.library_uses(), s.doc.unused_items().into_iter().collect()); + self.uses = Some((s.state, u.clone(), n.clone())); + (u, n) + } + } + } + + /// Only one row selected: `e`. + fn select_only(&mut self, e: LibraryEntry) { + self.sel = vec![e]; + self.anchor = Some(e); + } +} + +fn kind_rank(doc: &Document, e: LibraryEntry) -> u8 { + match e { + LibraryEntry::Folder(_) => 0, + LibraryEntry::Item(LibraryItem::Symbol(id)) => match doc.symbol(id).map(|s| s.kind) { + Some(SymbolKind::Graphic) => 1, + Some(SymbolKind::MovieClip) => 2, + _ => 3, + }, + LibraryEntry::Item(LibraryItem::Bitmap(_)) => 4, + LibraryEntry::Item(LibraryItem::Sound(_)) => 5, + } +} + +fn raw_id(e: LibraryEntry) -> u64 { + match e { + LibraryEntry::Item(i) => i.raw(), + LibraryEntry::Folder(f) => f.0, + } +} + +fn detail(doc: &Document, e: LibraryEntry) -> String { + match e { + LibraryEntry::Folder(f) => { + let n = doc.library_children(Some(f)).len(); + trn!("Folder · {n} item", "Folder · {n} items", n) + } + LibraryEntry::Item(LibraryItem::Symbol(id)) => doc.symbol(id).map_or_else(String::new, |s| { + let n = s.timeline.frame_count(); + let frames = trn!("{n} frame", "{n} frames", n); + tr!("{kind} · {frames}", kind = crate::panels::symbol_kind_label(s.kind), frames = frames) + }), + LibraryEntry::Item(LibraryItem::Bitmap(id)) => doc.bitmap(id).map_or_else(String::new, |b| tr!("Bitmap · {width}×{height}", width = b.width, height = b.height)), + LibraryEntry::Item(LibraryItem::Sound(id)) => doc.sound(id).map_or_else(String::new, |x| tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds()))), + } +} + +/// The visible rows: folders (open ones with what they hold), then items, ordered by `sort`. +/// With a search, only matching items show, inside every folder that leads to one. +fn rows(doc: &Document, v: &LibraryView, uses: &HashMap) -> Vec { + let query = v.filter.trim().to_lowercase(); + let matches = |e: LibraryEntry| query.is_empty() || doc.entry_name(e).is_some_and(|n| n.to_lowercase().contains(&query)); + // Folders that lead to a match (searching opens them all). + let mut leads: HashSet = HashSet::new(); + if !query.is_empty() { + for e in doc.library_items().map(LibraryEntry::Item).chain(doc.library_tree.folders.iter().map(|f| LibraryEntry::Folder(f.id))) { + if matches(e) + && let Some(p) = doc.parent_of(e) + { + leads.extend(doc.folder_chain(p)); + } + } + } + let count = |e: LibraryEntry| match e { + LibraryEntry::Item(i) => uses.get(&i).copied().unwrap_or(0), + LibraryEntry::Folder(_) => 0, + }; + let mut out = Vec::new(); + // Depth-first, in order: each level is sorted, then pushed in reverse. + let mut pending: Vec<(LibraryEntry, usize)> = level(doc, v, None, &count).into_iter().rev().map(|e| (e, 0)).collect(); + while let Some((e, depth)) = pending.pop() { + if out.len() > 100_000 { + break; + } + let shown = match e { + LibraryEntry::Folder(f) => query.is_empty() || leads.contains(&f) || matches(e), + LibraryEntry::Item(_) => matches(e), + }; + if !shown { + continue; + } + let open = match e { + LibraryEntry::Folder(f) => (!query.is_empty() && leads.contains(&f)) || (query.is_empty() && v.expanded.contains(&f)), + LibraryEntry::Item(_) => false, + }; + out.push(Row { entry: e, depth, name: doc.entry_name(e).unwrap_or("").to_string(), detail: detail(doc, e), uses: matches!(e, LibraryEntry::Item(_)).then(|| count(e)), open }); + if let LibraryEntry::Folder(f) = e + && open + && depth + 1 < MAX_FOLDER_DEPTH + { + pending.extend(level(doc, v, Some(f), &count).into_iter().rev().map(|c| (c, depth + 1))); + } + } + out +} + +/// What folder `parent` holds, folders first (by name), then items in the chosen order. +fn level(doc: &Document, v: &LibraryView, parent: Option, count: &dyn Fn(LibraryEntry) -> usize) -> Vec { + let mut all = doc.library_children(parent); + let name = |e: &LibraryEntry| doc.entry_name(*e).unwrap_or("").to_lowercase(); + all.sort_by(|a, b| { + let folders = matches!(b, LibraryEntry::Folder(_)).cmp(&matches!(a, LibraryEntry::Folder(_))); + let by = match v.sort { + Sort::Name => std::cmp::Ordering::Equal, + Sort::Type => kind_rank(doc, *a).cmp(&kind_rank(doc, *b)), + Sort::Uses => count(*a).cmp(&count(*b)), + Sort::Added => raw_id(*a).cmp(&raw_id(*b)), + }; + let by = by.then_with(|| name(a).cmp(&name(b))); + folders.then(if v.descending && !matches!(a, LibraryEntry::Folder(_)) { by.reverse() } else { by }) + }); + all +} + +/// F2 renames the selected row and Delete deletes the selection, while the list has the +/// keyboard (it was clicked last). Called before the global shortcuts. +pub fn consume_keys(app: &mut App, ctx: &egui::Context) { + let clicked_elsewhere = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !app.library.list_rect.is_some_and(|r| r.contains(p)))); + if clicked_elsewhere { + app.library.keys = false; + } + if !app.library.keys || app.library.renaming.is_some() { + return; + } + let (rename, delete) = ctx.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::F2), i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace))); + if rename && let [one] = app.library.sel.as_slice() { + let e = *one; + start_rename(app, e); + } + if delete { + delete_selection(app); + } +} + +fn start_rename(app: &mut App, e: LibraryEntry) { + let name = app.s.doc.entry_name(e).unwrap_or("").to_string(); + app.library.renaming = Some((e, name, true)); +} + +fn delete_selection(app: &mut App) { + let items: Vec = app.library.sel.iter().filter(|e| app.s.doc.has_entry(**e)).map(|e| entry_json(*e)).collect(); + if !items.is_empty() { + app.request("library.delete", json!({"items": items})); + } +} + +/// Places an item: a symbol or bitmap at the stage centre, a sound on the active layer's +/// keyframe at the playhead (its span grown to fit). +fn place(app: &mut App, item: LibraryItem) { + match item { + LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), + LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})), + LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})), + }; +} + +/// A new folder in the selected row's folder (or the selected folder), opened, selected and +/// ready to be named. +fn new_folder(app: &mut App) { + let parent = match app.library.sel.as_slice() { + [LibraryEntry::Folder(f)] => Some(*f), + [one] => app.s.doc.parent_of(*one), + _ => None, + }; + if let Some(p) = parent { + app.library.expanded.insert(p); + } + if let Some(v) = app.run("library.new_folder", json!({"parent": parent.map(|f| f.0)})) + && let Some(id) = v["folder"].as_u64() + { + let e = LibraryEntry::Folder(FolderId(id)); + app.library.select_only(e); + start_rename(app, e); + } +} + +/// Moves `what` into `to` (`None`: the top level), opening the folder so they stay in view. +fn move_into(app: &mut App, what: &[LibraryEntry], to: Option) { + let items: Vec = what.iter().filter(|e| app.s.doc.parent_of(**e) != to && **e != to.map_or(**e, LibraryEntry::Folder)).map(|e| entry_json(*e)).collect(); + if items.is_empty() { + return; + } + if app.run("library.move", json!({"items": items, "to": to.map(|f| f.0)})).is_some() + && let Some(f) = to + { + app.library.expanded.insert(f); + } +} + +pub fn panel(app: &mut App, ui: &mut egui::Ui) { + // Rows that are gone (an undo, a deletion) leave the selection. + let doc = &app.s.doc; + app.library.sel.retain(|e| doc.has_entry(*e)); + if app.library.renaming.as_ref().is_some_and(|(e, _, _)| !doc.has_entry(*e)) { + app.library.renaming = None; + } + if doc.library_items().next().is_none() && doc.library_tree.folders.is_empty() { + let key = |id: &str| app.keymap.primary(id).map(crate::platform::shortcut_label).unwrap_or_default(); + ui.label(text(Type::Caption, tr!("No symbols, images or sounds yet. Select artwork and press {convert} to make a symbol, or import an image or a sound with {import}.", convert = key("modify.convert_to_symbol"), import = key("file.import")))); + if ui.button(tr!("New Folder")).clicked() { + new_folder(app); + } + return; + } + toolbar(app, ui); + ui.add_space(4.0); + let (uses, unused) = app.library.counts(&app.s); + let list = rows(&app.s.doc, &app.library, &uses); + let total = app.s.doc.library_items().count(); + let summary = if app.library.filter.trim().is_empty() { + trn!("{n} item", "{n} items", total) + } else { + tr!("{shown} of {total}", shown = list.iter().filter(|r| matches!(r.entry, LibraryEntry::Item(_))).count(), total = total) + }; + ui.horizontal(|ui| { + ui.label(text(Type::Caption, summary)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(text(Type::Caption, tr!("Uses")))); + }); + list_ui(app, ui, &list, &unused); + ui.add_space(4.0); + actions_row(app, ui); + ui.add_space(6.0); + preview(app, ui); + properties(app, ui); +} + +/// Search, sort, and the panel's menu. +fn toolbar(app: &mut App, ui: &mut egui::Ui) { + let search = ui.add(egui::TextEdit::singleline(&mut app.library.filter).hint_text(tr!("Search")).desired_width(ui.available_width())); + search.set_name(tr!("Search the Library")); + ui.horizontal(|ui| { + ui.label(text(Type::Label, tr!("Sort"))); + egui::ComboBox::from_id_salt("lib_sort") + .width(110.0) + .selected_text(app.library.sort.label()) + .show_ui(ui, |ui| { + for s in Sort::ALL { + if ui.selectable_label(app.library.sort == s, s.label()).clicked() { + app.library.sort = s; + } + } + }) + .response + .set_name(tr!("Sort by")); + let (icon, tip) = if app.library.descending { (Icon::ChevronDown, tr!("Descending: click for ascending")) } else { (Icon::ChevronUp, tr!("Ascending: click for descending")) }; + if crate::timeline::icon_button(ui, tip, None, icon).clicked() { + app.library.descending = !app.library.descending; + } + let menu = ui.menu_button(tr!("More"), |ui| { + let n_unused = app.library.counts(&app.s).1.len(); + if ui.add_enabled(n_unused > 0, egui::Button::new(tr!("Select Unused Items"))).clicked() { + ui.close(); + select_unused(app); + } + if ui.add_enabled(n_unused > 0, egui::Button::new(tr!("Delete Unused Items…"))).clicked() { + ui.close(); + app.request("library.delete_unused", json!({})); + } + ui.separator(); + if ui.button(tr!("Expand All Folders")).clicked() { + ui.close(); + app.library.expanded = app.s.doc.library_tree.folders.iter().map(|f| f.id).collect(); + } + if ui.button(tr!("Collapse All Folders")).clicked() { + ui.close(); + app.library.expanded.clear(); + } + }); + menu.response.on_hover_text(tr!("Library options")).set_name(tr!("Library options")); + }); +} + +/// Selects every unused item, opening the folders they are in. +pub fn select_unused(app: &mut App) { + let unused = app.s.doc.unused_items(); + for i in &unused { + if let Some(p) = app.s.doc.parent_of(LibraryEntry::Item(*i)) { + app.library.expanded.extend(app.s.doc.folder_chain(p)); + } + } + app.library.sel = unused.iter().map(|i| LibraryEntry::Item(*i)).collect(); + app.library.keys = true; + app.status_ok(trn!("{n} unused item selected", "{n} unused items selected", unused.len())); +} + +fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet) { + let mut toggle: Option = None; + let mut clicked: Option<(LibraryEntry, Modifiers)> = None; + let mut activate: Option = None; + let mut rename: Option = None; + let mut dropped: Option<(Vec, Option)> = None; + let scroll = egui::ScrollArea::vertical().id_salt("lib").max_height(200.0).auto_shrink([false, true]).show(ui, |ui| { + for row in list { + let selected = app.library.sel.contains(&row.entry); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click_and_drag()); + let p = ui.painter(); + if selected || resp.hovered() { + p.rect_filled(r, T.rc(), if selected { T.accent_dim } else { T.hover }); + } + if selected { + p.rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); + } + let indent = 6.0 + row.depth as f32 * 14.0; + let chevron = Rect::from_center_size(pos2(r.left() + indent + 6.0, r.center().y), vec2(12.0, 12.0)); + let icon = Rect::from_center_size(pos2(r.left() + indent + 22.0, r.center().y), vec2(14.0, 14.0)); + match row.entry { + LibraryEntry::Folder(_) => { + icons::paint(p, chevron, if row.open { Icon::ChevronDown } else { Icon::ChevronRight }, T.icon); + icons::paint(p, icon.expand(1.0), if row.open { Icon::FolderOpen } else { Icon::Folder }, color(Type::Body)); + } + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + let kind_color = match app.s.doc.symbol(id).map(|s| s.kind) { + Some(SymbolKind::Graphic) | None => T.kind_graphic, + Some(SymbolKind::MovieClip) => T.kind_movie_clip, + Some(SymbolKind::Button) => T.kind_button, + }; + p.rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside); + p.circle_filled(icon.center(), 2.5, kind_color); + } + LibraryEntry::Item(LibraryItem::Sound(_)) => icons::paint(p, icon.expand(1.0), Icon::Sound, color(Type::Body)), + LibraryEntry::Item(LibraryItem::Bitmap(_)) => icons::paint(p, icon.expand(1.0), Icon::Image, color(Type::Body)), + } + let name_rect = Rect::from_min_max(pos2(icon.right() + 8.0, r.top()), pos2(r.right() - 40.0, r.bottom())); + let uses_text = row.uses.map(|n| n.to_string()).unwrap_or_default(); + let is_unused = matches!(row.entry, LibraryEntry::Item(i) if unused.contains(&i)); + if let Some(n) = row.uses { + p.text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, &uses_text, font(Type::Data), if n == 0 { T.text_faint } else { color(Type::Caption) }); + } + // Renaming: a field over the name; Enter or clicking away keeps it, Esc doesn't. + let editing = app.library.renaming.as_ref().is_some_and(|(e, _, _)| *e == row.entry); + if editing { + let mut commit = None; + if let Some((e, buf, focus)) = &mut app.library.renaming { + let edit = ui.put(name_rect.shrink2(vec2(0.0, 3.0)), egui::TextEdit::singleline(buf).font(font(Type::Body))); + edit.set_name(tr!("Library name")); + if *focus { + edit.request_focus(); + *focus = false; + } + let esc = ui.input(|i| i.key_pressed(Key::Escape)); + if edit.lost_focus() { + commit = Some((*e, buf.clone(), !esc)); + } + } + if let Some((e, name, keep)) = commit { + app.library.renaming = None; + if keep && app.s.doc.entry_name(e) != Some(name.as_str()) { + let mut params = entry_json(e); + params["name"] = json!(name); + app.run("library.rename", params); + } + } + } else { + let c = if is_unused { T.text_dim } else { color(Type::Body) }; + let galley = ui.painter().layout_no_wrap(row.name.clone(), font(Type::Body), c); + let clip = ui.painter().with_clip_rect(name_rect.intersect(ui.clip_rect())); + clip.galley(pos2(name_rect.left(), r.center().y - galley.size().y / 2.0), galley, c); + } + let used_note = match row.uses { + Some(0) => tr!("not used").to_string(), + Some(n) => trn!("used {n} time", "used {n} times", n), + None => String::new(), + }; + let name = if used_note.is_empty() { format!("{} · {}", row.name, row.detail) } else { format!("{} · {} · {}", row.name, row.detail, used_note) }; + a11y::control(ui, &resp, WidgetType::SelectableLabel, &name, Some(selected)); + let resp = resp.on_hover_text(&name); + // Dragging rows: the selection if the row is in it, else just the row. + if resp.drag_started() { + let what = if selected { app.library.sel.clone() } else { vec![row.entry] }; + resp.dnd_set_drag_payload(what); + } + let target = match row.entry { + LibraryEntry::Folder(f) => Some(f), + e => app.s.doc.parent_of(e), + }; + if let Some(payload) = resp.dnd_hover_payload::>() + && !payload.contains(&row.entry) + { + let hl = if let LibraryEntry::Folder(_) = row.entry { r } else { Rect::from_min_size(pos2(r.left(), r.top()), vec2(r.width(), 2.0)) }; + ui.painter().rect_stroke(hl, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + } + if let Some(payload) = resp.dnd_release_payload::>() { + dropped = Some(((*payload).clone(), target)); + } + if let LibraryEntry::Folder(f) = row.entry + && resp.clicked() + && ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x < icon.right() + 2.0) + { + toggle = Some(f); + } else if resp.clicked() { + clicked = Some((row.entry, ui.input(|i| i.modifiers))); + } + if resp.double_clicked() { + let on_name = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x >= name_rect.left()); + if on_name { + rename = Some(row.entry); + } else { + activate = Some(row.entry); + } + } + resp.context_menu(|ui| row_menu(app, ui, row.entry)); + } + // Below the rows: dropping there moves to the top level. + let rest = ui.available_rect_before_wrap(); + let (r, resp) = ui.allocate_exact_size(vec2(rest.width(), (rest.height()).max(TARGET)), Sense::click() - Sense::FOCUSABLE); + a11y::surface(ui, &resp, tr!("Library: drop here for the top level")); + if resp.dnd_hover_payload::>().is_some() { + ui.painter().rect_stroke(r, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + } + if let Some(payload) = resp.dnd_release_payload::>() { + dropped = Some(((*payload).clone(), None)); + } + if resp.clicked() { + app.library.sel.clear(); + app.library.keys = true; + } + resp.context_menu(|ui| { + if ui.button(tr!("New Folder")).clicked() { + ui.close(); + app.library.sel.clear(); + new_folder(app); + } + }); + }); + app.library.list_rect = Some(scroll.inner_rect); + if let Some(f) = toggle { + if !app.library.expanded.remove(&f) { + app.library.expanded.insert(f); + } + app.library.select_only(LibraryEntry::Folder(f)); + app.library.keys = true; + } + if let Some((e, m)) = clicked { + app.library.keys = true; + if m.command { + if let Some(i) = app.library.sel.iter().position(|x| *x == e) { + app.library.sel.remove(i); + } else { + app.library.sel.push(e); + } + app.library.anchor = Some(e); + } else if m.shift + && let Some(a) = app.library.anchor + && let (Some(i), Some(j)) = (list.iter().position(|r| r.entry == a), list.iter().position(|r| r.entry == e)) + { + let (lo, hi) = (i.min(j), i.max(j)); + app.library.sel = list.get(lo..=hi).map(|rs| rs.iter().map(|r| r.entry).collect()).unwrap_or_default(); + } else { + app.library.select_only(e); + } + if let LibraryEntry::Item(i) = e { + app.library_sel = Some(i); + } + } + if let Some(e) = rename { + app.library.select_only(e); + start_rename(app, e); + } else if let Some(e) = activate { + match e { + // A symbol opens for editing, as in Animate (ADR 0045); images and sounds are placed. + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + app.run("symbol.edit", json!({"symbol": id.0})); + } + LibraryEntry::Item(i) => place(app, i), + LibraryEntry::Folder(f) => { + if !app.library.expanded.remove(&f) { + app.library.expanded.insert(f); + } + } + } + } + if let Some((what, to)) = dropped { + move_into(app, &what, to); + } +} + +/// A row's right-click menu. +fn row_menu(app: &mut App, ui: &mut egui::Ui, e: LibraryEntry) { + if !app.library.sel.contains(&e) { + app.library.select_only(e); + if let LibraryEntry::Item(i) = e { + app.library_sel = Some(i); + } + } + let many = app.library.sel.len() > 1; + if let LibraryEntry::Item(LibraryItem::Symbol(id)) = e + && !many + { + if ui.button(tr!("Edit Symbol")).clicked() { + ui.close(); + app.run("symbol.edit", json!({"symbol": id.0})); + } + if ui.button(tr!("Duplicate Symbol")).clicked() { + ui.close(); + if let Some(v) = app.run("library.duplicate", json!({"symbol": id.0})) + && let Some(n) = v["symbol"].as_u64() + { + let copy = LibraryEntry::Item(LibraryItem::Symbol(anicraft_engine::doc::SymbolId(n))); + app.library.select_only(copy); + start_rename(app, copy); + } + } + } + if let LibraryEntry::Item(i) = e + && !many + { + let label = if matches!(i, LibraryItem::Sound(_)) { tr!("Place on Timeline") } else { tr!("Place on Stage") }; + if ui.button(label).clicked() { + ui.close(); + place(app, i); + } + } + if !many && ui.button(tr!("Rename")).clicked() { + ui.close(); + start_rename(app, e); + } + if ui.button(tr!("New Folder")).clicked() { + ui.close(); + new_folder(app); + } + let folders: Vec<(FolderId, String)> = app.s.doc.library_tree.folders.iter().map(|f| (f.id, app.s.doc.entry_path(LibraryEntry::Folder(f.id)))).collect(); + ui.menu_button(tr!("Move to"), |ui| { + let what = app.library.sel.clone(); + if ui.button(tr!("Library (top level)")).clicked() { + ui.close(); + move_into(app, &what, None); + } + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for (f, path) in &folders { + let inside_moved = what.iter().any(|w| matches!(w, LibraryEntry::Folder(m) if app.s.doc.folder_within(*f, *m))); + if ui.add_enabled(!inside_moved, egui::Button::new(path.as_str())).clicked() { + ui.close(); + move_into(app, &what, Some(*f)); + } + } + }); + }); + ui.separator(); + if ui.button(tr!("Delete")).clicked() { + ui.close(); + delete_selection(app); + } +} + +/// New Folder and Delete, and placing the current item. +fn actions_row(app: &mut App, ui: &mut egui::Ui) { + ui.horizontal(|ui| { + if crate::timeline::icon_button(ui, tr!("New Folder"), None, Icon::FolderPlus).clicked() { + new_folder(app); + } + let can_delete = !app.library.sel.is_empty(); + let del = ui.add_enabled(can_delete, egui::Button::new(tr!("Delete"))).on_hover_text(tr!("Deletes the selected items and folders (Delete)")); + if del.clicked() { + delete_selection(app); + } + let current = app.library_sel.filter(|i| app.s.doc.has_item(*i)); + match current { + Some(LibraryItem::Sound(id)) => { + if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click its icon)")).clicked() { + place(app, LibraryItem::Sound(id)); + } + } + other => { + if ui.add_enabled(other.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre")).clicked() + && let Some(item) = other + { + place(app, item); + } + } + } + }); +} + +/// The current item's settings: a symbol's type and linkage class, a bitmap's smoothing. +fn properties(app: &mut App, ui: &mut egui::Ui) { + let Some(item) = app.library_sel.filter(|i| app.s.doc.has_item(*i)) else { return }; + ui.add_space(6.0); + match item { + LibraryItem::Symbol(id) => { + let Some((kind, linkage)) = app.s.doc.symbol(id).map(|s| (s.kind, s.linkage.clone())) else { return }; + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, tr!("Type"), |ui| { + egui::ComboBox::from_id_salt("lib_symkind") + .width(150.0) + .selected_text(crate::panels::symbol_kind_label(kind)) + .show_ui(ui, |ui| { + for (k, key) in [(SymbolKind::Graphic, "graphic"), (SymbolKind::MovieClip, "movie_clip"), (SymbolKind::Button, "button")] { + if ui.selectable_label(kind == k, crate::panels::symbol_kind_label(k)).clicked() && kind != k { + app.run("symbol.set_kind", json!({"symbol": id.0, "kind": key})); + } + } + }) + .response + .set_name(tr!("Symbol type")); + }); + // The class scripts create it by (ADR 0013 tier 1: kept, not run). + let (class, base) = linkage.map_or((String::new(), String::new()), |l| (l.class, l.base)); + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, tr!("Class"), |ui| { + if let Some(v) = crate::actions_panel::class_field(ui, "lib_symclass", &class, tr!("Linkage class"), tr!("The class scripts create this symbol by (its linkage). Kept with the document; scripts don't run yet")) { + let base = if v.is_empty() { String::new() } else { base.clone() }; + app.run("script.set_class", json!({"symbol": id.0, "class": v, "base": base})); + } + }); + } + LibraryItem::Bitmap(id) => { + let Some(mut on) = app.s.doc.bitmap(id).map(|b| b.smoothing) else { return }; + if crate::theme::checkbox(ui, &mut on, tr!("Allow smoothing")).on_hover_text(tr!("Smooth when scaled or turned; off keeps hard pixel edges, for pixel art")).changed() { + app.run("library.set_smoothing", json!({"bitmap": id.0, "on": on})); + } + } + LibraryItem::Sound(id) => { + if let Some(x) = app.s.doc.sound(id) { + let info = format!("{} · {} Hz · {}", x.format.label(), x.rate, if x.channels > 1 { tr!("Stereo") } else { tr!("Mono") }); + with_type(ui, Type::Data, |ui| ui.label(text(Type::Caption, info))); + } + } + } +} + +// ----- preview -------------------------------------------------------------------------------- + +const PREVIEW_H: f32 = 72.0; + +/// The current item's picture: a symbol's first frame, a bitmap, or a sound's waveform with a +/// play button. +fn preview(app: &mut App, ui: &mut egui::Ui) { + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), PREVIEW_H), Sense::hover()); + ui.painter().rect_filled(r, T.rc(), T.field); + let Some(item) = app.library_sel.filter(|i| app.s.doc.has_item(*i)) else { + ui.painter().text(r.center(), Align2::CENTER_CENTER, tr!("Select an item to preview it"), font(Type::Caption), color(Type::Caption)); + return; + }; + let inner = r.shrink(6.0); + match item { + LibraryItem::Sound(id) => { + waveform(app, ui, inner, id); + let play = Rect::from_min_size(pos2(r.right() - TARGET - 4.0, r.top() + 4.0), vec2(TARGET, TARGET)); + let resp = ui.put(play, egui::Button::new("▶").min_size(vec2(TARGET, TARGET))); + a11y::control(ui, &resp, WidgetType::Button, tr!("Play the sound"), None); + if resp.on_hover_text(tr!("Plays the sound on its own")).clicked() + && let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded()) + { + app.playing = false; + app.sound.preview(dec.pcm.clone()); + if let Some(e) = app.sound.error.take() { + app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e.to_string()))); + } + } + } + _ => { + let key = (item, app.s.state); + if app.library.preview.as_ref().is_none_or(|p| p.key != key) { + let texture = picture(ui.ctx(), &app.s.doc, item, inner); + app.library.preview = Some(Preview { key, texture }); + } + if let Some(tex) = app.library.preview.as_ref().and_then(|p| p.texture.as_ref()) { + let size = tex.size_vec2() / ui.ctx().pixels_per_point(); + let fit = (inner.width() / size.x.max(1.0)).min(inner.height() / size.y.max(1.0)).min(1.0); + let at = Rect::from_center_size(inner.center(), size * fit); + ui.painter().image(tex.id(), at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + } + } +} + +/// A texture of `item` fitting `area` (in points): a symbol's first frame rendered by the +/// oracle, or the bitmap, drawn with or without smoothing as it will be on the stage. +fn picture(ctx: &egui::Context, doc: &Document, item: LibraryItem, area: Rect) -> Option { + let ppp = ctx.pixels_per_point().clamp(0.5, 4.0); + let (w, h) = ((area.width() * ppp).round().max(1.0) as u32, (area.height() * ppp).round().max(1.0) as u32); + match item { + LibraryItem::Symbol(id) => { + let dl = symbol_frame(doc, id); + let b = dl.items.iter().filter(|i| !i.guide && i.masks.is_none()).fold(anicraft_engine::geom::Rect::EMPTY, |acc, i| { + let reach = i.stroke.as_ref().map_or(0.0, |s| s.reach()); + acc.union(&i.path.bounds().inflate(reach).transformed(&i.transform)) + }); + if b.is_empty() || !(b.width().is_finite() && b.height().is_finite()) { + return None; + } + let s = ((w as f32 - 4.0) / b.width().max(1e-3)).min((h as f32 - 4.0) / b.height().max(1e-3)).min(4.0 * ppp); + let c = b.center(); + let transform = anicraft_engine::geom::Affine::translate(w as f32 / 2.0, h as f32 / 2.0).mul(&anicraft_engine::geom::Affine::scale(s, s)).mul(&anicraft_engine::geom::Affine::translate(-c.x, -c.y)); + let view = anicraft_engine::render::View { transform, width: w, height: h, background: None }; + let (px, _) = anicraft_engine::render::render(&dl, &view).ok()?; + let image = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &px.to_premul_rgba8()); + Some(ctx.load_texture("library-preview", image, egui::TextureOptions::LINEAR)) + } + LibraryItem::Bitmap(id) => { + let b = doc.bitmap(id)?; + let px = b.pixels()?; + // At most the area's size in pixels (nearest pixel), so a huge image costs little. + let k = (w as f32 / px.width.max(1) as f32).min(h as f32 / px.height.max(1) as f32).min(1.0); + let (tw, th) = (((px.width as f32 * k).round() as u32).max(1), ((px.height as f32 * k).round() as u32).max(1)); + let mut rgba = Vec::with_capacity((tw * th * 4) as usize); + for y in 0..th { + for x in 0..tw { + let c = px.at((x as f32 / k) as i64, (y as f32 / k) as i64); + rgba.extend(c.iter().map(|v| (v * 255.0 + 0.5) as u8)); + } + } + let image = egui::ColorImage::from_rgba_unmultiplied([tw as usize, th as usize], &rgba); + let options = if b.smoothing { egui::TextureOptions::LINEAR } else { egui::TextureOptions::NEAREST }; + Some(ctx.load_texture("library-preview", image, options)) + } + LibraryItem::Sound(_) => None, + } +} + +/// Symbol `id`'s first frame on its own, its registration point at the origin. +fn symbol_frame(doc: &Document, id: anicraft_engine::doc::SymbolId) -> anicraft_engine::doc::DisplayList { + use anicraft_engine::doc::{Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Scene}; + use std::sync::Arc; + let mut d = doc.clone(); + let mut layer = Layer::new(LayerId(u64::MAX - 1), ""); + if let Some(k) = layer.keyframe_mut(0) { + k.elements = vec![Arc::new(Element { + id: ElementId(u64::MAX - 2), + name: String::new(), + transform: Default::default(), + color: Default::default(), + kind: ElementKind::Symbol { symbol: id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + })]; + } + let mut scene = Scene::new(""); + scene.timeline.layers.push(Arc::new(layer)); + d.scenes = vec![Arc::new(scene)]; + anicraft_engine::doc::evaluate_scene(&d, 0, 0) +} + +/// A sound's waveform across `r`: one line per point column, lowest to highest sample. +fn waveform(app: &App, ui: &egui::Ui, r: Rect, id: anicraft_engine::doc::SoundId) { + let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded_if_ready()) else { + ui.painter().text(r.center(), Align2::CENTER_CENTER, tr!("Reading the sound…"), font(Type::Caption), color(Type::Caption)); + return; + }; + let len = dec.peaks.frames(); + let cols = r.width().floor().max(1.0) as usize; + if len == 0 { + return; + } + let (cy, half) = (r.center().y, r.height() / 2.0); + let stroke = Stroke::new(1.0, T.waveform); + for c in 0..cols { + let a = c * len / cols; + let b = ((c + 1) * len / cols).max(a + 1).min(len); + if let Some((lo, hi)) = dec.peaks.range(a, b) { + let x = r.left() + c as f32 + 0.5; + ui.painter().line_segment([pos2(x, cy - hi.clamp(-1.0, 1.0) * half), pos2(x, cy - lo.clamp(-1.0, 1.0) * half)], stroke); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session() -> (anicraft_engine::Session, u64, u64) { + let mut s = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let ball = s.doc.library.iter().find(|x| x.name == "Ball").map(|x| x.id.0).unwrap(); + let f = s.execute("library.new_folder", &json!({"name": "Characters"})).unwrap()["folder"].as_u64().unwrap(); + s.execute("library.duplicate", &json!({"symbol": ball})).unwrap(); + s.execute("library.move", &json!({"items": [{"symbol": ball}], "to": f})).unwrap(); + (s, ball, f) + } + + fn names(s: &anicraft_engine::Session, v: &mut LibraryView) -> Vec<(usize, String)> { + let (uses, _) = v.counts(s); + rows(&s.doc, v, &uses).into_iter().map(|r| (r.depth, r.name)).collect() + } + + #[test] + fn folders_come_first_and_open_ones_show_what_they_hold() { + let (s, _, f) = session(); + let mut v = LibraryView::default(); + let n = |d: usize, x: &str| (d, x.to_string()); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(0, "Ball copy"), n(0, "Star")]); + v.expanded.insert(FolderId(f)); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Ball copy"), n(0, "Star")]); + // By use count, most used first when descending; folders stay on top. + v.sort = Sort::Uses; + v.descending = true; + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Star"), n(0, "Ball copy")]); + // Date added: the copy is newest. + v.sort = Sort::Added; + v.descending = false; + assert_eq!(names(&s, &mut v)[2..], [n(0, "Star"), n(0, "Ball copy")]); + } + + #[test] + fn a_search_shows_matches_inside_closed_folders() { + let (s, _, _) = session(); + let mut v = LibraryView { filter: "BALL".into(), ..Default::default() }; + let n = |d: usize, x: &str| (d, x.to_string()); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Ball copy")]); + v.filter = "nothing like it".into(); + assert!(names(&s, &mut v).is_empty()); + } +} diff --git a/src/main.rs b/src/main.rs index 37e70968..38f7fe49 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,6 +34,7 @@ mod dialogs; mod gpu_stage; mod icons; mod keymap; +mod library; mod menus; mod motion_editor; mod panels; @@ -176,7 +177,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]\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]\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 4f65e630..a22c3809 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -1,11 +1,11 @@ //! Tools bar, edit bar, status bar, Properties and Library panels. -use crate::app::{App, LibraryItem, Tool}; +use crate::app::{App, Tool}; use crate::icons::{self, Icon}; -use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, font, section, text, to_color32, with_type}; -use anicraft_engine::doc::{ElementKind, Paint, Rgba, SymbolKind, evaluate_layer_elements}; +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 crate::a11y::{self, Named}; -use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::{Value, json}; // ----- tools -------------------------------------------------------------------------------- @@ -302,7 +302,12 @@ pub fn right(app: &mut App, ui: &mut egui::Ui) { // 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| { - egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, 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)); + }); }); 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)); @@ -439,7 +444,7 @@ fn properties(app: &mut App, ui: &mut egui::Ui) { } /// A symbol type's name, as the Properties panel shows it. -fn symbol_kind_label(kind: SymbolKind) -> &'static str { +pub(crate) fn symbol_kind_label(kind: SymbolKind) -> &'static str { match kind { SymbolKind::Graphic => tr!("Graphic"), SymbolKind::MovieClip => tr!("Movie clip"), @@ -579,6 +584,30 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E .response .set_name(tr!("Symbol type")); }); + // Swap Symbol (ADR 0050): another symbol in this instance's place, keeping its + // transform, colour effect, filters and name. + let current = *symbol; + let mut choices: Vec<(anicraft_engine::doc::SymbolId, String)> = app.s.doc.library.iter().map(|x| (x.id, app.s.doc.entry_path(anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Symbol(x.id))))).collect(); + choices.sort_by_key(|(_, p)| p.to_lowercase()); + let name = app.s.doc.symbol(current).map(|x| x.name.clone()).unwrap_or_default(); + row_prose(ui, tr!("Symbol"), |ui| { + ui.label(text(Type::Body, name)); + ui.menu_button(tr!("Swap…"), |ui| { + egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + for (id, path) in &choices { + if ui.selectable_label(*id == current, path.as_str()).clicked() { + ui.close(); + if *id != current { + app.run("element.swap_symbol", json!({"symbol": id.0})); + } + } + } + }); + }) + .response + .on_hover_text(tr!("Show another symbol here, keeping position, colour effect, filters and name")) + .set_name(tr!("Swap Symbol")); + }); // 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()); @@ -1926,124 +1955,5 @@ fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) { } fn library(app: &mut App, ui: &mut egui::Ui) { - let doc = &app.s.doc; - let rows: Vec = doc - .library - .iter() - .map(|sym| LibraryRow { - item: LibraryItem::Symbol(sym.id), - name: sym.name.clone(), - detail: tr!("{kind} · {frames}f", kind = symbol_kind_label(sym.kind), frames = sym.timeline.frame_count()), - kind: Some(sym.kind), - }) - .chain(doc.bitmaps.iter().map(|b| LibraryRow { item: LibraryItem::Bitmap(b.id), name: b.name.clone(), detail: tr!("Bitmap · {width}×{height}", width = b.width, height = b.height), kind: None })) - .chain(doc.sounds.iter().map(|x| LibraryRow { item: LibraryItem::Sound(x.id), name: x.name.clone(), detail: tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds())), kind: None })) - .collect(); - if rows.is_empty() { - let key = |id: &str| app.keymap.primary(id).map(crate::platform::shortcut_label).unwrap_or_default(); - ui.label(text(Type::Caption, tr!("No symbols, images or sounds yet. Select artwork and press {convert} to make a symbol, or import an image or a sound with {import}.", convert = key("modify.convert_to_symbol"), import = key("file.import")))); - return; - } - ui.label(text(Type::Caption, trn!("{n} item", "{n} items", rows.len()))); - // Sounds go on the active layer's keyframe at the playhead, their span grown to fit. - let place = |app: &mut App, item: LibraryItem| match item { - LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), - LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})), - LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})), - }; - egui::ScrollArea::vertical().id_salt("lib").max_height(140.0).auto_shrink([false, true]).show(ui, |ui| { - for row in &rows { - let selected = app.library_sel == Some(row.item); - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click()); - if selected || resp.hovered() { - ui.painter().rect_filled(r, T.rc(), if selected { T.accent_dim } else { T.hover }); - } - if selected { - ui.painter().rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); - } - let icon = Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(14.0, 14.0)); - match (row.kind, row.item) { - (Some(kind), _) => { - let kind_color = match kind { - SymbolKind::Graphic => T.kind_graphic, - SymbolKind::MovieClip => T.kind_movie_clip, - SymbolKind::Button => T.kind_button, - }; - ui.painter().rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside); - ui.painter().circle_filled(icon.center(), 2.5, kind_color); - } - (None, LibraryItem::Sound(_)) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Sound, color(Type::Body)), - (None, _) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Image, color(Type::Body)), - } - ui.painter().text(r.left_center() + vec2(30.0, 0.0), Align2::LEFT_CENTER, &row.name, font(Type::Body), color(Type::Body)); - ui.painter().text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, &row.detail, font(Type::Caption), color(Type::Caption)); - a11y::control(ui, &resp, WidgetType::SelectableLabel, &format!("{} · {}", row.name, row.detail), Some(selected)); - if resp.clicked() { - app.library_sel = Some(row.item); - } - // A symbol opens for editing, as in Animate (ADR 0045); images and sounds go on the - // stage. Place on stage (below) places a symbol. - if resp.double_clicked() { - match row.item { - LibraryItem::Symbol(id) => { - app.run("symbol.edit", json!({"symbol": id.0})); - } - other => { - place(app, other); - } - } - } - // Opens it alone, its registration point at the stage's centre (ADR 0045). - if let LibraryItem::Symbol(id) = row.item { - resp.context_menu(|ui| { - if ui.button(tr!("Edit Symbol")).clicked() { - ui.close(); - app.run("symbol.edit", json!({"symbol": id.0})); - } - }); - } - if let LibraryItem::Sound(id) = row.item { - resp.context_menu(|ui| { - if ui.button(tr!("Delete Sound")).clicked() { - ui.close(); - app.request("sound.delete", json!({"sound": id.0})); - } - }); - } - } - }); - ui.add_space(4.0); - let can_place = app.library_sel.filter(|sel| rows.iter().any(|r| r.item == *sel)); - match can_place { - Some(LibraryItem::Sound(id)) => { - ui.horizontal(|ui| { - if ui.button(tr!("Preview")).on_hover_text(tr!("Plays the sound on its own")).clicked() - && let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded()) - { - app.playing = false; - app.sound.preview(dec.pcm.clone()); - if let Some(e) = app.sound.error.take() { - app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e.to_string()))); - } - } - if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click it)")).clicked() { - place(app, LibraryItem::Sound(id)); - } - }); - } - _ => { - if ui.add_enabled(can_place.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre (or double-click an item)")).clicked() - && let Some(item) = can_place { - place(app, item); - } - } - } -} - -/// One Library row: a symbol (with its kind), a bitmap or a sound. -struct LibraryRow { - item: LibraryItem, - name: String, - detail: String, - kind: Option, + crate::library::panel(app, ui); } From f30192d0a6b1114ec791b1b3e9ad740bc7fb6823 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:55:24 -0700 Subject: [PATCH 035/402] feat(engine): delete, copy, paste, transform, align and re-merge on multiple frames; onion skin inside symbols (M1) --- crates/doc/src/eval.rs | 10 + crates/doc/src/lib.rs | 2 +- crates/engine/src/cmds_modify.rs | 51 +++- crates/engine/src/cmds_plugin.rs | 2 +- crates/engine/src/editing.rs | 23 +- crates/engine/src/lib.rs | 2 + crates/engine/src/multi.rs | 453 ++++++++++++++++++++++++++++ crates/engine/src/multi_tests.rs | 308 +++++++++++++++++++ crates/engine/src/onion.rs | 98 +----- crates/engine/src/onion_tests.rs | 1 + crates/engine/src/plugin_tests.rs | 3 + crates/engine/src/render_service.rs | 53 +++- crates/engine/src/tests.rs | 26 +- 13 files changed, 923 insertions(+), 109 deletions(-) create mode 100644 crates/engine/src/multi.rs create mode 100644 crates/engine/src/multi_tests.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 9fbf3a82..670843ec 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -136,6 +136,16 @@ pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayLi out } +/// [`evaluate_timeline`] placed by `xf` (symbol space to stage space): what an instance of the +/// timeline at `xf` shows, but with the timeline's own layers as the top-level ones, so each item +/// still says which of them it is on. The stage draws a symbol open in place this way when onion +/// skin or Edit Multiple Frames composes its frames (ADR 0051). +pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affine) -> DisplayList { + let mut out = DisplayList::default(); + eval_timeline(doc, tl, frame, &Ctx::top(xf), &mut out, None); + out +} + /// Scene `scene` at its own `frame` as the movie shows it: through the scene's camera, each /// layer shifted by its depth, the camera's tint over everything (ADR 0027). Without a camera /// this is [`evaluate_scene`]. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 086e9914..c66c9b3c 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -32,7 +32,7 @@ pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, W pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle}; pub use camera::Camera; 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, guide_walk, instance_start}; +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}; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index 5455b5a8..defc4498 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -50,6 +50,9 @@ pub struct ClipLayer { pub layer: LayerId, pub name: String, pub elements: Vec, + /// The keyframe (its first frame) it was copied from with Edit Multiple Frames (ADR 0051), + /// where Paste in Place on Multiple Frames puts it back; `None` for a copy on one frame. + pub frame: Option, } impl Clipboard { @@ -103,7 +106,7 @@ fn copy(s: &mut Session, _: &Value) -> Result { let elements: Vec = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect(); let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); if !elements.is_empty() { - copied.push(ClipLayer { layer: l, name, elements }); + copied.push(ClipLayer { layer: l, name, elements, frame: None }); } } let all: Vec = copied.iter().flat_map(|c| c.elements.iter().cloned()).collect(); @@ -141,20 +144,34 @@ fn clip_element_bounds(s: &Session, e: &Element) -> Rect { /// layers below it, in order, with missing layers created at the bottom named after the copied /// ones, as Paste Frames does. fn paste_targets(s: &mut Session) -> Result> { - let n = s.clipboard.layers.len(); + // Each layer the artwork came from once (a copy with Edit Multiple Frames has one entry per + // keyframe, ADR 0051), in order. + let mut src: Vec<(LayerId, String)> = Vec::new(); + for c in &s.clipboard.layers { + if !src.iter().any(|(l, _)| *l == c.layer) { + src.push((c.layer, c.name.clone())); + } + } + let dst = layer_targets(s, &src)?; + Ok(s.clipboard.layers.iter().map(|c| src.iter().position(|(l, _)| *l == c.layer).and_then(|i| dst.get(i)).copied().unwrap_or(s.layer)).collect()) +} + +/// [`paste_targets`] for each source layer (its id and name). +fn layer_targets(s: &mut Session, src: &[(LayerId, String)]) -> Result> { + let n = src.len(); if n <= 1 { return Ok(vec![s.layer]); } let tl = s.timeline(); let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature); - let home: Vec = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect(); + let home: Vec = src.iter().filter_map(|(id, name)| tl.layer(*id).filter(|l| l.name == *name && drawable(s, l)).map(|l| l.id)).collect(); if home.len() == n { return Ok(home); } let at = s.active_layer_index().unwrap_or(0); let mut out = vec![s.layer]; out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1)); - let names: Vec = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect(); + let names: Vec = src.iter().skip(out.len()).map(|(_, name)| name.clone()).collect(); for name in names { if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); @@ -174,13 +191,17 @@ fn paste_targets(s: &mut Session) -> Result> { Ok(out) } +/// Whether pasting the clipboard would put a symbol inside itself: inside an open symbol, an +/// instance of it (or of one using it). +pub(crate) fn clipboard_nests(s: &Session) -> bool { + s.clipboard.layers.iter().flat_map(|c| &c.elements).any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { symbol, .. } if crate::editing::would_nest(s, symbol))) +} + fn paste_with(s: &mut Session, offset: Vec2) -> Result { if s.clipboard.is_empty() { return Err(EngineError::State("the clipboard is empty".into())); } - // Inside an open symbol, an instance of it (or of one using it) would nest it in itself. - let nests = s.clipboard.layers.iter().flat_map(|c| &c.elements).any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { symbol, .. } if crate::editing::would_nest(s, symbol))); - if nests { + if clipboard_nests(s) { return Err(EngineError::State("a symbol can't be pasted inside itself".into())); } import_symbols(s, &s.clipboard.symbols.clone()); @@ -196,21 +217,27 @@ fn paste_with(s: &mut Session, offset: Vec2) -> Result { sel.extend_on(layer, fresh); } s.selection = sel; - if let Some(&first) = targets.first() - && targets.len() > 1 + let mut layers: Vec = Vec::new(); + for l in &targets { + if !layers.contains(l) { + layers.push(*l); + } + } + if let Some(&first) = layers.first() + && layers.len() > 1 { s.layer = first; } let mut v = json!({"pasted": all, "merged": merged}); - if targets.len() > 1 { - v["layers"] = json!(targets.iter().map(|l| l.0).collect::>()); + if layers.len() > 1 { + v["layers"] = json!(layers.iter().map(|l| l.0).collect::>()); } Ok(v) } /// Pastes `elements` moved by `offset` into the active layer's keyframe at the playhead; their /// new ids, and whether raw shapes merged. -fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec, bool)> { +pub(crate) fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec, bool)> { let mut fresh = Vec::new(); let mut out = Vec::new(); let mut raw = Vec::new(); diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 4cbb16d5..616bd168 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -34,7 +34,7 @@ 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"]; 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" => { + "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" => { Err("plug-ins don't use your clipboard") } _ => match id.split('.').next().unwrap_or("") { diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index b068e542..2928925e 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -89,6 +89,20 @@ pub struct StagePicture { pub doc: Document, pub frame: u32, pub state: StateId, + /// The open symbol in front, when one is open: onion skin and Edit Multiple Frames compose + /// its own frames (ADR 0051). + pub front: Option>, +} + +/// The open symbol in a [`StagePicture`]: the picture's top layer `layer` shows `timeline` at its +/// `frame`, placed by `at`. With onion skin on, that layer is drawn instead as the timeline's +/// frames composed by [`crate::onion::compose_timeline`], placed the same way. +#[derive(Clone, Debug)] +pub struct Front { + pub layer: LayerId, + pub timeline: Timeline, + pub frame: u32, + pub at: Affine, } impl Session { @@ -156,7 +170,7 @@ impl Session { /// timeline at its playhead where its instance stands, over the timelines it sits in dimmed. pub fn stage_picture(&self) -> Arc { let Some(view) = self.edit_view() else { - return Arc::new(StagePicture { doc: self.doc.clone(), frame: self.doc.scene_start(self.scene).saturating_add(self.frame), state: self.state }); + return Arc::new(StagePicture { doc: self.doc.clone(), frame: self.doc.scene_start(self.scene).saturating_add(self.frame), state: self.state, front: None }); }; let mut h = std::collections::hash_map::DefaultHasher::new(); (self.state, self.scene, self.frame).hash(&mut h); @@ -173,7 +187,10 @@ impl Session { let mut tl = Timeline::default(); // The open symbol, in front. let at = Affine::translate(view.origin.x, view.origin.y).mul(&Affine::scale(view.scale, view.scale)); - tl.layers.push(placed(&mut doc, self.timeline().clone(), at, self.frame, 1.0)); + let open = self.timeline().clone(); + let layer = placed(&mut doc, open.clone(), at, self.frame, 1.0); + 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. if view.in_place { for (i, l) in self.editing.iter().enumerate().rev() { @@ -188,7 +205,7 @@ impl Session { } *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 }); + let pic = Arc::new(StagePicture { frame: doc.scene_start(self.scene), doc, state: key | 1 << 63, front: Some(front) }); self.picture_cache.replace(Some((key, pic.clone()))); pic } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 399dc279..712645fc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -35,6 +35,7 @@ pub mod editing; pub mod format; pub mod history; mod merge; +pub mod multi; pub mod onion; pub mod recovery; pub mod render_service; @@ -115,6 +116,7 @@ pub fn commands() -> Vec { v.extend(cmds_scene::specs()); v.extend(cmds_frames::specs()); v.extend(onion::specs()); + v.extend(multi::specs()); v.extend(cmds_draw::specs()); v.extend(merge::specs()); v.extend(cmds_modify::specs()); diff --git a/crates/engine/src/multi.rs b/crates/engine/src/multi.rs new file mode 100644 index 00000000..3e3ed5fe --- /dev/null +++ b/crates/engine/src/multi.rs @@ -0,0 +1,453 @@ +//! Edit Multiple Frames, complete (ADR 0051; ADR 0047 began it with moves). +//! +//! With Edit Multiple Frames on, the artwork on every keyframe within the onion markers is edited +//! as if it were on one frame. These commands are that editing, on a list of [`FrameItem`]s (an +//! element on one keyframe), or on everything the markers show when no list is given: +//! +//! * `frames.edit_multiple` moves, `frames.transform` scales, rotates and skews about one shared +//! pivot, `frames.align` aligns: each item on its own keyframe, as one undo step; +//! * `frames.delete`, `frames.copy`, `frames.cut`; `frames.paste` pastes in place onto every +//! keyframe within the markers (artwork copied from several keyframes goes back keyframe by +//! keyframe); +//! * raw (merge-drawing) shapes that moved or landed go back into the drawing on their own +//! keyframe, cut and joined with what they touch, as `draw.drop` does on one frame +//! (`merge: false` holds that back while a drag is under way; `frames.merge` does it when the +//! drag ends). +//! +//! Every command answers with `items`: what the selection is afterwards (merged pieces have new +//! ids), so a front end keeps the multi-frame selection without asking again. +//! +//! The timeline is the one being edited, so all of this works inside a symbol open in place +//! (ADR 0045) on the symbol's own keyframes. + +use crate::cmds_modify::{ClipLayer, Clipboard, collect_symbols, import_symbols}; +use crate::onion::{FrameItem, multi_editable}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, LayerId, Timeline}; +use anicraft_geom::{Affine, Rect, Vec2}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, HashSet}; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..], merge?: bool} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; raw shapes merge again where they land unless merge is false; one undo step; answers the items after the move", true, move_cmd as crate::RunFn), + c("frames.transform", "Transform on Multiple Frames", "", None, "{first, last, items?, merge?, a, b, c, d, e, f} (an affine in stage space) | {rotate? (degrees), scale_x?, scale_y?, skew_x?, skew_y? (degrees), pivot?: [x, y] (default: the centre of every item's bounds together)} transforms the items on each keyframe about one shared pivot, as Free Transform does with Edit Multiple Frames on; one undo step", true, transform_cmd), + c("frames.align", "Align on Multiple Frames", "", None, "{first, last, edge: left|hcenter|right|top|vcenter|bottom, items?, to_stage? (default: one item aligns to the stage), merge?} lines the items up with the edge of their bounds together (or the stage's), each on its own keyframe", true, align_cmd), + c("frames.delete", "Clear on Multiple Frames", "", None, "{first, last, items?} deletes the items (default: everything shown) from their keyframes", true, delete_cmd), + c("frames.copy", "Copy on Multiple Frames", "", None, "{first, last, items?} copies the items (default: everything shown), remembering each one's keyframe: Paste on Multiple Frames puts them back keyframe by keyframe, Paste puts them all on the current frame", false, copy_cmd), + c("frames.cut", "Cut on Multiple Frames", "", None, "{first, last, items?} frames.copy, then frames.delete", true, cut_cmd), + c("frames.paste", "Paste in Place on Multiple Frames", "", None, "{first, last, layer?} pastes in place onto the keyframes within the markers: artwork copied from several keyframes onto the keyframe covering the frame each came from (on the layers it came from when it came from several, else on `layer` or the active layer); artwork copied on one frame onto every keyframe of the layer; raw shapes merge where they land", true, paste_cmd), + c("frames.merge", "Merge on Multiple Frames", "", None, "{first, last, items} the raw shapes among the items merge again with what they touch on their keyframes (the end of a drag made with merge: false); answers the items after the merge", true, merge_cmd), + ] +} + +// ----- params and the chosen items ----------------------------------------------------------- + +/// Most items a command takes. +const MAX_ITEMS: usize = 100_000; + +/// The `first` and `last` params, in order. +pub(crate) fn range_param(p: &Value) -> Result<(u32, u32)> { + let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)"))); + let (a, b) = (req("first")?, req("last")?); + if a.max(b) > crate::MAX_FRAME { + return Err(EngineError::Param(format!("frames go up to {}", crate::MAX_FRAME))); + } + Ok((a.min(b), a.max(b))) +} + +fn items_param(p: &Value) -> Result>> { + let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) }; + let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into()); + let list = v.as_array().ok_or_else(bad)?; + if list.len() > MAX_ITEMS { + return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items"))); + } + list.iter() + .map(|t| { + let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?; + let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad); + let frame = u32::try_from(n(1)?).map_err(|_| bad())?; + Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) }) + }) + .collect::>>() + .map(Some) +} + +/// The items a command acts on, with their stage bounds: the `items` given (each must be shown +/// in `first..=last`), or everything shown. +fn chosen(s: &Session, p: &Value, first: u32, last: u32) -> Result> { + let shown = s.multi_frame_items(first, last); + let Some(list) = items_param(p)? else { return Ok(shown) }; + let mut out = Vec::with_capacity(list.len()); + let mut seen = HashSet::new(); + for it in list { + let Some(&(_, b)) = shown.iter().find(|(s, _)| *s == it) else { + return Err(EngineError::State(format!( + "element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)", + it.element.0, it.layer.0, it.frame + ))); + }; + if seen.insert(it) { + out.push((it, b)); + } + } + Ok(out) +} + +/// The items keyframe by keyframe: (layer, keyframe start) → ids, in the order first seen. +fn by_keyframe(items: &[FrameItem]) -> BTreeMap<(LayerId, u32), Vec> { + let mut out: BTreeMap<(LayerId, u32), Vec> = BTreeMap::new(); + for it in items { + let ids = out.entry((it.layer, it.frame)).or_default(); + if !ids.contains(&it.element) { + ids.push(it.element); + } + } + out +} + +fn items_json(items: &[FrameItem]) -> Value { + json!(items.iter().map(FrameItem::to_json).collect::>()) +} + +fn merge_param(p: &Value) -> Result { + Ok(opt_bool(p, "merge")?.unwrap_or(true)) +} + +/// Runs `f` with the playhead on frame `start` of `layer` (a keyframe's first frame), so the +/// editing helpers that work at the playhead work on that keyframe; both come back after. +fn at_keyframe(s: &mut Session, layer: LayerId, start: u32, f: impl FnOnce(&mut Session) -> Result) -> Result { + let frame = s.frame; + s.frame = start; + let r = s.with_layer(layer, f); + s.frame = frame; + r +} + +// ----- moves and transforms ------------------------------------------------------------------ + +/// Whether `m` only moves (no scale, rotation or skew). +fn translation_only(m: &Affine) -> bool { + let [a, b, c, d, _, _] = m.m; + (a - 1.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6 +} + +/// Applies each item's own stage-space affine to it on its keyframe (`t' = m · t`). A motion +/// tween's object carries its path and X/Y keys along; it can only move (refused otherwise). +/// Nothing changes when anything is refused (the session rolls back a failed command). +fn apply_each(s: &mut Session, moves: &[(FrameItem, Affine)]) -> Result { + let mut by: BTreeMap<(LayerId, u32), Vec<(ElementId, Affine)>> = BTreeMap::new(); + for (it, m) in moves { + if !m.is_finite() || m.determinant().abs() < 1e-8 { + return Err(EngineError::Param("the transform is degenerate (it would collapse the artwork)".into())); + } + by.entry((it.layer, it.frame)).or_default().push((it.element, *m)); + } + let mut n = 0usize; + for ((layer, start), list) in &by { + let l = s.layer_mut(Some(*layer))?; + let Some(ki) = l.keyframe_starting_at(*start) else { continue }; + let Some(kf) = l.keyframe_mut(ki) else { continue }; + if let Some(mt) = kf.motion.as_mut() + && let Some((_, m)) = list.iter().find(|(id, _)| *id == mt.target) + { + if !translation_only(m) { + return Err(EngineError::State("a motion tween's object can only be moved on several frames at once; scale, rotate or skew it on its own keyframe".into())); + } + let d = m.translation(); + if d != Vec2::ZERO && !mt.translate(d) { + return Err(EngineError::State("the motion path would move out of range".into())); + } + } + for e in kf.elements_mut_where(|id| list.iter().any(|(x, _)| *x == id)) { + let Some((_, m)) = list.iter().find(|(x, _)| *x == e.id) else { continue }; + let t = m.mul(&e.transform); + let d = t.decompose(); + if !t.is_finite() || d.sx.abs() > 10_000.0 || d.sy.abs() > 10_000.0 || d.sx.abs() < 1e-4 || d.sy.abs() < 1e-4 { + return Err(EngineError::Param("the transform would make an element too large or too small".into())); + } + e.transform = t; + n += 1; + } + } + Ok(n) +} + +/// The raw shapes among `items` go back into the drawing on their keyframes, on top of what they +/// touch, cutting and joining it (`draw.drop` on each keyframe). The items afterwards: objects as +/// they were, each raw shape's pieces with their new ids. +fn remerge(s: &mut Session, items: &[FrameItem]) -> Result> { + let mut out: Vec = Vec::with_capacity(items.len()); + for ((layer, start), ids) in by_keyframe(items) { + let l = s.layer_mut(Some(layer))?; + let Some(ki) = l.keyframe_starting_at(start) else { continue }; + let Some(kf) = l.keyframe_mut(ki) else { continue }; + let mut moving: Vec = Vec::new(); + kf.elements.retain(|e| { + let take = ids.contains(&e.id) && crate::merge::mergeable(e).is_some(); + if take { + moving.push((**e).clone()); + } + !take + }); + let item = |element| FrameItem { layer, frame: start, element }; + out.extend(ids.iter().filter(|id| !moving.iter().any(|e| e.id == **id)).map(|&id| item(id))); + if moving.is_empty() { + continue; + } + let fresh = at_keyframe(s, layer, start, |s| crate::merge::merge_in(s, moving))?; + out.extend(fresh.into_iter().map(item)); + } + Ok(out) +} + +/// `remerge` when `merge`, else the items as they are. +fn finish(s: &mut Session, items: Vec, merge: bool) -> Result> { + if merge { remerge(s, &items) } else { Ok(items) } +} + +fn move_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); + if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT { + return Err(EngineError::Param("the move is too large".into())); + } + let merge = merge_param(p)?; + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + let keyframes = by_keyframe(&items).len(); + let mv = Affine::translate(d.x, d.y); + let moved = if d == Vec2::ZERO { 0 } else { apply_each(s, &items.iter().map(|it| (*it, mv)).collect::>())? }; + let items = if moved > 0 { finish(s, items, merge)? } else { items }; + Ok(json!({"moved": moved, "keyframes": keyframes, "dx": d.x, "dy": d.y, "items": items_json(&items)})) +} + +/// The transform a `frames.transform` call asks for, given the items' bounds together. +fn transform_param(p: &Value, bounds: Rect) -> Result { + let keys = ["a", "b", "c", "d", "e", "f"]; + if keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + let mut m = [0.0f32; 6]; + for (slot, k) in m.iter_mut().zip(keys) { + *slot = f32_req(p, k)?; + } + return Ok(Affine { m }); + } + let deg = |k: &str| -> Result { + let v = opt_f32(p, k)?.unwrap_or(0.0); + if v.abs() > 36_000.0 { + return Err(EngineError::Param(format!("param '{k}' is out of range"))); + } + Ok(v.to_radians()) + }; + let factor = |k: &str| -> Result { + let v = opt_f32(p, k)?.unwrap_or(1.0); + if !(1e-3..=1e3).contains(&v.abs()) { + return Err(EngineError::Param(format!("param '{k}' must be a scale between 0.001 and 1000 (negative flips)"))); + } + Ok(v) + }; + let (sx, sy, r, kx, ky) = (factor("scale_x")?, factor("scale_y")?, deg("rotate")?, deg("skew_x")?, deg("skew_y")?); + let pivot = match p.get("pivot").filter(|v| !v.is_null()) { + Some(v) => { + let bad = || EngineError::Param("param 'pivot' must be [x, y]".into()); + let a = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?; + let n = |i: usize| a.get(i).and_then(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite() && x.abs() <= crate::cmds_draw::MAX_EXTENT).ok_or_else(bad); + Vec2::new(n(0)?, n(1)?) + } + None => bounds.center(), + }; + // Scale, then skew, then rotate, about the pivot. + let skew = Affine { m: [1.0, ky.tan(), kx.tan(), 1.0, 0.0, 0.0] }; + let m = Affine::rotate(r).mul(&skew).mul(&Affine::scale(sx, sy)); + Ok(Affine::translate(pivot.x, pivot.y).mul(&m).mul(&Affine::translate(-pivot.x, -pivot.y))) +} + +fn transform_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let merge = merge_param(p)?; + let chosen = chosen(s, p, first, last)?; + if chosen.is_empty() { + return Err(EngineError::State("nothing to transform on the frames between the markers".into())); + } + let bounds = chosen.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)); + let m = transform_param(p, bounds)?; + let items: Vec = chosen.into_iter().map(|(it, _)| it).collect(); + let n = apply_each(s, &items.iter().map(|it| (*it, m)).collect::>())?; + let items = finish(s, items, merge)?; + Ok(json!({"transformed": n, "keyframes": by_keyframe(&items).len(), "matrix": m.m, "items": items_json(&items)})) +} + +fn align_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let edge = str_req(p, "edge")?; + let merge = merge_param(p)?; + let chosen: Vec<(FrameItem, Rect)> = chosen(s, p, first, last)?.into_iter().filter(|(_, b)| !b.is_empty()).collect(); + if chosen.is_empty() { + return Err(EngineError::State("nothing to align on the frames between the markers".into())); + } + let to_stage = opt_bool(p, "to_stage")?.unwrap_or(chosen.len() == 1); + let target = if to_stage { Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32) } else { chosen.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)) }; + let d = |b: &Rect| -> Result { + Ok(match edge { + "left" => Vec2::new(target.min.x - b.min.x, 0.0), + "hcenter" => Vec2::new(target.center().x - b.center().x, 0.0), + "right" => Vec2::new(target.max.x - b.max.x, 0.0), + "top" => Vec2::new(0.0, target.min.y - b.min.y), + "vcenter" => Vec2::new(0.0, target.center().y - b.center().y), + "bottom" => Vec2::new(0.0, target.max.y - b.max.y), + _ => return Err(EngineError::Param(format!("unknown edge '{edge}' (left, hcenter, right, top, vcenter or bottom)"))), + }) + }; + let mut moves = Vec::with_capacity(chosen.len()); + for (it, b) in &chosen { + let v = d(b)?; + if v != Vec2::ZERO { + moves.push((*it, Affine::translate(v.x, v.y))); + } + } + let n = apply_each(s, &moves)?; + let moved: Vec = moves.iter().map(|(it, _)| *it).collect(); + let mut items: Vec = chosen.iter().map(|(it, _)| *it).filter(|it| !moved.contains(it)).collect(); + items.extend(finish(s, moved, merge)?); + Ok(json!({"moved": n, "to_stage": to_stage, "items": items_json(&items)})) +} + +fn merge_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + if items_param(p)?.is_none() { + return Err(EngineError::Param("param 'items' is required (the items a drag moved)".into())); + } + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + let items = remerge(s, &items)?; + Ok(json!({"items": items_json(&items)})) +} + +// ----- delete, copy, cut, paste -------------------------------------------------------------- + +fn delete_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + if items.is_empty() { + return Err(EngineError::State("nothing to delete on the frames between the markers".into())); + } + let groups = by_keyframe(&items); + let mut deleted = 0usize; + for ((layer, start), ids) in &groups { + let l = s.layer_mut(Some(*layer))?; + let Some(ki) = l.keyframe_starting_at(*start) else { continue }; + let Some(kf) = l.keyframe_mut(ki) else { continue }; + let before = kf.elements.len(); + kf.elements.retain(|e| !ids.contains(&e.id)); + deleted += before - kf.elements.len(); + } + s.selection.clear(); + Ok(json!({"deleted": deleted, "keyframes": groups.len(), "items": []})) +} + +/// The layers' order in `tl`, top first, for sorting. +fn rank(tl: &Timeline, l: LayerId) -> usize { + tl.layers.iter().position(|x| x.id == l).unwrap_or(usize::MAX) +} + +fn copy_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + if items.is_empty() { + return Err(EngineError::State("nothing to copy on the frames between the markers".into())); + } + let tl = s.timeline(); + let mut groups: Vec<((LayerId, u32), Vec)> = by_keyframe(&items).into_iter().collect(); + // Top layer first, then frame order (a clipboard lists layers top to bottom). + groups.sort_by_key(|((l, f), _)| (rank(tl, *l), *f)); + let mut layers = Vec::with_capacity(groups.len()); + for ((layer, start), ids) in groups { + let Some(l) = tl.layer(layer) else { continue }; + let Some(k) = l.keyframe_starting_at(start).and_then(|i| l.keyframes.get(i)) else { continue }; + // In their stacking order on the keyframe. + let elements: Vec = k.elements.iter().filter(|e| ids.contains(&e.id)).map(|e| (**e).clone()).collect(); + if !elements.is_empty() { + layers.push(ClipLayer { layer, name: l.name.clone(), elements, frame: Some(start) }); + } + } + let all: Vec = layers.iter().flat_map(|c| c.elements.iter().cloned()).collect(); + let symbols = collect_symbols(s, &all); + let (n, keyframes) = (all.len(), layers.len()); + s.clipboard = Clipboard { layers, symbols }; + Ok(json!({"copied": n, "keyframes": keyframes})) +} + +fn cut_cmd(s: &mut Session, p: &Value) -> Result { + let v = copy_cmd(s, p)?; + delete_cmd(s, p)?; + Ok(json!({"cut": v["copied"], "keyframes": v["keyframes"], "items": []})) +} + +/// The first frames of `layer`'s keyframes that Edit Multiple Frames shows in `first..=last` +/// (the playhead's too); none when it doesn't edit that layer. +fn shown_keyframes(tl: &Timeline, layer: LayerId, first: u32, last: u32) -> Vec { + let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return Vec::new() }; + if !multi_editable(tl, i) { + return Vec::new(); + } + tl.layers.get(i).map(|l| l.keyframes.iter().filter(|k| k.start <= last && k.end() > first).map(|k| k.start).collect()).unwrap_or_default() +} + +fn paste_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + if s.clipboard.is_empty() { + return Err(EngineError::State("the clipboard is empty".into())); + } + if crate::cmds_modify::clipboard_nests(s) { + return Err(EngineError::State("a symbol can't be pasted inside itself".into())); + } + let active = match opt_u64(p, "layer")? { + Some(id) => LayerId(id), + None => s.layer, + }; + let clip = s.clipboard.clone(); + // Artwork from several layers goes back on those layers when they are all here and edited + // with Edit Multiple Frames; else everything goes on the one layer, as a paste does. + let mut from: Vec = Vec::new(); + for c in &clip.layers { + if !from.contains(&c.layer) { + from.push(c.layer); + } + } + let tl = s.timeline(); + let home = from.len() > 1 && from.iter().all(|l| !shown_keyframes(tl, *l, first, last).is_empty()); + let mut plan: Vec<(LayerId, u32, &ClipLayer)> = Vec::new(); + let mut skipped = 0usize; + for c in &clip.layers { + let target = if home { c.layer } else { active }; + let keys = shown_keyframes(tl, target, first, last); + match c.frame { + // Back onto the keyframe covering the frame it came from, if the markers show it. + Some(f) => match tl.layer(target).and_then(|l| l.keyframe_at(f)).map(|k| k.start).filter(|k| keys.contains(k)) { + Some(k) => plan.push((target, k, c)), + None => skipped += 1, + }, + // Copied on one frame: onto every keyframe shown. + None => plan.extend(keys.iter().map(|&k| (target, k, c))), + } + } + if plan.is_empty() { + let why = if tl.layer(active).is_some_and(|_| shown_keyframes(tl, active, first, last).is_empty()) { "the layer has no keyframe Edit Multiple Frames can paste onto between the markers (it must be visible, unlocked and hold artwork)" } else { "none of the copied keyframes is between the markers" }; + return Err(EngineError::State(why.into())); + } + import_symbols(s, &clip.symbols); + let mut items = Vec::new(); + let mut keyframes: HashSet<(LayerId, u32)> = HashSet::new(); + for (layer, start, c) in plan { + let (fresh, _) = at_keyframe(s, layer, start, |s| crate::cmds_modify::paste_layer(s, &c.elements, Vec2::ZERO))?; + keyframes.insert((layer, start)); + items.extend(fresh.into_iter().map(|element| FrameItem { layer, frame: start, element })); + } + s.selection.clear(); + Ok(json!({"pasted": items.len(), "keyframes": keyframes.len(), "skipped": skipped, "items": items_json(&items)})) +} + +#[cfg(test)] +#[path = "multi_tests.rs"] +mod tests; diff --git a/crates/engine/src/multi_tests.rs b/crates/engine/src/multi_tests.rs new file mode 100644 index 00000000..783e66f8 --- /dev/null +++ b/crates/engine/src/multi_tests.rs @@ -0,0 +1,308 @@ +//! Edit Multiple Frames, complete (ADR 0051): transforms about one shared pivot, align, delete, +//! copy, cut and paste per keyframe, raw shapes merged again on their keyframes, and all of it +//! (with onion skin) inside a symbol open in place. + +use super::*; +use crate::Session; +use crate::onion::OnionSkin; +use anicraft_doc::{ElementKind, Keyframe, LayerId}; +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}")) +} + +/// One layer, a 20 × 20 drawing object walking right: keyframes on frames 0, 4 and 8 with it at +/// x = 10, 50 and 90 (y = 10). The playhead is on frame 4. +fn walk() -> (Session, LayerId, ElementId) { + let mut s = Session::default(); + let layer = s.layer; + let id = ElementId(run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()); + for f in [4, 8] { + run(&mut s, "timeline.goto", json!({"frame": f})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [id.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + run(&mut s, "timeline.goto", json!({"frame": 4})); + (s, layer, id) +} + +fn key(s: &Session, layer: LayerId, start: u32) -> Keyframe { + let l = s.timeline().layer(layer).unwrap(); + (**l.keyframes.iter().find(|k| k.start == start).unwrap()).clone() +} + +/// The bounds of every element on the keyframe of `layer` starting at `start`. +fn bounds_on(s: &Session, layer: LayerId, start: u32) -> Vec { + key(s, layer, start).elements.iter().map(|e| e.bounds(&s.doc)).collect() +} + +fn near(a: Rect, b: [f32; 4]) -> bool { + [a.min.x, a.min.y, a.max.x, a.max.y].iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3) +} + +#[test] +fn a_transform_about_the_shared_pivot_lands_each_keyframes_artwork_exactly() { + let (mut s, a, _) = walk(); + let steps = s.history_len(); + // Together the three copies span x 10..110, y 10..30: the pivot is (60, 20). + let v = run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "scale_x": 2, "scale_y": 0.5})); + assert_eq!((v["transformed"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3))); + // x' = 60 + 2 (x − 60), y' = 20 + 0.5 (y − 20). + for (f, x) in [(0, 10.0), (4, 50.0), (8, 90.0)] { + let b = bounds_on(&s, a, f)[0]; + assert!(near(b, [60.0 + 2.0 * (x - 60.0), 15.0, 60.0 + 2.0 * (x + 20.0 - 60.0), 25.0]), "keyframe {f}: {b:?}"); + } + assert_eq!(s.history_len(), steps + 1, "one undo step"); + s.undo().unwrap(); + // A quarter turn (clockwise on the y-down stage): (x, y) → (60 − (y − 20), 20 + (x − 60)). + run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "rotate": 90})); + for (f, x) in [(0, 10.0), (4, 50.0), (8, 90.0)] { + let b = bounds_on(&s, a, f)[0]; + let (cx, cy) = (x + 10.0, 20.0); + let (nx, ny) = (60.0 - (cy - 20.0), 20.0 + (cx - 60.0)); + assert!(near(b, [nx - 10.0, ny - 10.0, nx + 10.0, ny + 10.0]), "keyframe {f}: {b:?}"); + } + // Its own pivot, and a matrix, as Free Transform sends. + s.undo().unwrap(); + let on8 = key(&s, a, 8).elements[0].id.0; + run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "scale_x": 2, "pivot": [10, 10], "items": [[a.0, 8, on8]]})); + assert!(near(bounds_on(&s, a, 8)[0], [170.0, 10.0, 210.0, 30.0])); + assert!(near(bounds_on(&s, a, 0)[0], [10.0, 10.0, 30.0, 30.0]), "only the item given"); + run(&mut s, "frames.transform", json!({"first": 0, "last": 4, "a": 1, "b": 0, "c": 0, "d": 1, "e": 5, "f": -5})); + assert!(near(bounds_on(&s, a, 0)[0], [15.0, 5.0, 35.0, 25.0])); + // Degenerate or wild transforms are refused, with nothing changed. + let before = s.doc.clone(); + assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0})).is_err()); + assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "scale_x": 0})).is_err()); + assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "pivot": [1]})).is_err()); + assert!(s.doc == before); +} + +#[test] +fn align_lines_every_keyframes_artwork_up() { + let (mut s, a, _) = walk(); + run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 0, "dy": 0})); + let v = run(&mut s, "frames.align", json!({"first": 0, "last": 8, "edge": "left"})); + assert_eq!(v["moved"], json!(2), "the one already at the left edge stays"); + for f in [0, 4, 8] { + assert!(near(bounds_on(&s, a, f)[0], [10.0, 10.0, 30.0, 30.0]), "keyframe {f}"); + } + s.undo().unwrap(); + run(&mut s, "frames.align", json!({"first": 0, "last": 8, "edge": "bottom", "to_stage": true})); + let h = s.doc.stage.height as f32; + assert!([0, 4, 8].iter().all(|&f| (bounds_on(&s, a, f)[0].max.y - h).abs() < 1e-3)); + assert!(s.execute("frames.align", &json!({"first": 0, "last": 8, "edge": "middle"})).is_err()); +} + +#[test] +fn delete_copy_cut_and_paste_count_per_keyframe() { + let (mut s, a, id) = walk(); + // A second element on keyframes 0 and 8 only. + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "draw.rect", json!({"x": 10, "y": 100, "w": 10, "h": 10, "object": true})); + run(&mut s, "timeline.goto", json!({"frame": 8})); + run(&mut s, "draw.rect", json!({"x": 90, "y": 100, "w": 10, "h": 10, "object": true})); + run(&mut s, "timeline.goto", json!({"frame": 4})); + let count = |s: &Session| [0, 4, 8].map(|f| key(s, a, f).elements.len()); + assert_eq!(count(&s), [2, 1, 2]); + + // Copy the walker on 0 and 8 (with its keyframes), cut everything else. + let walker = |f| json!([a.0, f, id.0]); + let v = run(&mut s, "frames.copy", json!({"first": 0, "last": 8, "items": [walker(0), walker(8)]})); + assert_eq!((v["copied"].as_u64(), v["keyframes"].as_u64()), (Some(2), Some(2))); + assert_eq!(s.clipboard.layers.iter().map(|c| c.frame).collect::>(), vec![Some(0), Some(8)]); + let steps = s.history_len(); + let v = run(&mut s, "frames.delete", json!({"first": 0, "last": 8, "items": [walker(0), walker(4), walker(8)]})); + assert_eq!((v["deleted"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3))); + assert_eq!(count(&s), [1, 0, 1]); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + + // Paste in place: back keyframe by keyframe, where each came from. + let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 8})); + assert_eq!((v["pasted"].as_u64(), v["keyframes"].as_u64(), v["skipped"].as_u64()), (Some(2), Some(2), Some(0))); + assert_eq!(count(&s), [2, 0, 2]); + assert!(near(bounds_on(&s, a, 8)[1], [90.0, 10.0, 110.0, 30.0]), "in place"); + assert_eq!(v["items"].as_array().map(Vec::len), Some(2), "what was pasted is what is selected"); + // Markers that leave out frame 8: only the copy from 0 goes back. + let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 3})); + assert_eq!((v["pasted"].as_u64(), v["skipped"].as_u64()), (Some(1), Some(1))); + assert_eq!(count(&s), [3, 0, 2]); + + // Copied on one frame: onto every keyframe shown. + run(&mut s, "timeline.goto", json!({"frame": 0})); + let small = key(&s, a, 0).elements[0].id; + run(&mut s, "element.select", json!({"ids": [small.0]})); + run(&mut s, "edit.copy", json!({})); + let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 8})); + assert_eq!((v["pasted"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3))); + assert_eq!(count(&s), [4, 1, 3]); + + // Cut: copies, then deletes, as one step. + let steps = s.history_len(); + let v = run(&mut s, "frames.cut", json!({"first": 0, "last": 8})); + assert_eq!(v["cut"], json!(8)); + assert_eq!(count(&s), [0, 0, 0]); + assert_eq!(s.history_len(), steps + 1); + // A plain Paste puts a multi-frame copy on the current frame, on the active layer. + run(&mut s, "timeline.goto", json!({"frame": 4})); + run(&mut s, "edit.paste_in_place", json!({})); + assert_eq!(count(&s), [0, 8, 0]); + + // Nothing to act on, or nowhere to paste: refused. + run(&mut s, "layer.toggle_lock", json!({"layer": a.0})); + assert!(s.execute("frames.paste", &json!({"first": 0, "last": 8})).is_err(), "a locked layer"); +} + +/// Raw (merge-drawing) rectangles, the same colour, on keyframes 0 and 5: one at x 0..40 and one +/// at x 100..140 (y 0..40). Their ids on each keyframe. +fn raw_pair() -> (Session, LayerId) { + let mut s = Session::default(); + s.style.object_drawing = false; + let layer = s.layer; + for x in [0, 100] { + run(&mut s, "draw.rect", json!({"x": x, "y": 0, "w": 40, "h": 40, "fill": "#3366ff", "stroke": null})); + } + run(&mut s, "timeline.goto", json!({"frame": 5})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + (s, layer) +} + +fn raw_fills(s: &Session, layer: LayerId, start: u32) -> Vec { + key(s, layer, start).elements.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_some())).map(|e| e.bounds(&s.doc)).collect() +} + +#[test] +fn raw_shapes_merge_again_on_each_keyframe_after_a_move_or_transform() { + let (mut s, a) = raw_pair(); + assert_eq!(raw_fills(&s, a, 0).len(), 2); + let right = |s: &Session, f: u32| key(s, a, f).elements.iter().find(|e| e.bounds(&s.doc).min.x > 50.0).map(|e| json!([a.0, f, e.id.0])).unwrap(); + let items = json!([right(&s, 0), right(&s, 5)]); + // Moved left by 80 it overlaps the other (x 20..60): one fill region on each keyframe. + let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 5, "dx": -80, "dy": 0, "items": items})); + for f in [0, 5] { + let fills = raw_fills(&s, a, f); + assert_eq!(fills.len(), 1, "keyframe {f}: joined into one fill: {fills:?}"); + assert!(near(fills[0], [0.0, 0.0, 60.0, 40.0]), "keyframe {f}: {:?}", fills[0]); + } + // The selection is the merged pieces, with their new ids. + let after: Vec = v["items"].as_array().unwrap().clone(); + assert_eq!(after.len(), 2); + for it in &after { + let f = it[1].as_u64().unwrap() as u32; + assert!(key(&s, a, f).elements.iter().any(|e| json!(e.id.0) == it[2]), "{it} is on its keyframe"); + } + s.undo().unwrap(); + assert_eq!(raw_fills(&s, a, 5).len(), 2, "one undo takes the move and the merge back"); + + // A drag holds the merge back (merge: false) and merges when it ends (frames.merge). + let items = json!([right(&s, 0), right(&s, 5)]); + s.begin_gesture("Move"); + for _ in 0..4 { + run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 5, "dx": -20, "dy": 0, "items": items, "merge": false})); + } + assert_eq!(raw_fills(&s, a, 0).len(), 2, "not merged mid-drag"); + let v = run(&mut s, "frames.merge", json!({"first": 0, "last": 5, "items": items})); + s.end_gesture(); + assert_eq!([0, 5].map(|f| raw_fills(&s, a, f).len()), [1, 1]); + assert_eq!(v["items"].as_array().map(Vec::len), Some(2)); + assert!(s.execute("frames.merge", &json!({"first": 0, "last": 5})).is_err(), "items are required"); + + // A transform merges too: the right square scaled 3× about its right edge reaches over. + s.undo().unwrap(); + let items = json!([right(&s, 0), right(&s, 5)]); + run(&mut s, "frames.transform", json!({"first": 0, "last": 5, "items": items, "scale_x": 3, "pivot": [140, 0]})); + for f in [0, 5] { + let fills = raw_fills(&s, a, f); + assert_eq!(fills.len(), 1, "keyframe {f}: {fills:?}"); + assert!(near(fills[0], [0.0, 0.0, 140.0, 40.0]), "keyframe {f}: {:?}", fills[0]); + } +} + +#[test] +fn a_motion_tweens_object_moves_but_does_not_scale_on_several_frames() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "object": true})); + run(&mut s, "timeline.insert_frame", json!({"count": 9})); + run(&mut s, "timeline.create_motion_tween", json!({})); + let before = s.doc.clone(); + let e = s.execute("frames.transform", &json!({"first": 0, "last": 9, "rotate": 30})); + assert!(e.is_err_and(|e| e.to_string().contains("motion tween"))); + assert!(s.doc == before); + run(&mut s, "frames.transform", json!({"first": 0, "last": 9, "a": 1, "b": 0, "c": 0, "d": 1, "e": 10, "f": 0})); +} + +/// A symbol open in place (ADR 0045) whose own timeline has keyframes on 0 and 4, the playhead on 4. +fn in_symbol() -> (Session, LayerId, ElementId) { + let mut s = Session::default(); + let id = ElementId(run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Walker"})); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 50})); + run(&mut s, "symbol.edit", json!({})); + let inner = s.layer; + run(&mut s, "timeline.goto", json!({"frame": 4})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [id.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + assert_eq!(s.editing.len(), 1); + (s, inner, id) +} + +#[test] +fn inside_a_symbol_the_commands_edit_its_own_keyframes() { + let (mut s, inner, id) = in_symbol(); + let shown = s.multi_frame_items(0, 4); + assert_eq!(shown.iter().map(|(it, _)| it.frame).collect::>(), vec![0, 4], "the symbol's keyframes"); + run(&mut s, "frames.transform", json!({"first": 0, "last": 4, "scale_x": 2, "scale_y": 2})); + // In the symbol's space (its registration point at the square's centre) the two copies + // span x −10..50, y −10..10 together: the pivot is (20, 0). + assert!(near(bounds_on(&s, inner, 0)[0], [-40.0, -20.0, 0.0, 20.0])); + assert!(near(bounds_on(&s, inner, 4)[0], [40.0, -20.0, 80.0, 20.0])); + run(&mut s, "frames.copy", json!({"first": 0, "last": 4, "items": [[inner.0, 0, id.0]]})); + run(&mut s, "frames.paste", json!({"first": 0, "last": 4})); + assert_eq!(key(&s, inner, 0).elements.len(), 2); + run(&mut s, "frames.delete", json!({"first": 0, "last": 4})); + assert!([0, 4].iter().all(|&f| key(&s, inner, f).elements.is_empty())); + // The scene's own timeline never changed shape: one layer, one instance. + assert_eq!(s.doc.timeline(s.scene).layers.len(), 1); +} + +#[test] +fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() { + let (s, _, _) = in_symbol(); + let pic = s.stage_picture(); + let front = pic.front.clone().expect("the open symbol is in front"); + assert_eq!(front.frame, 4); + let plain = crate::render_service::display_list_with_onion(&pic.doc, pic.frame, None); + let ghosts = OnionSkin { markers: crate::onion::Markers::Relative { before: 4, after: 0 }, keyframes_only: true, ..OnionSkin::default() }; + let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &ghosts); + assert_eq!(dl.items.len(), plain.items.len() + 1, "frame 0 of the symbol under its frame 4"); + // The symbol's origin stands at x 110: its frame 0 (x −10..10) shows at x 100..120, tinted + // and faded; its frame 4 (x 30..50) at 140..160 at full strength, on top. + let left = |i: &anicraft_doc::DisplayItem| i.path.bounds().transformed(&i.transform).min.x; + 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); + // 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.clone(), Some(&ghosts)); + let job = plain_job.clone().inside(pic.front.clone()); + assert_ne!(job.key, plain_job.key); + assert_eq!(job.display_list().items.len(), dl.items.len()); + // 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)); + // 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()); +} + +fn make_off(pic: &crate::editing::StagePicture) -> crate::render_service::FrameJob { + let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None }; + crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, None).inside(pic.front.clone()) +} + diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index 997caa48..fd5a51a5 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -18,10 +18,9 @@ //! Behaviour learned from Adobe's public help pages on onion skinning and from watching the //! program; nothing was copied. -use crate::params::*; -use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session}; +use crate::{CommandSpec, MAX_FRAME, Result, Session}; use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; -use anicraft_geom::{Affine, Rect, Vec2}; +use anicraft_geom::{Rect, Vec2}; use serde_json::{Value, json}; use std::collections::{BTreeMap, HashSet}; use std::hash::{Hash, Hasher}; @@ -341,9 +340,14 @@ fn interleave(tl: &Timeline, parts: Vec) -> (DisplayList, Vec, eval: impl Fn(usize, u32) -> DisplayList + Sync) -> DisplayList { - let now = eval(scene, local); + compose_timeline(doc.timeline(scene), local, skin, |f| eval(scene, f)) +} + +/// [`compose`] for any timeline: `tl` at its frame `local`, `eval` evaluating one of its frames +/// (a scene's, or a symbol's open in place, ADR 0051). Pure: the same inputs give the same list. +pub fn compose_timeline(tl: &Timeline, local: u32, skin: Option<&OnionSkin>, eval: impl Fn(u32) -> DisplayList + Sync) -> DisplayList { + let now = eval(local); let Some(skin) = skin.filter(|s| s.shows()) else { return now }; - let tl = doc.timeline(scene); let (first, last) = skin.range(local, tl.frame_count()); let extras = if skin.edit_multiple { multi_frames(tl, local, first, last) } else { onion_frames(tl, local, skin) }; if extras.is_empty() { @@ -351,7 +355,7 @@ pub fn compose(doc: &Document, scene: usize, local: u32, skin: Option<&OnionSkin } // The frames are independent: evaluated in parallel, kept in order. use rayon::prelude::*; - let mut parts: Vec = extras.par_iter().map(|e| eval(scene, e.frame)).collect(); + let mut parts: Vec = extras.par_iter().map(|e| eval(e.frame)).collect(); for (part, e) in parts.iter_mut().zip(&extras) { keep_layers(part, &e.layers); if let Some(past) = e.past { @@ -454,95 +458,15 @@ pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ c("frames.artwork", "Artwork on Multiple Frames", "", None, "{first, last} lists every element Edit Multiple Frames shows in frames first..=last (0-based): [layer, frame (its keyframe's first frame), id] with stage bounds; the playhead's elements as they look there", false, artwork as crate::RunFn), - c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..]} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; one undo step", true, edit_multiple), ] } -/// The `first` and `last` params, in order. -fn range_param(p: &Value) -> Result<(u32, u32)> { - let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)"))); - let (a, b) = (req("first")?, req("last")?); - if a.max(b) > MAX_FRAME { - return Err(EngineError::Param(format!("frames go up to {MAX_FRAME}"))); - } - Ok((a.min(b), a.max(b))) -} - fn artwork(s: &mut Session, p: &Value) -> Result { - let (first, last) = range_param(p)?; + let (first, last) = crate::multi::range_param(p)?; let items: Vec = s.multi_frame_items(first, last).into_iter().map(|(it, b)| json!({"layer": it.layer.0, "frame": it.frame, "id": it.element.0, "bounds": [b.min.x, b.min.y, b.max.x, b.max.y]})).collect(); Ok(json!({"first": first, "last": last, "items": items})) } -/// Most items `frames.edit_multiple` takes. -const MAX_ITEMS: usize = 100_000; - -fn items_param(p: &Value) -> Result>> { - let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) }; - let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into()); - let list = v.as_array().ok_or_else(bad)?; - if list.len() > MAX_ITEMS { - return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items"))); - } - list.iter() - .map(|t| { - let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?; - let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad); - let frame = u32::try_from(n(1)?).map_err(|_| bad())?; - Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) }) - }) - .collect::>>() - .map(Some) -} - -fn edit_multiple(s: &mut Session, p: &Value) -> Result { - let (first, last) = range_param(p)?; - let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); - if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT { - return Err(EngineError::Param("the move is too large".into())); - } - let shown: Vec = s.multi_frame_items(first, last).into_iter().map(|(it, _)| it).collect(); - let items = match items_param(p)? { - Some(list) => { - let have: HashSet = shown.iter().copied().collect(); - if let Some(bad) = list.iter().find(|it| !have.contains(it)) { - return Err(EngineError::State(format!( - "element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)", - bad.element.0, bad.layer.0, bad.frame - ))); - } - list - } - None => shown, - }; - // One pass per keyframe: (layer, keyframe start) → its ids. - let mut by_key: BTreeMap<(LayerId, u32), HashSet> = BTreeMap::new(); - for it in &items { - by_key.entry((it.layer, it.frame)).or_default().insert(it.element); - } - let mv = Affine::translate(d.x, d.y); - let mut moved = 0usize; - for ((layer, start), ids) in &by_key { - let l = s.layer_mut(Some(*layer))?; - let Some(ki) = l.keyframe_starting_at(*start) else { continue }; - let Some(kf) = l.keyframe_mut(ki) else { continue }; - // A motion tween's object carries its path and X/Y keys along (refused, with nothing - // changed, if they would leave the stage's range). - if let Some(m) = kf.motion.as_mut() - && ids.contains(&m.target) - && d != Vec2::ZERO - && !m.translate(d) - { - return Err(EngineError::State("the motion path would move out of range".into())); - } - for e in kf.elements_mut_where(|id| ids.contains(&id)) { - e.transform = mv.mul(&e.transform); - moved += 1; - } - } - Ok(json!({"moved": moved, "keyframes": by_key.len(), "dx": d.x, "dy": d.y})) -} - #[cfg(test)] #[path = "onion_tests.rs"] mod tests; diff --git a/crates/engine/src/onion_tests.rs b/crates/engine/src/onion_tests.rs index 014bc507..db289dd2 100644 --- a/crates/engine/src/onion_tests.rs +++ b/crates/engine/src/onion_tests.rs @@ -4,6 +4,7 @@ use super::*; use crate::Session; use anicraft_doc::{DisplayItem, ElementId, LayerId, Rgba, evaluate_scene, sample}; +use anicraft_geom::Affine; use anicraft_render::{View, render}; use serde_json::{Value, json}; diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index c8239c34..35ced9f4 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -175,6 +175,9 @@ fn every_command_namespace_has_a_plugin_policy() { } assert!(plugin_may_call("draw.rect").is_ok()); assert!(plugin_may_call("future.thing").is_err()); + // Edit Multiple Frames (ADR 0051): document edits yes, the clipboard no. + assert!(["frames.transform", "frames.delete", "frames.align", "frames.merge", "frames.edit_multiple"].iter().all(|c| plugin_may_call(c).is_ok())); + assert!(["frames.copy", "frames.cut", "frames.paste"].iter().all(|c| plugin_may_call(c).is_err())); } #[test] diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index db6e1a17..c28e4ecf 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -14,6 +14,7 @@ //! keep its pictures on the GPU ([`Raster::Native`], ADR 0029): the cache then holds them, under //! a budget of their own, and only the shell knows what they are. +use crate::editing::Front; use crate::history::StateId; use crate::onion::OnionSkin; use anicraft_doc::{DisplayList, Document, evaluate_scene, evaluate_scene_camera}; @@ -41,6 +42,9 @@ pub struct FrameJob { /// Seen through the scene's camera (View › Preview Through Camera, ADR 0027): what the /// movie shows, rather than the stage as edited. pub camera: bool, + /// A symbol open in place, in front of the picture (ADR 0045): onion skin composes its own + /// frames (ADR 0051). Set with [`FrameJob::inside`]. + pub front: Option>, } impl FrameJob { @@ -58,6 +62,47 @@ impl FrameJob { } self } + + /// The same job for a stage picture whose top layer is the open symbol `front` (from + /// [`crate::editing::StagePicture::front`]): onion skin and Edit Multiple Frames then compose + /// the symbol's frames, not the picture's one frame. Keyed apart from the plain job. + pub fn inside(mut self, front: Option>) -> FrameJob { + if let Some(f) = front { + if self.onion.is_some() { + let mix = |k: u64| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (k, "front", f.layer.0).hash(&mut h); + h.finish() + }; + self.key = mix(self.key); + self.scene = mix(self.scene); + } + self.front = Some(f); + } + self + } + + /// What the job draws: its frame with what its onion settings add (ADR 0047), on the open + /// symbol's own timeline when there is one (ADR 0051). + pub fn display_list(&self) -> DisplayList { + let onion = self.onion.as_ref().filter(|o| o.shows()); + match (&self.front, onion) { + (Some(front), Some(skin)) => display_list_inside(&self.doc, self.frame, front, skin), + _ => display_list_for(&self.doc, self.frame, self.onion.as_ref(), self.camera), + } + } +} + +/// 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. +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))); + dl } /// A finished image: premultiplied RGBA8, ready for a texture upload, or (`native`) an image @@ -128,7 +173,7 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSk /// A job whose `scene` is derived from the same inputs as its key. pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob { let onion = onion.filter(|o| o.shows()).copied(); - FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false } + FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false, front: None } } /// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and @@ -192,7 +237,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>) /// Renders a job synchronously, evaluating its scene. pub fn render_job(job: &FrameJob) -> FrameImage { - render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion.as_ref(), job.camera)) + render_job_with(job, &job.display_list()) } /// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel. @@ -204,7 +249,7 @@ pub fn render_batch(jobs: &[FrameJob]) -> Vec { fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { let mut scenes: HashMap> = HashMap::new(); for j in jobs { - scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera))); + scenes.entry(j.scene).or_insert_with(|| Arc::new(j.display_list())); } jobs.par_iter() .map(|j| { @@ -212,7 +257,7 @@ fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id); match scenes.get(&j.scene) { Some(dl) => render_job_by(j, dl, raster), - None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera), raster), + None => render_job_by(j, &j.display_list(), raster), } }) .collect() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c85b61fb..1fb1babf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -623,6 +623,15 @@ fn panic_hunt_every_command() { json!({"first": u64::MAX, "last": 0, "dx": 5, "dy": 5, "items": []}), json!({"first": 40, "last": 0, "dx": 3, "dy": -2}), json!({"first": 0, "last": 100_001, "dx": f64::NAN, "dy": 0, "items": [[1, 2]]}), + // Edit Multiple Frames, complete (ADR 0051): transforms at the limits, pivots and edges + // that aren't, pastes onto ranges with nothing in them, merges of what isn't raw. + json!({"first": 0, "last": 99_999, "a": 0, "b": 0, "c": 0, "d": 0, "e": 1e30, "f": 0, "merge": "x"}), + json!({"first": 0, "last": 50, "a": 1e9, "b": 1, "c": 1, "d": 1e-9, "e": 0, "f": f64::NAN}), + json!({"first": 0, "last": 50, "rotate": 1e9, "scale_x": 1e-9, "scale_y": -1e9, "skew_x": 90, "skew_y": -90, "pivot": [1e30, 0]}), + json!({"first": 0, "last": 50, "rotate": 45, "skew_x": 89.999, "pivot": [5], "edge": "nope", "to_stage": "x"}), + 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::>()}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); @@ -691,7 +700,22 @@ fn panic_hunt_every_command() { in_symbol.execute(id, &p).unwrap(); } assert_eq!(in_symbol.editing.len(), 1, "the fuzz starts inside a symbol"); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol] { + // Raw drawings on several keyframes, artwork copied from two of them (ADR 0051). + let mut keyed = Session::default(); + keyed.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("draw.rect", json!({"x": 100, "y": 0, "w": 60, "h": 60, "fill": "#ff0000"})), + ("timeline.goto", json!({"frame": 4})), + ("timeline.insert_keyframe", json!({})), + ("timeline.goto", json!({"frame": 8})), + ("timeline.insert_keyframe", json!({})), + ("frames.copy", json!({"first": 0, "last": 8})), + ("timeline.goto", json!({"frame": 4})), + ] { + keyed.execute(id, &p).unwrap(); + } + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, keyed] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { From 41b55241fdd4af51220bed31afd4c03cca463174 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:55:55 -0700 Subject: [PATCH 036/402] perf(engine): measure Library use counts and unused items on a large document (M2) 200,000 element keys (stress 100x100x240) plus 1,000 symbols in 50 folders, release build: use counts 1.5 ms, unused items 1.7 ms, library.items 5.0 ms. --- crates/engine/src/library_tests.rs | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs index cc350a87..318b460d 100644 --- a/crates/engine/src/library_tests.rs +++ b/crates/engine/src/library_tests.rs @@ -283,3 +283,37 @@ fn inside_an_open_symbol_swap_never_nests_and_deleting_it_closes_it() { run(&mut s, "library.delete", json!({"items": [{"symbol": outer}], "confirm": true})); assert!(s.editing.is_empty() && s.doc.symbol(SymbolId(outer)).is_none()); } + +#[test] +fn library_counts_stay_quick_on_a_large_document() { + // 100 layers × 100 shapes keyed every 12 frames over 240 frames (200,000 element keys), + // plus 1,000 symbols in 50 folders, each placed once. Measured, loosely bounded (CI varies); + // the shell works these out once per document change, not per frame. + let mut s = Session::new(anicraft_doc::sample::stress(100, 100, 240)); + // A new layer, so the symbol holds only the new rectangle (drawing selects it). + run(&mut s, "layer.new", json!({})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + let sym = run(&mut s, "modify.convert_to_symbol", json!({}))["symbol"].as_u64().unwrap(); + for i in 0..50 { + run(&mut s, "library.new_folder", json!({"name": format!("F{i}")})); + } + let folders: Vec = s.doc.library_tree.folders.iter().map(|f| f.id.0).collect(); + for i in 0..999 { + let c = run(&mut s, "library.duplicate", json!({"symbol": sym, "name": format!("S{i}")}))["symbol"].as_u64().unwrap(); + run(&mut s, "library.move", json!({"items": [{"symbol": c}], "to": folders[i % folders.len()]})); + } + let t = std::time::Instant::now(); + let uses = s.doc.library_uses(); + let counted = t.elapsed(); + let t = std::time::Instant::now(); + let unused = s.doc.unused_items(); + let reach = t.elapsed(); + let t = std::time::Instant::now(); + let listed = run(&mut s, "library.items", json!({})); + let listing = t.elapsed(); + println!("library of {} items, {} folders: use counts {counted:?}, unused {reach:?} ({} unused), library.items {listing:?}", s.doc.library.len(), folders.len(), unused.len()); + assert_eq!(listed["items"].as_array().map(Vec::len), Some(1000)); + assert_eq!(unused.len(), 999); + assert!(uses.values().sum::() >= 1); + assert!(counted.as_millis() < 500 && reach.as_millis() < 500, "counted {counted:?}, unused {reach:?}"); +} From dfca6610f8f280f87024539b5e71aa3c1c175740 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:56:53 -0700 Subject: [PATCH 037/402] docs: ADR 0050 library management, roadmap and changelog (M2) --- CHANGELOG.md | 25 ++++++ docs/adr/0050-library-management.md | 126 ++++++++++++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 3 +- 4 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 docs/adr/0050-library-management.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 11ee8d59..a6b3e715 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ ## Unreleased +* **Library management** (ADR 0050, M2). + * **Folders**: New Folder (the folder icon under the list, or right-click), nested as deep as + you like (32 levels). Drag items and folders onto a folder to move them in, onto an item to + join its folder, or below the list for the top level; right-click › Move to does the same. + Deleting a folder that holds items asks first, and its items go with it. + * **Rename in place** with F2 or a double-click on the name; Enter keeps it, Esc cancels. + Names are unique within a folder (case aside), as in Animate. Convert to Symbol picks the next + free “Symbol n”. + * **Duplicate Symbol** (right-click): “Ball copy” in the same folder, ready to rename. + * **Swap Symbol** in Properties › Symbol: pick another symbol for the selected instances. + Position, colour effect, blending, filters, looping and instance name stay. + * A **use count** for every item, **Select Unused Items** and **Delete Unused Items…** (in + More). Unused means nothing in any scene reaches it, so one pass clears a whole unused + branch; symbols with a linkage class count as used. Deleting an item the movie uses asks, + and its instances go with it. + * **Sort** by name, type, use count or date added, ascending or descending, and **search** + by name; folders that hold a match open. + * A **preview** of the current item (a symbol's first frame, the bitmap, or a sound's + waveform with a play button) and its **properties**: a symbol's type and linkage class, a + bitmap's **Allow Smoothing**. Smoothing off keeps hard pixel edges on the stage, in + renders, in SVG and in the HTML page. + * Animate files keep their library folders and Allow Smoothing. + * Headless: `library.items`, `library.new_folder`, `library.rename`, `library.move`, + `library.duplicate`, `library.delete`, `library.unused`, `library.delete_unused`, + `library.set_smoothing`, `element.swap_symbol`. * **Raw points, snapping while drawing, and symbols edited in place** (ADR 0045, issue #42, M1). * **Add a point** on a merged drawing's line or fill edge with the Pen's Alt-click or a Subselection double-click: every shape on that edge gets it, and the curve keeps its shape. diff --git a/docs/adr/0050-library-management.md b/docs/adr/0050-library-management.md new file mode 100644 index 00000000..56c82456 --- /dev/null +++ b/docs/adr/0050-library-management.md @@ -0,0 +1,126 @@ +# ADR 0050: Library folders, item management and Swap Symbol + +* Status: accepted (2026-11-10) +* Relates to: ADR 0003 (file format), ADR 0004 (destructive actions), ADR 0009 (XFL import), + ADR 0013 (scripts and linkage), ADR 0019/0032 (GPU stage), ADR 0028 (HTML canvas export), + ADR 0045 (symbols edited in place), roadmap M2 + +## Context + +The Library listed symbols, bitmaps and sounds in one flat list. It could place an item, delete +a sound and (since ADR 0045) open a symbol for editing. Animate users keep hundreds of items in +nested folders, rename them in place, duplicate symbols to make variants, swap one symbol for +another on the stage, clean out what the movie no longer uses, and set per-item options such as +a bitmap's smoothing. We learned how Animate does this from its public help pages and from +watching the program. Nothing was copied. + +## Decision + +1. **The organisation is a side table, not a field on each item.** + `Document.library_tree: Arc` (`crates/doc/src/library.rs`) holds the folders + (`LibraryFolder { id, name, parent }`) and a map from each item (`LibraryItem::Symbol | + Bitmap | Sound`) to its folder. An item that isn't in the map is at the top level. We chose + this over a `folder` field on `Symbol`, `Bitmap` and `Sound`: + * Moving or renaming folders touches one small table, never a symbol (so undo snapshots stay + O(changed) and symbol timelines keep their `Arc`s). + * The three item structs, which many places build, are unchanged. + * Older files have no `library_tree` and open with everything at the top level. A Library + without folders writes nothing new (`skip_serializing_if`), so files stay the same until + a folder is made. + + Folder ids come from the document's id counter, like every other id. On load, + `sanitize_library_tree` repairs a damaged tree: duplicate ids, missing parents, cycles and + nesting deeper than 32 levels are fixed, and placements of items that aren't there are + dropped. It touches nothing when the tree is sound. The fuzz checks that no command leaves a + tree that a load would have to repair. + +2. **Names are unique within a folder, ignoring case,** across items and folders, as in Animate. + They can't be empty, can't be longer than 256 characters, and can't contain `/`, which joins + a path (`Characters/Hero/Ball`). The engine checks this in `library.new_folder`, + `library.rename`, `library.move` and `library.duplicate`. A move whose name is already in + the target folder fails with a message naming it, and nothing moves (commands are atomic). + We chose refusing over Animate's "replace existing items?" prompt: replacing destroys + content, and a rename is one keystroke away. Older documents with duplicate names open as + they are. Convert to Symbol now picks the next free "Symbol n". + +3. **Commands** (`crates/engine/src/cmds_library.rs`), all in the existing `library` and + `element` plug-in namespaces. Entries are named `{"symbol"|"bitmap"|"sound"|"folder": id}`. + * `library.items`: every folder and item with path, kind, use count and whether it is unused. + * `library.new_folder`, `library.rename`, `library.move`. A folder can't go inside itself, + and nesting is limited to 32 levels. + * `library.duplicate`: a copy right after the original, in the same folder, named + " copy" (then "copy 2", …). It gets fresh layer and element ids, with layer parents, + motion tween targets and bone ends following them (`library::fresh_ids`). It has no + linkage class, because a class names one symbol. + * `library.delete`: deletes items and folders together with what they hold. What uses them + goes too, as in Animate: instances of deleted symbols, shapes filled with deleted bitmaps, + and deleted sounds on keyframes, on every timeline. Only the layers and keyframes that had + a use are copied. Deleting the symbol that is open for editing closes it (ADR 0045). + * `library.unused` (Select Unused Items) and `library.delete_unused`. + * `library.set_smoothing`; `element.swap_symbol`. Linkage stays `script.set_class` + (ADR 0013). + +4. **Use count and unused have different meanings, on purpose.** Use count is the number of + references on every timeline (scenes and symbols), counted once per keyframe: instances, + bitmap fills and keyframe sounds. *Unused* means **not reachable from any scene**. A symbol + used only inside a symbol that nothing places is unused, even though its count is above + zero. One Delete Unused Items then clears a whole dead branch in one undo step, instead of + peeling off one layer per run. Symbols with a linkage class count as reached, because scripts + create them by name (ADR 0013). The row's tooltip and screen-reader name give both. + +5. **Confirmations follow ADR 0004** (undoable tier, `crates/engine/src/confirm.rs`). Deleting + asks only when something deleted is in use ("used 4 times in the movie; those uses go too") + or when a folder holds items ("holds 5 items, deleted with it"). Deleting an unused item or + an empty folder is routine and doesn't ask. Delete Unused Items always asks and names the + first few items. + +6. **Swap Symbol** replaces only the symbol an instance shows. Transform, colour effect, + blending, filters, looping, actions and instance name stay, as in Animate. It is a button in + Properties › Symbol ("Swap…", listing symbols by path). Inside a symbol open for editing, it + refuses a symbol that would contain itself (`editing::would_nest`). + +7. **Allow Smoothing** is a property of the bitmap (`Bitmap.smoothing`, on by default; only + `false` is written). It reaches the renderers through `DisplayItem.smooth`. The CPU oracle + samples the nearest pixel instead of bilinear (`Shader::smoothed`). The GPU stage uses bit 1 + of the bitmap's flag word in `fine.wgsl` and does the same, so oracle parity still holds. + SVG export marks the image `image-rendering="pixelated"`, and the HTML page turns + `imageSmoothingEnabled` off for that fill. XFL import reads `allowSmoothing`. + +8. **XFL import keeps folders.** `` creates folders, empty + ones included. Symbols and bitmaps go into the folder their library name's path names + (`Characters/Ball` → `Ball` in `Characters`). The report lists "library folders" as kept. + +9. **The panel (`src/library.rs`) holds only view state**: selection (Ctrl-click and + Shift-click ranges), open folders, sort (Name, Type, Use count, Date added, ascending or + descending; folders first), the search text, and the item being renamed. Everything that + changes the document is a command. + * "Date added" is the item's id order: ids only grow, so no clock is stored. + * Searching opens every folder that leads to a match. + * F2, or a double-click on the name, renames in place. Enter or clicking away keeps the new + name; Esc cancels. A double-click on the icon edits a symbol (ADR 0045) or places an image + or sound. + * Rows drag onto a folder (into it), onto an item (into that item's folder) or below the + list (to the top level). + * F2 and Delete act on the Library only while the list was the last thing clicked, so + Delete on the stage still clears artwork. + * The preview shows a symbol's first frame rendered by the CPU oracle, a bitmap drawn with or + without smoothing as on the stage, or a sound's waveform with a play button. Below it are + the item's properties: a symbol's type and linkage class, a bitmap's Allow Smoothing, a + sound's format. + * Use counts are worked out once per document state. + +## Consequences + +* Measured on 200,000 element keys plus 1,000 symbols in 50 folders, release build: use counts + 1.5 ms, unused items 1.7 ms, the whole `library.items` listing 5.0 ms (`library_tests.rs`). +* Duplicates share no ids with their originals. Bone ids inside an armature are kept: they are + scoped to their layer. +* One XFL corpus golden changed: its checker bitmap says `allowSmoothing="false"` and is now + drawn with hard edges, as Animate shows it. + +## Not yet + +Dragging Library items onto the stage, Animate's Properties dialog (the properties are inline), +linkage on bitmaps and sounds, bitmap compression settings, Update and Import of library items +from another document (shared libraries), folder expansion saved in the file, sorting by size, +choosing a folder in Convert to Symbol, and Swap Bitmap. diff --git a/docs/adr/README.md b/docs/adr/README.md index 0390bd99..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 | -| 0050 | m2/library-management | Library folders, item management and Swap Symbol | diff --git a/docs/roadmap.md b/docs/roadmap.md index 780d3774..dcb99ce2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -17,6 +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): 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`. Not yet: dragging items onto the stage, shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, a folder choice in Convert to Symbol, Swap Bitmap. | | 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. | @@ -32,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); ~~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); ~~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); ~~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 deferred (not the bottleneck as tiles); ~~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: 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); not yet: `.fla` variants of the corpus, sound and video items; ~~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 c68c9a0eafe1d7a1a060f08d496b1df4476e096b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:02:29 -0700 Subject: [PATCH 038/402] feat(shell): Edit Multiple Frames edits, Free Transform about one pivot, and onion skin inside symbols (M1) --- crates/engine/src/multi.rs | 17 +- crates/engine/src/multi_tests.rs | 2 +- src/a11y.rs | 2 +- src/app.rs | 46 +++-- src/i18n/tests.rs | 21 ++- src/menus.rs | 4 + src/onion.rs | 286 +++++++++++++++++++++++++++++-- src/stage.rs | 40 ++++- 8 files changed, 371 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/multi.rs b/crates/engine/src/multi.rs index 3e3ed5fe..bad74c48 100644 --- a/crates/engine/src/multi.rs +++ b/crates/engine/src/multi.rs @@ -180,7 +180,8 @@ fn apply_each(s: &mut Session, moves: &[(FrameItem, Affine)]) -> Result { /// touch, cutting and joining it (`draw.drop` on each keyframe). The items afterwards: objects as /// they were, each raw shape's pieces with their new ids. fn remerge(s: &mut Session, items: &[FrameItem]) -> Result> { - let mut out: Vec = Vec::with_capacity(items.len()); + // Each keyframe's raw shapes merged: (layer, start) → the pieces (ids gone, ids new). + let mut merged: BTreeMap<(LayerId, u32), (Vec, Vec)> = BTreeMap::new(); for ((layer, start), ids) in by_keyframe(items) { let l = s.layer_mut(Some(layer))?; let Some(ki) = l.keyframe_starting_at(start) else { continue }; @@ -193,13 +194,21 @@ fn remerge(s: &mut Session, items: &[FrameItem]) -> Result> { } !take }); - let item = |element| FrameItem { layer, frame: start, element }; - out.extend(ids.iter().filter(|id| !moving.iter().any(|e| e.id == **id)).map(|&id| item(id))); if moving.is_empty() { continue; } + let gone: Vec = moving.iter().map(|e| e.id).collect(); let fresh = at_keyframe(s, layer, start, |s| crate::merge::merge_in(s, moving))?; - out.extend(fresh.into_iter().map(item)); + merged.insert((layer, start), (gone, fresh)); + } + // In the order given: objects as they were, each keyframe's pieces where its first raw + // shape was. + let mut out: Vec = Vec::with_capacity(items.len()); + for it in items { + match merged.get_mut(&(it.layer, it.frame)) { + Some((gone, fresh)) if gone.contains(&it.element) => out.extend(std::mem::take(fresh).into_iter().map(|element| FrameItem { element, ..*it })), + _ => out.push(*it), + } } Ok(out) } diff --git a/crates/engine/src/multi_tests.rs b/crates/engine/src/multi_tests.rs index 783e66f8..ee9d7d9e 100644 --- a/crates/engine/src/multi_tests.rs +++ b/crates/engine/src/multi_tests.rs @@ -288,7 +288,7 @@ fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() { assert!(ghost.color.alpha < 1.0 && ghost.color.tint_amount > 0.0 && now.color.alpha == 1.0); // 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.clone(), Some(&ghosts)); + let plain_job = crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, Some(&ghosts)); let job = plain_job.clone().inside(pic.front.clone()); assert_ne!(job.key, plain_job.key); assert_eq!(job.display_list().items.len(), dl.items.len()); diff --git a/src/a11y.rs b/src/a11y.rs index 15318b84..52387723 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"] { + 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", "edittransform", "onionsymbol"] { 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 5d04f74d..6585fe4d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -194,6 +194,9 @@ pub enum Drag { /// pointer at `last` last frame; or a marquee over them. MultiMove { last: egui::Pos2 }, MultiMarquee { start: egui::Pos2, cur: egui::Pos2 }, + /// Free Transform on Edit Multiple Frames' selection (ADR 0051): as `Transform`, on every + /// keyframe the selection is on, about one shared pivot. + MultiTransform { kind: XfKind, start: egui::Pos2, bounds: [f32; 4], applied: anicraft_engine::geom::Affine }, Shape { start: egui::Pos2, cur: egui::Pos2 }, /// Subselection: dragging the selected points (stage position of the last frame). Points { last: egui::Pos2 }, @@ -802,6 +805,30 @@ impl App { self.run("timeline.goto", json!({"frame": 12})); crate::onion::select_all(self); } + Some("edittransform") => { + // Free Transform on Edit Multiple Frames' selection (ADR 0051): one box, one + // pivot, over the artwork on every keyframe between the markers. + self.onion.preset(5); + crate::onion::toggle_edit_multiple(self); + self.run("timeline.goto", json!({"frame": 12})); + self.tool = Tool::Transform; + crate::onion::select_all(self); + // The bouncing ball on its keyframes. + let top = self.s.timeline().layers.first().map(|l| l.id); + self.onion_ui.sel.retain(|it| Some(it.layer) == top); + } + 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. + let star = self.s.timeline().layers.iter().flat_map(|l| l.keyframes.iter().flat_map(|k| k.elements.iter())).find(|e| e.name == "star").map(|e| e.id.0); + if let Some(id) = star { + self.run("element.select", json!({"ids": [id]})); + self.run("symbol.edit", json!({})); + self.run("timeline.goto", json!({"frame": 12})); + } + self.onion.ghosts = true; + self.onion.preset(5); + } Some("selection") => { // A selection across layers (ADR 0044): Select All takes every unlocked layer's // artwork; the timeline marks the layers, Properties says how many. @@ -1505,21 +1532,10 @@ impl App { self.status_err(crate::i18n::t(why)); return; } - // Edit Multiple Frames (ADR 0047) selects on every keyframe between the markers. - if crate::onion::editing(self) { - match id { - "edit.select_all" => return crate::onion::select_all(self), - "edit.deselect" => { - self.onion_ui.sel.clear(); - return; - } - // This slice moves artwork across keyframes; other edits stay on one frame. - "edit.delete" | "edit.cut" | "edit.copy" | "edit.duplicate" if !self.onion_ui.sel.is_empty() => { - self.status_err(tr!("Edit Multiple Frames moves artwork on several keyframes; to delete, copy or duplicate it, turn Edit Multiple Frames off and work frame by frame.")); - return; - } - _ => {} - } + // Edit Multiple Frames (ADR 0047, 0051) selects and edits on every keyframe between the + // markers: the Edit menu, Align and Transform act there. + if crate::onion::editing(self) && crate::onion::invoke(self, id) { + return; } if id == "timeline.paste_frames" && let Some(p) = timeline::paste_params(self) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 45096bc0..971a0377 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"] { + 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)))); } for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { @@ -623,6 +623,25 @@ fn status_lines_for_every_result_are_translated() { assert!(plain.is_empty(), "status lines in plain English:\n{}", plain.join("\n")); } +#[test] +fn edit_multiple_frames_status_lines_are_translated() { + // The Edit menu with Edit Multiple Frames on (ADR 0051), as the status bar shows it. + let (mut app, _ctx) = pseudo_app(|a, _| a.open_panel(Some("edittransform"))); + let mut plain = Vec::new(); + for id in ["edit.copy", "edit.cut", "edit.paste_in_place", "edit.duplicate", "edit.delete"] { + app.status = None; + app.invoke(id); + match &app.status { + Some(s) if !s.text.chars().any(pseudo::is_accented) => plain.push(format!("{id}: {:?}", s.text)), + None => plain.push(format!("{id}: said nothing")), + _ => {} + } + } + assert!(plain.is_empty(), "status lines in plain English: +{}", plain.join(" +")); +} + #[test] fn tool_status_lines_are_translated() { // The Eraser's and Eyedropper's results on the sample (on the sun and the hills, and on diff --git a/src/menus.rs b/src/menus.rs index bc6fa9c7..5eda634a 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -42,6 +42,10 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) { } fn enabled(app: &App, id: &str) -> bool { + // With Edit Multiple Frames on, the selection is on several keyframes (ADR 0051). + if let Some(on) = crate::onion::enabled(app, id) { + return on; + } match id { "edit.undo" => app.s.can_undo(), "edit.redo" => app.s.can_redo(), diff --git a/src/onion.rs b/src/onion.rs index ea6e3970..dec79592 100644 --- a/src/onion.rs +++ b/src/onion.rs @@ -2,8 +2,10 @@ //! onion menu, the markers on the frame ruler, and Edit Multiple Frames on the stage. //! //! The settings are view state ([`OnionSkin`], in `App::onion`); the options that carry over -//! between sessions are also in the preferences. Only Edit Multiple Frames' moves change the -//! document, through `frames.edit_multiple`. +//! between sessions are also in the preferences. Only Edit Multiple Frames' edits change the +//! document, through the `frames.*` commands (ADR 0051): moves, Free Transform, align, delete, +//! copy, cut and paste, each on every keyframe the selection is on. Inside a symbol open in place +//! both work on the symbol's own timeline. use crate::a11y::Named; use crate::app::{App, Drag}; @@ -19,8 +21,9 @@ use std::sync::Arc; /// The onion menu's popup (opened by its button, a right-click on the ruler, or `--open onion`). pub const MENU_ID: &str = "onion_menu"; -/// What the shown items depend on: document state, scene, playhead and the markers' frames. -type ItemsKey = (u64, usize, u32, u32, u32); +/// What the shown items depend on: document state, scene, the symbol open (and how deep), +/// playhead and the markers' frames. +type ItemsKey = (u64, usize, (usize, Option), u32, u32, u32); /// Every element Edit Multiple Frames shows, with its stage bounds. pub type Shown = Arc>; @@ -82,8 +85,8 @@ pub fn range(app: &App) -> (u32, u32) { /// What the stage composes now: `None` while playing or when nothing is on. pub fn stage_skin(app: &App) -> Option<&OnionSkin> { - // Not inside a symbol open in place: the stage then draws a picture of it (ADR 0045). - (!app.playing && app.onion.shows() && app.s.editing.is_empty()).then_some(&app.onion) + // Inside a symbol open in place too: the stage composes the symbol's own frames (ADR 0051). + (!app.playing && app.onion.shows()).then_some(&app.onion) } /// Onion skin on or off (the timeline button, View › Onion Skin, Alt+Shift+O). @@ -104,7 +107,7 @@ pub fn toggle_edit_multiple(app: &mut App) { /// Edit Multiple Frames is taking the Selection tool's input. pub fn editing(app: &App) -> bool { - app.onion.edit_multiple && !app.playing && !crate::camera_tool::previewing(app) && app.s.editing.is_empty() + app.onion.edit_multiple && !app.playing && !crate::camera_tool::previewing(app) } // ----- the menu ------------------------------------------------------------------------------ @@ -305,7 +308,7 @@ pub fn ruler(app: &mut App, ui: &mut egui::Ui, ruler: Rect, cell_w: f32, x_of: i /// playhead and markers). pub fn items(app: &mut App) -> Shown { let (first, last) = range(app); - let key = (app.s.state, app.s.scene, app.s.frame, first, last); + let key = (app.s.state, app.s.scene, (app.s.editing.len(), app.s.editing_symbol().map(|s| s.0)), app.s.frame, first, last); if let Some((k, v)) = &app.onion_ui.cache && *k == key { @@ -324,15 +327,190 @@ fn live_selection(app: &mut App) -> Vec { sel } -/// Moves the selection by `d` on every keyframe it is on (no-op when nothing is selected). -fn move_by(app: &mut App, d: Vec2) -> bool { - let sel = live_selection(app); - if sel.is_empty() || d == Vec2::ZERO { +/// The `items` a command answered with, as the selection. +fn parse_items(v: &serde_json::Value) -> Option> { + let list = v.get("items")?.as_array()?; + Some( + list.iter() + .filter_map(|t| { + let n = |i: usize| t.get(i).and_then(serde_json::Value::as_u64); + Some(FrameItem { layer: anicraft_engine::doc::LayerId(n(0)?), frame: u32::try_from(n(1)?).ok()?, element: anicraft_engine::doc::ElementId(n(2)?) }) + }) + .collect(), + ) +} + +/// Runs `id` (a `frames.*` command) on the markers' frames with `extra` params, on the selection +/// when `on_sel` (nothing happens without one), and takes the items it answers as the new +/// selection. +fn run_on(app: &mut App, id: &str, extra: serde_json::Value, on_sel: bool) -> Option { + let (first, last) = range(app); + let mut p = json!({"first": first, "last": last}); + if on_sel { + let sel = live_selection(app); + if sel.is_empty() { + return None; + } + p["items"] = json!(sel.iter().map(FrameItem::to_json).collect::>()); + } + if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) { + o.extend(e.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + let v = app.run(id, p)?; + if let Some(items) = parse_items(&v) { + app.onion_ui.sel = items; + } + Some(v) +} + +/// Moves the selection by `d` on every keyframe it is on (no-op when nothing is selected). Raw +/// shapes merge where they land when `merge` (a drag merges once, when it ends). +fn move_by(app: &mut App, d: Vec2, merge: bool) -> bool { + if d == Vec2::ZERO { return false; } - let (first, last) = range(app); - let items: Vec = sel.iter().map(FrameItem::to_json).collect(); - app.run("frames.edit_multiple", json!({"first": first, "last": last, "dx": d.x, "dy": d.y, "items": items})).is_some() + run_on(app, "frames.edit_multiple", json!({"dx": d.x, "dy": d.y, "merge": merge}), true).is_some() +} + +/// The end of a drag that moved or transformed the selection: raw shapes merge where they landed +/// (in the drag's undo step), then the step closes. +pub fn drag_end(app: &mut App) { + let raw = live_selection(app).iter().any(|it| is_raw(app, it)); + if raw { + run_on(app, "frames.merge", json!({}), true); + } + app.s.end_gesture(); +} + +/// Whether `it` is a raw (merge-drawing) shape. +fn is_raw(app: &App, it: &FrameItem) -> bool { + let k = app.s.timeline().layer(it.layer).and_then(|l| l.keyframe_starting_at(it.frame).and_then(|i| l.keyframes.get(i))); + k.and_then(|k| k.elements.iter().find(|e| e.id == it.element)).is_some_and(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)) +} + +/// The selection's bounds on every keyframe together (the Free Transform box), in stage space. +pub fn selection_bounds(app: &mut App) -> Option<[f32; 4]> { + let sel = live_selection(app); + let r = items(app).iter().filter(|(it, _)| sel.contains(it)).fold(GRect::EMPTY, |r, (_, b)| r.union(b)); + (!r.is_empty()).then_some([r.min.x, r.min.y, r.max.x, r.max.y]) +} + +/// One step of a Free Transform drag: `delta` (stage space, about the shared pivot the drag +/// chose) on every keyframe; merged when the drag ends. +pub fn transform_by(app: &mut App, delta: &anicraft_engine::geom::Affine) -> bool { + let [a, b, c, d, e, f] = delta.m; + run_on(app, "frames.transform", json!({"a": a, "b": b, "c": c, "d": d, "e": e, "f": f, "merge": false}), true).is_some() +} + +/// The Edit menu, the Align panel and their shortcuts with Edit Multiple Frames on: they act on +/// the selection on every keyframe. True when handled here. +pub fn invoke(app: &mut App, id: &str) -> bool { + let has_sel = !live_selection(app).is_empty(); + let undo = app.undo_key(); + match id { + "edit.select_all" => select_all(app), + "edit.deselect" => app.onion_ui.sel.clear(), + "edit.delete" if has_sel => { + if let Some(v) = run_on(app, "frames.delete", json!({}), true) { + let n = v["deleted"].as_u64().unwrap_or(0) as usize; + app.status_ok(trn!("Deleted {n} element on the frames between the markers. {undo} to undo.", "Deleted {n} elements on the frames between the markers. {undo} to undo.", n, undo = undo)); + } + } + "edit.copy" if has_sel => { + if let Some(v) = run_on(app, "frames.copy", json!({}), true) { + let n = v["copied"].as_u64().unwrap_or(0) as usize; + let key = crate::platform::shortcut_label(app.keymap.primary("edit.paste_in_place").unwrap_or("Ctrl+Shift+V")); + app.status_ok(trn!("Copied {n} element. Paste in Place ({key}) puts it back on its keyframe.", "Copied {n} elements. Paste in Place ({key}) puts each back on its keyframe.", n, key = key)); + } + } + "edit.cut" if has_sel => { + if let Some(v) = run_on(app, "frames.cut", json!({}), true) { + let n = v["cut"].as_u64().unwrap_or(0) as usize; + app.status_ok(trn!("Cut {n} element from the frames between the markers. {undo} to undo.", "Cut {n} elements from the frames between the markers. {undo} to undo.", n, undo = undo)); + } + } + // Paste in Place: onto the keyframes between the markers. + "edit.paste_in_place" if !app.s.clipboard.is_empty() => { + if let Some(v) = run_on(app, "frames.paste", json!({}), false) { + let n = v["keyframes"].as_u64().unwrap_or(0) as usize; + app.status_ok(trn!("Pasted in place onto {n} keyframe. {undo} to undo.", "Pasted in place onto {n} keyframes. {undo} to undo.", n, undo = undo)); + } + } + // Paste: onto the current frame, as without Edit Multiple Frames; what lands is selected. + "edit.paste" if !app.s.clipboard.is_empty() => { + if app.run("edit.paste", json!({})).is_some() { + adopt_selection(app); + } + } + "edit.duplicate" | "modify.convert_to_symbol" | "modify.break_apart" if has_sel => { + app.status_err(tr!("Edit Multiple Frames moves, transforms, aligns, deletes, copies and pastes artwork on several keyframes; for this, turn it off and work frame by frame.")); + } + "align.left" | "align.hcenter" | "align.right" | "align.top" | "align.vcenter" | "align.bottom" if has_sel => { + let edge = id.trim_start_matches("align."); + // The Align panel's To Stage option. + let p = if app.align_to_stage { json!({"edge": edge, "to_stage": true}) } else { json!({"edge": edge}) }; + run_on(app, "frames.align", p, true); + } + "modify.rotate_cw" | "modify.rotate_ccw" | "modify.flip_h" | "modify.flip_v" if has_sel => { + let p = match id { + "modify.rotate_cw" => json!({"rotate": 90}), + "modify.rotate_ccw" => json!({"rotate": -90}), + "modify.flip_h" => json!({"scale_x": -1}), + _ => json!({"scale_y": -1}), + }; + run_on(app, "frames.transform", p, true); + } + _ => return false, + } + true +} + +/// Takes what a command selected at the playhead as the multi-frame selection (each element on +/// its layer's keyframe there), and lets go of the playhead's selection. +fn adopt_selection(app: &mut App) { + let frame = app.s.frame; + let picked: Vec = app.s.selected_elements().iter().filter_map(|(l, e)| app.s.timeline().layer(*l).and_then(|x| x.keyframe_at(frame)).map(|k| FrameItem { layer: *l, frame: k.start, element: e.id })).collect(); + app.s.selection.clear(); + app.onion_ui.sel = picked; +} + +/// Whether a menu command can act with Edit Multiple Frames on (`None`: decided as usual). +pub fn enabled(app: &App, id: &str) -> Option { + if !editing(app) { + return None; + } + let sel = !app.onion_ui.sel.is_empty(); + match id { + "edit.delete" | "edit.cut" | "edit.copy" => Some(sel), + "edit.duplicate" | "modify.convert_to_symbol" | "modify.break_apart" | "arrange.bring_to_front" | "arrange.send_to_back" | "align.distribute_h" | "align.distribute_v" => Some(false), + _ => None, + } +} + +/// The stage's right-click menu with Edit Multiple Frames on. +pub fn context_menu(app: &mut App, ui: &mut egui::Ui) { + let selected = !app.onion_ui.sel.is_empty(); + let ids: &[&str] = if selected { &["edit.cut", "edit.copy", "edit.paste", "edit.paste_in_place", "edit.delete"] } else { &["edit.paste", "edit.paste_in_place", "edit.select_all"] }; + for id in ids { + crate::menus::cmd_item(app, ui, id); + } + if selected { + ui.separator(); + ui.menu_button(tr!("Transform"), |ui| { + for id in ["modify.rotate_cw", "modify.rotate_ccw", "modify.flip_h", "modify.flip_v"] { + crate::menus::cmd_item(app, ui, id); + } + }); + ui.menu_button(tr!("Align"), |ui| { + for id in ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"] { + crate::menus::cmd_item(app, ui, id); + } + }); + } + ui.separator(); + for id in ["edit.undo", "edit.redo"] { + crate::menus::cmd_item(app, ui, id); + } } /// A press on the stage with Edit Multiple Frames on: on artwork, select it (unless it is) and @@ -358,7 +536,7 @@ pub fn drag_start(app: &mut App, sp: Pos2, shift: bool, zoom: f32) -> Drag { /// The pointer moved to `c` during a move. pub fn drag_to(app: &mut App, last: &mut Pos2, c: Pos2) { let d = c - *last; - if d.length_sq() > 0.0 && move_by(app, Vec2::new(d.x, d.y)) { + if d.length_sq() > 0.0 && move_by(app, Vec2::new(d.x, d.y), false) { *last = c; } } @@ -406,7 +584,7 @@ pub fn nudge(app: &mut App, d: Vec2) { if own { app.s.begin_gesture(tr_noop!("Move")); // i18n-exempt: an undo label (the engine's English, translated where shown) } - move_by(app, d); + move_by(app, d, true); if own { app.s.end_gesture(); } @@ -541,6 +719,80 @@ mod tests { assert_eq!(big.sanitized().onion.before, ONION_REACH_MAX); } + /// How many elements each keyframe of the sample's top layer (the ball) holds. + fn ball_counts(a: &App) -> Vec { + a.s.timeline().layers.first().map(|l| l.keyframes.iter().map(|k| k.elements.len()).collect()).unwrap_or_default() + } + + #[test] + fn the_edit_menu_deletes_copies_and_pastes_on_every_keyframe() { + let mut a = app(); + a.open_panel(Some("edittransform")); + let sel = a.onion_ui.sel.clone(); + assert!(sel.len() >= 2, "the ball on two keyframes: {sel:?}"); + let before = ball_counts(&a); + let steps = a.s.history_len(); + assert!(invoke(&mut a, "edit.cut")); + assert_eq!(a.s.history_len(), steps + 1, "one undo step"); + let after = ball_counts(&a); + assert_eq!(before.iter().sum::() - after.iter().sum::(), sel.len()); + assert!(a.onion_ui.sel.is_empty(), "nothing left to select"); + // Paste in Place puts each back on its keyframe, selected. + assert!(invoke(&mut a, "edit.paste_in_place")); + assert_eq!(ball_counts(&a), before); + assert_eq!(a.onion_ui.sel.len(), sel.len()); + assert_eq!(a.onion_ui.sel.iter().map(|it| it.frame).collect::>(), sel.iter().map(|it| it.frame).collect::>()); + // Menus follow the multi-frame selection; duplicate waits for a later slice. + assert_eq!(enabled(&a, "edit.delete"), Some(true)); + assert_eq!(enabled(&a, "edit.duplicate"), Some(false)); + assert!(invoke(&mut a, "edit.delete")); + assert_eq!(enabled(&a, "edit.delete"), Some(false)); + // Without Edit Multiple Frames the menu is decided as usual. + toggle_edit_multiple(&mut a); + assert_eq!(enabled(&a, "edit.delete"), None); + } + + #[test] + fn free_transform_scales_every_keyframe_about_one_pivot_in_one_step() { + let mut a = app(); + a.open_panel(Some("edittransform")); + let b = selection_bounds(&mut a).expect("a box"); + let (cx, cy) = ((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0); + let steps = a.s.history_len(); + a.s.begin_gesture("Free Transform"); + // A drag in two steps: twice as big about the box's centre, sent as changes. + let half = anicraft_engine::geom::Affine::translate(cx, cy).mul(&anicraft_engine::geom::Affine::scale(1.5, 1.5)).mul(&anicraft_engine::geom::Affine::translate(-cx, -cy)); + let rest = anicraft_engine::geom::Affine::translate(cx, cy).mul(&anicraft_engine::geom::Affine::scale(2.0 / 1.5, 2.0 / 1.5)).mul(&anicraft_engine::geom::Affine::translate(-cx, -cy)); + assert!(transform_by(&mut a, &half) && transform_by(&mut a, &rest)); + drag_end(&mut a); + assert_eq!(a.s.history_len(), steps + 1, "one undo step"); + let n = selection_bounds(&mut a).expect("a box"); + for (got, want) in n.iter().zip([cx + 2.0 * (b[0] - cx), cy + 2.0 * (b[1] - cy), cx + 2.0 * (b[2] - cx), cy + 2.0 * (b[3] - cy)]) { + assert!((got - want).abs() < 0.05, "{n:?}"); + } + // Rotate 90° from the menu, about the same centre. + assert!(invoke(&mut a, "modify.rotate_cw")); + assert_eq!(a.s.history_len(), steps + 2); + } + + #[test] + fn onion_skin_and_edit_multiple_frames_work_inside_a_symbol() { + let mut a = app(); + a.open_panel(Some("onionsymbol")); + assert_eq!(a.s.editing.len(), 1, "the star is open in place"); + assert!(stage_skin(&a).is_some(), "onion skin draws inside it"); + let pic = a.s.stage_picture(); + assert!(pic.front.is_some()); + toggle_edit_multiple(&mut a); + assert!(editing(&a)); + select_all(&mut a); + // The star's own keyframes (ADR 0051). + let frames: Vec = a.onion_ui.sel.iter().map(|it| it.frame).collect(); + assert!(frames.len() >= 2 && frames.iter().all(|f| a.s.timeline().layers.iter().any(|l| l.keyframe_starting_at(*f).is_some())), "{frames:?}"); + nudge(&mut a, Vec2::new(5.0, 0.0)); + assert_eq!(a.onion_ui.sel.len(), frames.len(), "the selection stays"); + } + fn srgb_of(c: Rgba) -> [u8; 3] { let [r, g, b, _] = to_color32(c).to_srgba_unmultiplied(); [r, g, b] diff --git a/src/stage.rs b/src/stage.rs index cbece835..43426016 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -274,10 +274,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.status_ok(tr!("Previewing through the camera: artwork edits are paused. Turn off View › Preview Through Camera to edit.")); } // Selection box in screen space (free transform handles live on it). - let sel_bounds = bounds_arr(app.s.selection_bounds()); - let sel_rect = sel_bounds.map(|b| Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3])))); - // Edit Multiple Frames takes the Selection and Free Transform tools' input (ADR 0047). + // Edit Multiple Frames takes the Selection and Free Transform tools' input (ADR 0047); Free + // Transform's box then holds the selection on every keyframe (ADR 0051). let multi = crate::onion::editing(app) && !preview; + let sel_bounds = if multi { crate::onion::selection_bounds(app) } else { bounds_arr(app.s.selection_bounds()) }; + let sel_rect = sel_bounds.map(|b| Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3])))); // Shape hint markers take the pointer first with the selection tools (ADR 0023). let hint_tools = matches!(app.tool, Tool::Select | Tool::Transform | Tool::Subselect) && !panning && !preview; let hint_marks = if hint_tools { crate::shape_hints::markers(app) } else { Vec::new() }; @@ -317,7 +318,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Tool::Width => crate::widthtool::cursor(app, pointer, xf), Tool::Transform => { let zone = match app.drag { - Drag::Transform { kind, .. } => Some(kind), + Drag::Transform { kind, .. } | Drag::MultiTransform { kind, .. } => Some(kind), _ => sel_rect.zip(pointer).and_then(|(r, p)| xf_zone(r, p)), }; match zone { @@ -370,7 +371,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } else { let tool = app.tool; match tool { - // Edit Multiple Frames (ADR 0047): artwork on every keyframe between the markers. + // Edit Multiple Frames (ADR 0047): artwork on every keyframe between the markers; + // Free Transform's handles transform it all about one pivot (ADR 0051). + Tool::Transform if multi && let (Some(kind), Some(bounds)) = (sel_rect.and_then(|r| xf_zone(r, press)), sel_bounds) => { + app.s.begin_gesture(tr_noop!("Free Transform")); + Drag::MultiTransform { kind, start: sp, bounds, applied: Affine::IDENTITY } + } Tool::Select | Tool::Transform if multi => crate::onion::drag_start(app, sp, shift, zoom), // On an armature, a drag poses it (ADR 0043). Tool::Select if let Some(d) = crate::bone_tool::select_drag_start(app, xf, press) => d, @@ -491,6 +497,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.drag = Drag::MultiMove { last: l }; } (Drag::MultiMarquee { cur: m, .. }, Some(c)) => *m = c, + (Drag::MultiTransform { kind, start, bounds, applied }, Some(c)) => { + let (kind, start, bounds, applied) = (*kind, *start, *bounds, *applied); + let total = xf_total(kind, bounds, start, c, shift, alt); + // Only the change since the last frame; the gesture makes it one undo step. + if let Some(inv) = applied.inverse() { + let delta = total.mul(&inv); + if delta.m.iter().zip(Affine::IDENTITY.m).any(|(a, b)| (a - b).abs() > 1e-6) && crate::onion::transform_by(app, &delta) { + app.drag = Drag::MultiTransform { kind, start, bounds, applied: total }; + } + } + } (Drag::Bend { id, cmd, t, last }, Some(c)) => { let d = c - *last; if d.length_sq() > 0.0 { @@ -586,7 +603,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Drag::Pencil => crate::pathtools::commit_pencil(app, xf), Drag::Brush => crate::brushtool::commit(app, xf), Drag::Eraser => crate::erasertool::commit(app, xf), - Drag::MultiMove { .. } => app.s.end_gesture(), + // Raw shapes merge where they landed, in the drag's step (ADR 0051). + Drag::MultiMove { .. } | Drag::MultiTransform { .. } => crate::onion::drag_end(app), Drag::MultiMarquee { start, cur } => crate::onion::marquee(app, start, cur, shift), Drag::Marquee { start, cur } => { // The parts of raw fills and strokes under it, cut at its edges, and the objects @@ -720,6 +738,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if crate::shape_hints::menu(app, ui) || crate::motion_path::menu(app, ui) || crate::pathtools::point_menu(app, ui) { return; } + if multi { + crate::onion::context_menu(app, ui); + return; + } if app.s.selection.is_empty() { for id in ["edit.paste", "edit.paste_in_place", "edit.select_all", "timeline.insert_keyframe", "timeline.insert_blank_keyframe"] { crate::menus::cmd_item(app, ui, id); @@ -790,7 +812,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Render jobs take movie frames: the current scene starts at `start`. let start = app.s.doc.scene_start(app.s.scene); let frame = app.s.frame; - let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview); (t, j) }).collect(); + // Inside a symbol open in place, onion skin composes the symbol's own frames (ADR 0051). + let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview).inside(pic.front.clone()); (t, j) }).collect(); let keys: Vec = jobs.iter().map(|(_, j)| j.key).collect(); let missing: Vec = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect(); @@ -989,7 +1012,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.circle(o, 3.5, Color32::WHITE, Stroke::new(1.0, Color32::BLACK)); } // Free transform box: recomputed every frame so it follows the artwork while you drag. - if transforming && let Some(b) = bounds_arr(app.s.selection_bounds()) { + let xf_box = if multi { crate::onion::selection_bounds(app) } else { bounds_arr(app.s.selection_bounds()) }; + if transforming && let Some(b) = xf_box { let r = Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3]))).expand(1.0); painter.rect_stroke(r, 0.0, Stroke::new(1.5, T.selection), StrokeKind::Middle); for (h, _, _) in handles(r) { From 6fe6557634b520afdd9514a3fde7235b66a85391 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:04:50 -0700 Subject: [PATCH 039/402] perf(engine): index Edit Multiple Frames items by hash; timings for ADR 0051 (M1) Measured (optimised dev build, multi_timings, 24 keyframes, 4,656 items shown): list 1.4 ms; move 1,200 objects 2.8 ms; rotate 1,200 2.9 ms; move and merge 288 raw squares 5.6 ms; copy + paste in place 1,200 3.1 ms; delete all 1.8 ms. --- crates/engine/src/multi.rs | 3 ++- crates/engine/src/multi_tests.rs | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/multi.rs b/crates/engine/src/multi.rs index bad74c48..c7059569 100644 --- a/crates/engine/src/multi.rs +++ b/crates/engine/src/multi.rs @@ -81,10 +81,11 @@ fn items_param(p: &Value) -> Result>> { fn chosen(s: &Session, p: &Value, first: u32, last: u32) -> Result> { let shown = s.multi_frame_items(first, last); let Some(list) = items_param(p)? else { return Ok(shown) }; + let index: std::collections::HashMap = shown.into_iter().collect(); let mut out = Vec::with_capacity(list.len()); let mut seen = HashSet::new(); for it in list { - let Some(&(_, b)) = shown.iter().find(|(s, _)| *s == it) else { + let Some(&b) = index.get(&it) else { return Err(EngineError::State(format!( "element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)", it.element.0, it.layer.0, it.frame diff --git a/crates/engine/src/multi_tests.rs b/crates/engine/src/multi_tests.rs index ee9d7d9e..dc2bac63 100644 --- a/crates/engine/src/multi_tests.rs +++ b/crates/engine/src/multi_tests.rs @@ -306,3 +306,44 @@ fn make_off(pic: &crate::editing::StagePicture) -> crate::render_service::FrameJ crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, None).inside(pic.front.clone()) } + +/// Measured numbers for ADR 0051: `cargo test -p anicraft-engine --lib multi_timings -- --ignored --nocapture`. +#[test] +#[ignore] +fn multi_timings() { + use std::time::Instant; + // 24 keyframes, each with 12 × 12 raw squares and 50 objects. + let mut s = Session::default(); + s.style.object_drawing = false; + for i in 0..144 { + let (x, y) = ((i % 12) as f32 * 50.0, (i / 12) as f32 * 50.0); + run(&mut s, "draw.rect", json!({"x": x, "y": y, "w": 30, "h": 30, "fill": "#3366ff", "stroke": null})); + } + for i in 0..50 { + run(&mut s, "draw.rect", json!({"x": 700 + i, "y": i * 10, "w": 20, "h": 20, "object": true})); + } + for f in 1..24 { + run(&mut s, "timeline.goto", json!({"frame": f * 2})); + run(&mut s, "timeline.insert_keyframe", json!({})); + } + let last = 47; + let t = |label: &str, f: &mut dyn FnMut(&mut Session)| { + let mut s2 = Session::new(s.doc.clone()); + let t0 = Instant::now(); + f(&mut s2); + eprintln!("{label}: {:.2} ms", t0.elapsed().as_secs_f64() * 1000.0); + }; + let objects = |s: &Session| -> Vec { s.multi_frame_items(0, last).into_iter().filter(|(it, _)| key(s, it.layer, it.frame).elements.iter().any(|e| e.id == it.element && !matches!(&e.kind, ElementKind::Shape(sh) if sh.merge))).map(|(it, _)| it.to_json()).collect() }; + let raws = |s: &Session| -> Vec { s.multi_frame_items(0, last).into_iter().filter(|(it, _)| key(s, it.layer, it.frame).elements.iter().any(|e| e.id == it.element && matches!(&e.kind, ElementKind::Shape(sh) if sh.merge))).map(|(it, _)| it.to_json()).take(24 * 12).collect() }; + let (objects, raws) = (objects(&s), raws(&s)); + eprintln!("items shown: {}, objects: {}, raw: {}", s.multi_frame_items(0, last).len(), objects.len(), raws.len()); + t("list what is shown (24 keyframes)", &mut |s| drop(s.multi_frame_items(0, last))); + t("move 1,200 objects, a drag step", &mut |s| drop(run(s, "frames.edit_multiple", json!({"first": 0, "last": last, "dx": 1, "dy": 0, "items": objects, "merge": false})))); + t("rotate 1,200 objects", &mut |s| drop(run(s, "frames.transform", json!({"first": 0, "last": last, "rotate": 15, "items": objects})))); + t("move and merge 288 raw squares (24 keyframes)", &mut |s| drop(run(s, "frames.edit_multiple", json!({"first": 0, "last": last, "dx": 25, "dy": 0, "items": raws})))); + t("copy 1,200 objects, paste in place", &mut |s| { + run(s, "frames.copy", json!({"first": 0, "last": last, "items": objects})); + run(s, "frames.paste", json!({"first": 0, "last": last})); + }); + t("delete everything shown", &mut |s| drop(run(s, "frames.delete", json!({"first": 0, "last": last})))); +} From 2b3aaf79bbe8530d7c178177afd3392d0375dfb7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:04:50 -0700 Subject: [PATCH 040/402] docs: ADR 0051 Edit Multiple Frames, complete; onion skin inside symbols (M1) --- CHANGELOG.md | 15 +++ ...aw-points-and-raw-shapes-inside-symbols.md | 2 +- ...047-onion-skin-and-edit-multiple-frames.md | 3 +- ...ames-complete-and-onion-skin-in-symbols.md | 120 ++++++++++++++++++ docs/adr/README.md | 1 - docs/development.md | 2 +- docs/roadmap.md | 10 +- 7 files changed, 144 insertions(+), 9 deletions(-) create mode 100644 docs/adr/0051-edit-multiple-frames-complete-and-onion-skin-in-symbols.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 11ee8d59..8609e3e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +* **Edit Multiple Frames, complete; onion skin inside symbols** (ADR 0051, M1). + * With Edit Multiple Frames on, **Cut, Copy, Paste, Paste in Place and Clear** act on the + artwork selected on every keyframe between the markers. Paste in Place puts artwork copied + from several keyframes back keyframe by keyframe, and artwork copied on one frame onto every + keyframe; Paste puts it on the current frame. + * **Free Transform** shows one box around the selection on every keyframe and scales, rotates + and moves it all about one pivot, one undo step per drag. **Align** (To Stage too), + **Rotate 90°** and **Flip** work across keyframes, and so do the arrow keys. + * Merge-drawing shapes moved, transformed or pasted there **merge again** on their own + keyframe, so drawings stay connected. + * **Onion skin and Edit Multiple Frames work inside a symbol** edited in place, on the + symbol's own timeline. + * Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, + `frames.paste`, `frames.merge`. + * **Raw points, snapping while drawing, and symbols edited in place** (ADR 0045, issue #42, M1). * **Add a point** on a merged drawing's line or fill edge with the Pen's Alt-click or a Subselection double-click: every shape on that edge gets it, and the curve keeps its shape. diff --git a/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md b/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md index e0a17ec5..3eef7525 100644 --- a/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md +++ b/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md @@ -154,7 +154,7 @@ nothing was copied. * the parent symbol's frame moving with the open one (a nested graphic shows the frame it was opened at), and onion skin and Edit Multiple Frames (ADR 0047) while a symbol is open in place: the stage then draws a picture of the symbol, so both switch off (`frames.*` commands - still work on the open timeline); + still work on the open timeline). ADR 0051 turns both on there; * deleting a point where three or more edges meet; * width profiles in the merge (ADR 0042); * a marquee across layers with the Subselection tool (Animate keeps it on one layer too). diff --git a/docs/adr/0047-onion-skin-and-edit-multiple-frames.md b/docs/adr/0047-onion-skin-and-edit-multiple-frames.md index b21ccd77..33cbc534 100644 --- a/docs/adr/0047-onion-skin-and-edit-multiple-frames.md +++ b/docs/adr/0047-onion-skin-and-edit-multiple-frames.md @@ -112,6 +112,7 @@ and from watching the program; nothing was copied. * per-layer onion skin toggles, and onion skin inside a symbol being edited in place; * Edit Multiple Frames deleting, transforming (scale, rotate), copying or recolouring across keyframes; it moves only. Raw (merge) shapes moved there are not merged again with what - they land on; + they land on. (Done in ADR 0051, except recolouring; onion skin inside a symbol open in + place too.) * a marker drag that also scrolls the timeline; * onion skin in Test Movie and exports (never: it is an editing aid). diff --git a/docs/adr/0051-edit-multiple-frames-complete-and-onion-skin-in-symbols.md b/docs/adr/0051-edit-multiple-frames-complete-and-onion-skin-in-symbols.md new file mode 100644 index 00000000..3645d4c7 --- /dev/null +++ b/docs/adr/0051-edit-multiple-frames-complete-and-onion-skin-in-symbols.md @@ -0,0 +1,120 @@ +# ADR 0051: Edit Multiple Frames, complete; onion skin inside symbols + +* Status: accepted (2026-11-11) +* Relates to: ADR 0047 (onion skin and Edit Multiple Frames), ADR 0045 (symbols edited in place), + ADR 0031 / 0041 (merge drawing, the Selection tool on raw shapes), ADR 0004 (destructive + actions), ADR 0017 (plug-in policy), ADR 0040 (interface languages) + +## Context + +ADR 0047 shipped Edit Multiple Frames as a move-only tool. Raw (merge-drawing) shapes it moved +were not merged again with what they landed on. ADR 0045 switched both onion skin and Edit +Multiple Frames off while a symbol was open in place, because the stage then draws a picture +document of the symbol rather than the scene. Artists coming from Animate expect the rest of +Edit Multiple Frames: delete, cut, copy and paste across keyframes, Free Transform of the whole +multi-frame selection about one pivot, Align, arrow nudges, and onion skin inside the symbol +they are animating. + +Behaviour was learned from Adobe's public help pages on onion skinning and Edit Multiple Frames +and from watching the program. Nothing was copied. + +## Decision + +1. **Commands on explicit items.** As in ADR 0047, the multi-frame selection is a list of + `FrameItem { layer, frame (the keyframe's first frame), element }` kept by the shell. Every + edit is a `frames.*` command (`crates/engine/src/multi.rs`) taking `{first, last}` (the + markers) and `items?`. An item that the markers don't show, or that sits on a hidden or + locked layer, is refused and nothing changes. Without `items`, a command acts on everything + shown. Each command is one undo step, and each answers with `items`, the selection + afterwards (merged pieces get new ids), so a front end never has to ask again. + * `frames.edit_multiple` (moved from `onion.rs`) moves. `frames.transform` takes a stage + affine `{a..f}` (what Free Transform sends) or `{rotate, scale_x, scale_y, skew_x, skew_y, + pivot?}`, where the pivot defaults to **the centre of every item's bounds together**: one + shared pivot, so each keyframe's copy lands exactly where the same transform of the whole + multi-frame picture puts it. `frames.align {edge, to_stage?}` lines the items up with the + edge of their bounds together. With one item, or with To Stage, it aligns to the stage. + So Align Left on a walk cycle lines every frame's figure up. + * `frames.delete`, `frames.copy`, `frames.cut`. Delete is an undoable routine edit with a + status-bar hint, like `edit.delete` (ADR 0004 tier 3). Whole keyframes are never removed. + * `frames.paste` is **Paste in Place onto the keyframes between the markers**. Each copied + chunk remembers the keyframe it came from (`ClipLayer::frame`, `None` for a copy made on + one frame). A multi-frame copy goes back keyframe by keyframe, onto the target layer's + keyframe covering the frame each chunk came from. If those keyframes are outside the + markers, the chunk is skipped and counted. A one-frame copy goes onto every keyframe of the + layer shown. Artwork from several layers goes back on those layers when they are all + edited there; otherwise everything goes on the active layer (or `layer`). **Paste** + (Ctrl+V) with Edit Multiple Frames on pastes onto the current frame, as Animate does, and + the pasted artwork becomes the multi-frame selection. Without Edit Multiple Frames, a + multi-frame copy pastes like any copy, and several keyframes of one layer count as one + layer (`paste_targets` maps each distinct source layer once). + * **Re-merge.** Raw shapes that moved, were transformed or aligned, or were pasted go back + into the drawing **on their own keyframe** as `draw.drop` does on one frame: taken out, + then `merge_in` on top of what they touch. The editing helpers work at the playhead, so + `at_keyframe` runs them with the playhead on the keyframe's first frame and restores it. + A drag passes `merge: false` on each step and calls `frames.merge {items}` when it ends, + inside the same gesture, so the drag stays one undo step and shapes are not cut while + they pass over others. + * **Motion tweens.** A tween's object can be moved across frames (its path and X/Y keys move + with it, `MotionTween::translate`). Scaling, rotating or skewing it on several frames is + refused with a message, because its look comes from property keys, not one transform. + * **Plug-ins** may call the document edits (`frames.edit_multiple/transform/align/delete/ + merge`). `frames.copy/cut/paste` are refused like every clipboard command. + + *Rejected:* a multi-frame selection inside the engine (`Session::selection` with frames). + Commands already take explicit items, so headless callers and agents get the same power with + no second selection model to keep in step with undo. *Rejected:* a separate multi-frame + clipboard. It would make Copy on one frame and Paste in Place across frames disagree about + what was copied. One clipboard with a frame on each chunk keeps Animate's single clipboard. + +2. **In the editor** (`src/onion.rs`). With Edit Multiple Frames on, the Edit menu, shortcuts + and the stage's right-click menu act on the multi-frame selection: Cut, Copy, Paste (current + frame), Paste in Place (every keyframe), Clear (Delete/Backspace), Select All, Deselect; the + Align panel and Ctrl+Alt+1…6 (To Stage honoured); Rotate 90° and Flip about the shared + centre. The **Free Transform** tool draws one box around the selection on every keyframe, + with the pivot at its centre. Its handles scale (Shift proportional, Alt from the centre), + rotate (Shift 15°) and move it all, one undo step per drag, merged on release. Arrow keys + nudge, one step each, merged. Duplicate, Convert to Symbol, Break Apart, Arrange and + Distribute are disabled there and say why. Status lines go through `trn!`. + +3. **Onion skin inside symbols.** The open symbol's timeline is the timeline both features + compose. `StagePicture::front` names the picture's top layer (the open symbol's instance), + the timeline, its frame and its placement `at`. A render job made with `FrameJob::inside( + front)` draws, when onion settings show anything, the timelines around the symbol as they + are, then `onion::compose_timeline(symbol timeline, frame, skin, eval)` with + `eval = evaluate_timeline_at(doc, tl, f, at)`. That is the instance's own evaluation with + the symbol's layers as top-level ones, so onion frames still interleave layer by layer and + Edit Multiple Frames keeps per-layer keyframes. `compose` for a scene is now this function on + the scene's timeline. The job key mixes in the front, so the frame cache keeps symbol and + scene looks apart. Markers, keyframes-only and every other option refer to the symbol's own + timeline (the playhead and frame count the shell already uses there, ADR 0045). Picking and + bounds were already in the symbol's space. + +## Consequences + +* Edit Multiple Frames now does what Animate users use it for: re-posing, rescaling or + re-aligning a whole animation, and cleaning up or copying artwork across keyframes. Raw + drawings stay connected after a move. +* Onion skin and Edit Multiple Frames work inside a symbol edited in place, rotated instances + (opened upright, ADR 0045) included. +* Measured (optimised dev build, `multi_timings`, 24 keyframes × (144 raw squares + 50 + objects) = 4,656 items shown): + + | Operation | Time | + |---|---| + | List what is shown | 1.4 ms | + | Move 1,200 objects (one drag step) | 2.8 ms | + | Rotate 1,200 objects about the shared pivot | 2.9 ms | + | Move and merge 288 raw squares across 24 keyframes | 5.6 ms | + | Copy 1,200 objects, Paste in Place | 3.1 ms | + | Delete everything shown | 1.8 ms | + + The sample's spinning star with onion skin ±5 inside the symbol renders its tiles in 2.3 ms on + the GPU stage. +* Not in this slice: + * Duplicate, Distribute, Arrange, Convert to Symbol and recolouring across keyframes; + * scaling, rotating or skewing a motion tween's object on several frames (it moves); + * Subselection, the Width tool and point edits across keyframes; + * a pivot the artist can drag (it is the centre of the box, or the opposite handle with + scale, as on one frame); + * per-layer onion skin toggles, and onion skin of the parent timeline's frames around an + open symbol (only the symbol's own frames are composed). diff --git a/docs/adr/README.md b/docs/adr/README.md index 8fb94da0..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 | -| 0051 | M1 track (multi-frame editing) | Edit Multiple Frames, complete; onion skin inside symbols | diff --git a/docs/development.md b/docs/development.md index 7c23c65a..167cd9f7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -6,7 +6,7 @@ cargo build # app + CLI (debug) cargo run # desktop app with the sample cargo run -- --screenshot shots/now.png # draw ~120 frames, save the window, exit -cargo run -- --open --screenshot x.png # palette|shortcuts|files|confirm|selection|transform|points|pen|frames|span|bucket|sound|tlzoom|tlwide|prefs|licenses|zoom +cargo run -- --open --screenshot x.png # palette|shortcuts|files|confirm|selection|transform|points|pen|frames|span|bucket|sound|tlzoom|tlwide|prefs|licenses|zoom|editmultiple|edittransform|onionsymbol cargo run -- --theme high-contrast --scale 200 --screenshot x.png # a palette and interface scale for one run (not saved) cargo test # every crate cargo clippy --all-targets -- -D warnings diff --git a/docs/roadmap.md b/docs/roadmap.md index 780d3774..1fdb52c5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,8 +10,8 @@ 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). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, 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`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **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 inside a symbol. **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. | +| 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. | | 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. | @@ -31,7 +31,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | M | Theme | Exit criteria | |---|---|---| | **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); ~~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~~ ✅. | +| **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); ~~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 deferred (not the bottleneck as tiles); ~~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: 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); not yet: `.fla` variants of the corpus, sound and video items; ~~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~~ ✅. | @@ -109,8 +109,8 @@ Next, in order: drawing; Snap to Objects is Ctrl+Shift+/; **symbols open for editing in place** (double-click an instance or a Library symbol, Ctrl+E; the edit bar's path back), where merge drawing, Selection and Subselection work as on the stage. Not yet: in-place editing - of rotated instances (they open upright), deleting a point where three edges meet, onion - skin and Edit Multiple Frames inside a symbol. + of rotated instances (they open upright), deleting a point where three edges meet. (Onion + skin and Edit Multiple Frames inside a symbol: ADR 0051 ✅.) 1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, ~~shape tweens~~ ✅, ~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), ~~text~~ ✅ (one style per line; per-character styles with the text model), motion tweens, and ~~a larger self-authored From 6e8850705434e3047f04b4f09a93c91d74ae919a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:38:08 -0700 Subject: [PATCH 041/402] docs(adr): reserve ADR 0054 for .fla packages (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..f70942cf 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 | +| 0054 | m4/fla-packages | `.fla` packages: corpus variants and a hardened zip reader | From 5630b514b987c72c5cc43ec2717712c5cb74099a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:23:55 -0700 Subject: [PATCH 042/402] docs: reserve ADR 0053 for Library and Properties polish (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..6261aa89 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 | +| 0053 | M2 Library and Properties polish | Library drag and drop, Swap Bitmap, mixed Properties | From 53c9c57402dfbe1a4742b97da97c014dba21031e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:27:58 -0700 Subject: [PATCH 043/402] feat(engine): library.place takes several items and a sound; element.swap_bitmap (M2) --- crates/engine/src/cmds_draw.rs | 99 ++++++++++++---- crates/engine/src/cmds_library.rs | 42 +++++++ crates/engine/src/cmds_sound.rs | 2 +- crates/engine/src/place_tests.rs | 183 ++++++++++++++++++++++++++++++ crates/engine/src/tests.rs | 12 ++ 5 files changed, 318 insertions(+), 20 deletions(-) create mode 100644 crates/engine/src/place_tests.rs diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 6a980d01..c26d8304 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, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{ColorEffect, 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; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))), c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol), c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))), - c("library.place", "Place Instance", "", None, "{symbol | bitmap, x?, y?}", true, place), + c("library.place", "Place on Stage", "", None, "{symbol | bitmap | sound: id, x?, y?} or {items: [{symbol | bitmap | sound: id}, ..], x?, y?} → {element, elements, sound?}: symbols and bitmaps centred on x, y (default: the stage centre; inside an open symbol, in its space) in the active layer's keyframe at the playhead, selected; a sound goes onto that keyframe, its span grown to fit (one sound per keyframe). One undo step", true, place), ] } @@ -752,21 +752,86 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { Ok(json!({"created": fresh_ids.len()})) } -/// Places a Library item centred on `x`/`y` (default: the stage centre): an instance of -/// `symbol`, or a rectangle of `bitmap`'s size showing it, in the current keyframe, selected. +/// Most items one `library.place` takes. +const MAX_PLACE: usize = 1_000; + +/// Places Library items at `x`/`y` (default: the stage centre), as a drop from the Library +/// 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 { - if let Some(bitmap) = opt_u64(p, "bitmap")? { - return place_bitmap(s, p, anicraft_doc::BitmapId(bitmap)); + 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()))?; + if list.len() > MAX_PLACE { + return Err(EngineError::Param(format!("at most {MAX_PLACE} items at once"))); + } + let mut out = Vec::with_capacity(list.len()); + for v in list { + match crate::cmds_library::entry_of(v)? { + LibraryEntry::Item(i) => out.push(i), + LibraryEntry::Folder(_) => return Err(EngineError::Param("a folder can't be placed; name the items in it".into())), + } + } + out + } + None => match (opt_u64(p, "symbol")?, opt_u64(p, "bitmap")?, opt_u64(p, "sound")?) { + (Some(i), None, None) => vec![LibraryItem::Symbol(SymbolId(i))], + (None, Some(i), None) => vec![LibraryItem::Bitmap(anicraft_doc::BitmapId(i))], + (None, None, Some(i)) => vec![LibraryItem::Sound(anicraft_doc::SoundId(i))], + _ => return Err(EngineError::Param("name one item ('symbol', 'bitmap' or 'sound'), or a list in 'items'".into())), + }, + }; + if items.is_empty() { + return Err(EngineError::Param("nothing to place".into())); } - let sym = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' or 'bitmap' is required".into()))?); - if s.doc.symbol(sym).is_none() { - return Err(EngineError::State(format!("no symbol with id {}", sym.0))); - } - if crate::editing::would_nest(s, sym) { - return Err(EngineError::State("a symbol can't be placed inside itself".into())); + let mut sound = None; + for &i in &items { + if !s.doc.has_item(i) { + return Err(EngineError::State(match i { + LibraryItem::Symbol(id) => format!("no symbol with id {}", id.0), + LibraryItem::Bitmap(id) => format!("no bitmap with id {}", id.0), + LibraryItem::Sound(id) => format!("no sound with id {} in the library", id.0), + })); + } + match i { + LibraryItem::Symbol(id) if crate::editing::would_nest(s, id) => return Err(EngineError::State("a symbol can't be placed inside itself".into())), + LibraryItem::Sound(id) => { + if sound.is_some_and(|x| x != id) { + return Err(EngineError::State("a keyframe holds one sound; place sounds one at a time, on different keyframes or layers".into())); + } + sound = Some(id); + } + _ => {} + } } 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 placed = Vec::new(); + for &i in &items { + match i { + LibraryItem::Symbol(id) => placed.push(place_symbol(s, id, x, y)?), + LibraryItem::Bitmap(id) => placed.push(place_bitmap(s, id, x, y)?), + LibraryItem::Sound(_) => {} + } + } + let mut out = json!({"element": placed.first().map(|e| e.0), "elements": placed.iter().map(|e| e.0).collect::>()}); + if let Some(id) = sound { + if s.active_layer().is_some_and(|l| l.locked) || s.timeline().locked_by_folder(s.layer) { + return Err(EngineError::State("the active layer is locked; unlock it to put a sound on it".into())); + } + out["sound"] = crate::cmds_sound::place(s, &json!({"sound": id.0, "extend": true}))?; + } + if !placed.is_empty() { + s.select_only(placed.iter().copied()); + } + Ok(out) +} + +fn place_symbol(s: &mut Session, sym: SymbolId, x: f32, y: f32) -> Result { let id = ElementId(s.doc.alloc_id()); let el = Element { id, @@ -776,17 +841,14 @@ fn place(s: &mut Session, p: &Value) -> Result { kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.select_only([id]); - Ok(json!({"element": id.0})) + Ok(id) } -fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> Result { +fn place_bitmap(s: &mut Session, bitmap: anicraft_doc::BitmapId, x: f32, y: f32) -> Result { let (name, w, h) = match s.doc.bitmap(bitmap) { Some(b) => (b.name.clone(), b.width as f32, b.height as f32), None => return Err(EngineError::State(format!("no bitmap with id {}", bitmap.0))), }; - 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); let id = ElementId(s.doc.alloc_id()); let el = Element { id, @@ -802,6 +864,5 @@ fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> R }), }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.select_only([id]); - Ok(json!({"element": id.0})) + Ok(id) } diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index 0002b8d4..5f0c80ee 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -25,6 +25,7 @@ pub fn specs() -> Vec { c("library.unused", "Select Unused Items", "", None, "{} → {items: [..]} the items nothing in the movie reaches: not in a scene, nor inside a symbol that is; symbols with a linkage class count as used", false, unused), c("library.delete_unused", "Delete Unused Items", "", None, "{} deletes every item `library.unused` lists (asks first)", true, delete_unused), c("library.set_smoothing", "Allow Smoothing", "", None, "{bitmap, on?: bool (default: toggle)} whether the bitmap is filtered when scaled or turned (off: hard-edged pixels)", true, set_smoothing), + c("element.swap_bitmap", "Swap Bitmap", "", None, "{bitmap} the selected bitmaps and bitmap-filled shapes show another bitmap: a placed bitmap keeps its transform and top-left corner and takes the new bitmap's size; a bitmap fill keeps its shape and fill transform", true, |s, p| s.each_layer(false, |s| swap_bitmap(s, p))), c("element.swap_symbol", "Swap Symbol", "", None, "{symbol} the selected instances show another symbol, keeping their transform, colour effect, blending, filters, looping, actions and instance name", true, |s, p| s.each_layer(false, |s| swap_symbol(s, p))), ] } @@ -395,6 +396,47 @@ fn swap_symbol(s: &mut Session, p: &Value) -> Result { Ok(json!({"swapped": swapped, "symbol": to.0})) } +/// Swap Bitmap (ADR 0053), as Animate's Properties offer on a bitmap. A bitmap placed from the +/// Library is a rectangle of the bitmap's size filled with it: it keeps its transform (so its +/// top-left corner stays put) and becomes the new bitmap's size, and its name follows when it was +/// 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 { + 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 swapped == 0 { + return Err(EngineError::State("select a bitmap, or a shape filled with one, to swap".into())); + } + Ok(json!({"swapped": swapped, "bitmap": to.0})) +} + #[cfg(test)] #[path = "library_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "place_tests.rs"] +mod place_tests; diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index c87a6522..47666910 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -200,7 +200,7 @@ fn sound_param(s: &Session, p: &Value) -> Result { /// Place Sound: the sound goes on the keyframe covering the frame (a blank keyframe is made /// on an empty frame), Animate-style. With `extend`, the layer's last span grows to the sound's /// length so its waveform shows in full. -fn place(s: &mut Session, p: &Value) -> Result { +pub(crate) fn place(s: &mut Session, p: &Value) -> Result { let id = sound_param(s, p)?; let fps = s.doc.stage.fps; let want = s.doc.sound(id).map_or(1, |x| x.movie_frames(fps)); diff --git a/crates/engine/src/place_tests.rs b/crates/engine/src/place_tests.rs new file mode 100644 index 00000000..59e3f687 --- /dev/null +++ b/crates/engine/src/place_tests.rs @@ -0,0 +1,183 @@ +//! Placing Library items (a drop on the stage, Place on Stage) and Swap Bitmap (ADR 0053). + +use crate::Session; +use anicraft_doc::{BitmapId, Element, ElementKind, LibraryItem, Paint, SymbolId, sample}; +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(), + } +} + +fn sym(s: &Session, name: &str) -> u64 { + s.doc.library.iter().find(|x| x.name == name).map(|x| x.id.0).unwrap_or_else(|| panic!("no symbol {name}")) +} + +/// A `w`×`h` bitmap of one colour, added to the Library. +fn add_bitmap(s: &mut Session, name: &str, w: u32, h: u32) -> BitmapId { + let id = BitmapId(s.doc.alloc_id()); + let bytes = anicraft_render::encode_png(w, h, &[255, 0, 0, 255].repeat((w * h) as usize)).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(id, name, bytes).unwrap())); + id +} + +fn add_sound(s: &mut Session, name: &str) -> u64 { + let id = anicraft_doc::SoundId(s.doc.alloc_id()); + let wav = crate::cmds_sound::test_wav(8000, &[0.25; 8000]); + s.doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(id, name, wav).unwrap())); + id.0 +} + +/// Element `id` on the timeline being edited. +fn element(s: &Session, id: u64) -> Element { + s.timeline().layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find(|e| e.id.0 == id).map(|e| (**e).clone()).unwrap_or_else(|| panic!("no element {id}")) +} + +fn shape(e: &Element) -> &anicraft_doc::Shape { + match &e.kind { + ElementKind::Shape(sh) => sh, + k => panic!("not a shape: {k:?}"), + } +} + +#[test] +fn a_drop_places_symbols_bitmaps_and_a_sound_in_one_undo_step() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let bitmap = add_bitmap(&mut s, "red.png", 4, 2); + let sound = add_sound(&mut s, "beep.wav"); + run(&mut s, "timeline.goto", json!({"frame": 3})); + let layer = s.layer; + let before = s.doc.clone(); + let steps = s.history.undo_len(); + let v = run(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"symbol": star}, {"bitmap": bitmap.0}, {"sound": sound}], "x": 200, "y": 120})); + assert_eq!(s.history.undo_len(), steps + 1, "one undo step"); + let ids: Vec = v["elements"].as_array().unwrap().iter().map(|x| x.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 3); + assert_eq!(v["element"], ids[0]); + assert_eq!(s.selection.ids().map(|e| e.0).collect::>(), ids, "what was placed is selected"); + // Symbols stand with their registration point on the drop point; a bitmap is centred on it. + for &id in &ids[..2] { + assert_eq!(element(&s, id).transform.apply(Vec2::ZERO), Vec2::new(200.0, 120.0)); + } + assert_eq!(element(&s, ids[2]).transform.apply(Vec2::new(2.0, 1.0)), Vec2::new(200.0, 120.0)); + // All on the active layer's keyframe at the playhead, the sound too. + assert_eq!(s.layer, layer); + let k = s.active_layer().unwrap().keyframe_at(3).unwrap(); + assert!(ids.iter().all(|id| k.elements.iter().any(|e| e.id.0 == *id))); + assert_eq!(k.sound.as_ref().map(|f| f.sound.0), Some(sound)); + assert_eq!(v["sound"]["sound"], sound); + s.undo().unwrap(); + assert_eq!(s.doc, before, "one undo takes the whole drop back"); +} + +#[test] +fn placing_one_item_keeps_the_old_params_and_takes_a_sound_alone() { + let mut s = Session::new(sample::demo()); + let sound = add_sound(&mut s, "beep.wav"); + let selected: Vec<_> = s.selection.ids().collect(); + let v = run(&mut s, "library.place", json!({"sound": sound})); + assert_eq!(v["elements"], json!([])); + assert!(v["element"].is_null()); + assert_eq!(s.selection.ids().collect::>(), selected, "a sound alone leaves the selection"); + let k = s.active_layer().unwrap().keyframe_at(s.frame).unwrap(); + assert_eq!(k.sound.as_ref().map(|f| f.sound.0), Some(sound)); + // Without a position: the stage centre. + let ball = sym(&s, "Ball"); + let el = run(&mut s, "library.place", json!({"symbol": ball}))["element"].as_u64().unwrap(); + let c = Vec2::new(s.doc.stage.width as f32 / 2.0, s.doc.stage.height as f32 / 2.0); + assert_eq!(element(&s, el).transform.apply(Vec2::ZERO), c); +} + +#[test] +fn placing_refuses_what_it_cannot_do_and_changes_nothing() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let (a, b) = (add_sound(&mut s, "a.wav"), add_sound(&mut s, "b.wav")); + let f = run(&mut s, "library.new_folder", json!({}))["folder"].as_u64().unwrap(); + let before = s.doc.clone(); + assert!(err(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"folder": f}]})).contains("folder")); + assert!(err(&mut s, "library.place", json!({"items": [{"sound": a}, {"sound": b}]})).contains("one sound")); + assert!(err(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"symbol": 999_999}]})).contains("no symbol")); + assert!(err(&mut s, "library.place", json!({"items": []})).contains("nothing")); + assert!(err(&mut s, "library.place", json!({"items": "x"})).contains("list")); + assert!(err(&mut s, "library.place", json!({"items": (0..1001).map(|_| json!({"symbol": ball})).collect::>()})).contains("at most")); + assert!(err(&mut s, "library.place", json!({"symbol": ball, "bitmap": 1})).contains("one item")); + err(&mut s, "library.place", json!({"symbol": ball, "x": 1e300})); + assert!(err(&mut s, "library.place", json!({"symbol": ball, "x": 2e6})).contains("million")); + assert!(err(&mut s, "library.place", json!({"sound": 999_999})).contains("no sound")); + assert_eq!(s.doc, before); + // A locked layer takes neither artwork nor a sound. + let layer = s.layer.0; + run(&mut s, "layer.toggle_lock", json!({"layer": layer})); + let locked = s.doc.clone(); + assert!(err(&mut s, "library.place", json!({"symbol": ball})).contains("locked")); + assert!(err(&mut s, "library.place", json!({"sound": a})).contains("locked")); + assert_eq!(s.doc, locked); +} + +#[test] +fn placing_inside_a_symbol_open_for_editing_uses_its_space() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + run(&mut s, "symbol.edit", json!({"symbol": ball})); + let el = run(&mut s, "library.place", json!({"symbol": star, "x": 5, "y": -7}))["element"].as_u64().unwrap(); + let inside = s.doc.symbol(SymbolId(ball)).unwrap().timeline.layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find(|e| e.id.0 == el).cloned().expect("in the open symbol"); + assert_eq!(inside.transform.apply(Vec2::ZERO), Vec2::new(5.0, -7.0)); + assert!(err(&mut s, "library.place", json!({"items": [{"symbol": star}, {"symbol": ball}]})).contains("inside itself")); +} + +#[test] +fn swap_bitmap_resizes_a_placed_bitmap_and_keeps_a_filled_shape() { + let mut s = Session::new(sample::demo()); + let small = add_bitmap(&mut s, "small.png", 2, 2); + let big = add_bitmap(&mut s, "big.png", 6, 4); + let placed = run(&mut s, "library.place", json!({"bitmap": small.0, "x": 100, "y": 100}))["element"].as_u64().unwrap(); + let corner = element(&s, placed).transform.apply(Vec2::ZERO); + // A drawn rectangle filled with the small bitmap, tiled, on a second layer. + run(&mut s, "layer.new", json!({})); + let drawn = run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 30, "h": 30, "object": true}))["element"].as_u64().unwrap(); + let tiled = Paint::Bitmap { bitmap: small, repeat: true, matrix: Affine::scale(2.0, 2.0) }; + for e in s.editable_keyframe().unwrap().elements_mut_where(|id| id.0 == drawn) { + if let ElementKind::Shape(sh) = &mut e.kind { + sh.fill = Some(tiled.clone()); + } + } + let drawn_path = shape(&element(&s, drawn)).path.clone(); + run(&mut s, "edit.select_all", json!({})); + let steps = s.history.undo_len(); + let v = run(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})); + assert_eq!(v["swapped"], 2, "on both layers"); + assert_eq!(s.history.undo_len(), steps + 1); + let p = element(&s, placed); + assert_eq!(p.name, "big.png", "the name follows the bitmap"); + assert_eq!(p.transform.apply(Vec2::ZERO), corner, "the top-left corner stays"); + assert_eq!(*shape(&p).path, Path::rect(0.0, 0.0, 6.0, 4.0), "the new bitmap's size"); + assert_eq!(shape(&p).fill, Some(Paint::Bitmap { bitmap: big, repeat: false, matrix: Affine::IDENTITY })); + let d = element(&s, drawn); + assert_eq!(shape(&d).path, drawn_path, "a filled shape keeps its outline"); + assert_eq!(shape(&d).fill, Some(Paint::Bitmap { bitmap: big, repeat: true, matrix: Affine::scale(2.0, 2.0) }), "and its fill transform"); + // The old bitmap is now unused; one undo brings it back. + assert!(s.doc.unused_items().contains(&LibraryItem::Bitmap(small))); + s.undo().unwrap(); + assert!(!s.doc.unused_items().contains(&LibraryItem::Bitmap(small))); + // Refusals. + assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": 999_999})).contains("no bitmap")); + assert!(err(&mut s, "element.swap_bitmap", json!({})).contains("'bitmap'")); + run(&mut s, "edit.deselect", json!({})); + assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})).contains("nothing is selected")); + let other = run(&mut s, "draw.rect", json!({"x": 300, "y": 300, "w": 5, "h": 5, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [other]})); + assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})).contains("filled with one")); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a25d0ec2..e1d514c7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -723,12 +723,24 @@ fn panic_hunt_every_command() { let ball = library.doc.library.first().map(|x| x.id.0).unwrap(); library.execute("library.move", &json!({"items": [{"symbol": ball}], "to": inner})).unwrap(); library.execute("library.duplicate", &json!({"symbol": ball})).unwrap(); + // ...and a bitmap placed on the stage, for Swap Bitmap (ADR 0053). + let bm = anicraft_doc::BitmapId(library.doc.alloc_id()); + let png = anicraft_render::encode_png(3, 2, &[0, 0, 255, 255].repeat(6)).unwrap(); + library.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(bm, "b.png", png).unwrap())); + library.execute("library.place", &json!({"bitmap": bm.0})).unwrap(); + hostile.push(json!({"bitmap": bm.0, "items": [{"bitmap": bm.0}, {"symbol": ball}], "x": 3, "y": 4})); hostile.extend([ json!({"items": [{"folder": outer}], "to": inner, "folder": outer, "name": "Hero", "parent": inner, "confirm": true}), json!({"items": [{"folder": inner}, {"symbol": ball}, {"folder": inner}], "to": null, "folder": inner, "name": "a/b", "symbol": ball}), json!({"items": [{"symbol": ball, "folder": outer}, "x", {"sound": u64::MAX}], "to": u64::MAX, "parent": "x", "name": " "}), json!({"items": (0..200).map(|i| json!({"folder": i})).collect::>(), "to": outer, "symbol": ball, "name": "x".repeat(300), "on": "x", "bitmap": 1}), json!({"items": [{"symbol": ball}], "to": outer, "symbol": ball, "name": "Ball copy", "confirm": true}), + // Drops from the Library and Swap Bitmap (ADR 0053): mixed lists, two sounds, far points. + json!({"items": [{"symbol": ball}, {"sound": SOUND}, {"bitmap": u64::MAX}], "x": 1e300, "y": -1e300}), + json!({"items": [{"sound": SOUND}, {"sound": SOUND}, {"symbol": ball}], "x": 999_999, "y": -999_999, "bitmap": 0}), + 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}), ]); 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 1e31d8440cf0670fd534e328385f5bc5dee02264 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:29:12 -0700 Subject: [PATCH 044/402] feat(engine): Convert to Symbol takes a folder and a type (M2) --- crates/engine/src/cmds_draw.rs | 19 +++++++++++---- crates/engine/src/cmds_library.rs | 14 +++++++++-- crates/engine/src/place_tests.rs | 40 +++++++++++++++++++++++++++++-- 3 files changed, 64 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index c26d8304..4c2e0e8c 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { 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))), c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, false))), c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))), - c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol), + c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name? (default: the next free “Symbol n”; a name the folder holds gets a number), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level)} → {symbol, instance, name, layer, folder} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol), c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))), c("library.place", "Place on Stage", "", None, "{symbol | bitmap | sound: id, x?, y?} or {items: [{symbol | bitmap | sound: id}, ..], x?, y?} → {element, elements, sound?}: symbols and bitmaps centred on x, y (default: the stage centre; inside an open symbol, in its space) in the active layer's keyframe at the playhead, selected; a sound goes onto that keyframe, its span grown to fit (one sound per keyframe). One undo step", true, place), ] @@ -648,8 +648,14 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { let Some(&top) = layers.first() else { return Err(EngineError::State("select something to convert".into())); }; - // The next free “Symbol n” at the Library's top level, where new symbols go (ADR 0050). - let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| s.doc.numbered_name(None, "Symbol", s.doc.library.len() + 1)); + // Into the folder asked for (ADR 0053), else the top level; the name is free there: the + // next free “Symbol n”, or the name asked for with a number when the folder has it already. + let folder = crate::cmds_library::opt_folder(s, p, "folder")?; + let kind = opt_str(p, "kind")?.map(crate::cmds_library::kind_of).transpose()?.unwrap_or(SymbolKind::Graphic); + let name: String = match opt_str(p, "name")? { + Some(n) => s.doc.unique_name(folder, n), + None => s.doc.numbered_name(folder, "Symbol", s.doc.library.len() + 1), + }; let bounds = s.selection_bounds(); let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; let sym_id = SymbolId(s.doc.alloc_id()); @@ -694,10 +700,13 @@ 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: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: inner } })); + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, timeline: Timeline { layers: inner } })); + if folder.is_some() { + s.doc.place_entry(LibraryEntry::Item(LibraryItem::Symbol(sym_id)), folder); + } s.layer = top; s.select_only([inst_id]); - Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0})) + Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0, "folder": folder.map(|f| f.0)})) } fn break_apart(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index 5f0c80ee..a607bec6 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -85,7 +85,7 @@ fn describe(e: LibraryEntry) -> String { } } -fn opt_folder(s: &Session, p: &Value, key: &str) -> Result> { +pub(crate) fn opt_folder(s: &Session, p: &Value, key: &str) -> Result> { match p.get(key) { None | Some(Value::Null) => Ok(None), Some(v) => { @@ -98,7 +98,17 @@ fn opt_folder(s: &Session, p: &Value, key: &str) -> Result> { } } -fn kind_key(k: SymbolKind) -> &'static str { +/// The symbol type `key` names (`graphic`, `movie_clip` or `button`). +pub(crate) fn kind_of(key: &str) -> Result { + match key { + "graphic" => Ok(SymbolKind::Graphic), + "movie_clip" | "movie clip" => Ok(SymbolKind::MovieClip), + "button" => Ok(SymbolKind::Button), + _ => Err(EngineError::Param(format!("unknown symbol type '{key}' (graphic, movie_clip or button)"))), + } +} + +pub(crate) fn kind_key(k: SymbolKind) -> &'static str { match k { SymbolKind::Graphic => "graphic", SymbolKind::MovieClip => "movie_clip", diff --git a/crates/engine/src/place_tests.rs b/crates/engine/src/place_tests.rs index 59e3f687..6f4f9c05 100644 --- a/crates/engine/src/place_tests.rs +++ b/crates/engine/src/place_tests.rs @@ -1,7 +1,8 @@ -//! Placing Library items (a drop on the stage, Place on Stage) and Swap Bitmap (ADR 0053). +//! Placing Library items (a drop on the stage, Place on Stage), Swap Bitmap and Convert to Symbol +//! into a folder (ADR 0053). use crate::Session; -use anicraft_doc::{BitmapId, Element, ElementKind, LibraryItem, Paint, SymbolId, sample}; +use anicraft_doc::{BitmapId, Element, ElementKind, FolderId, LibraryEntry, LibraryItem, Paint, SymbolId, SymbolKind, sample}; use anicraft_geom::{Affine, Path, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -181,3 +182,38 @@ fn swap_bitmap_resizes_a_placed_bitmap_and_keeps_a_filled_shape() { run(&mut s, "element.select", json!({"ids": [other]})); assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})).contains("filled with one")); } + +#[test] +fn convert_to_symbol_goes_into_the_folder_asked_for_with_a_free_name() { + let mut s = Session::new(sample::demo()); + let props = run(&mut s, "library.new_folder", json!({"name": "Props"}))["folder"].as_u64().unwrap(); + let entry = |v: &Value| LibraryEntry::Item(LibraryItem::Symbol(SymbolId(v["symbol"].as_u64().unwrap()))); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "object": true})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Ball", "kind": "movie_clip", "folder": props})); + assert_eq!(v["folder"], props); + assert_eq!(v["name"], "Ball", "Props has no Ball yet (the top level's doesn't count)"); + assert_eq!(s.doc.parent_of(entry(&v)), Some(FolderId(props))); + assert_eq!(s.doc.entry_path(entry(&v)), "Props/Ball"); + assert_eq!(s.doc.symbol(SymbolId(v["symbol"].as_u64().unwrap())).unwrap().kind, SymbolKind::MovieClip); + // The same name again in that folder gets a number; no name gives the next free “Symbol n”. + run(&mut s, "draw.rect", json!({"x": 50, "y": 10, "w": 20, "h": 20, "object": true})); + assert_eq!(run(&mut s, "modify.convert_to_symbol", json!({"name": "ball", "folder": props}))["name"], "ball 2"); + run(&mut s, "draw.rect", json!({"x": 90, "y": 10, "w": 20, "h": 20, "object": true})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"folder": props})); + assert!(v["name"].as_str().unwrap().starts_with("Symbol ")); + assert_eq!(s.doc.symbol(SymbolId(v["symbol"].as_u64().unwrap())).unwrap().kind, SymbolKind::Graphic, "graphic by default"); + // Without a folder: the top level, as before. + run(&mut s, "draw.rect", json!({"x": 130, "y": 10, "w": 20, "h": 20, "object": true})); + let v = run(&mut s, "modify.convert_to_symbol", json!({})); + assert!(v["folder"].is_null()); + assert_eq!(s.doc.parent_of(entry(&v)), None); + // Refusals change nothing. + run(&mut s, "draw.rect", json!({"x": 170, "y": 10, "w": 20, "h": 20, "object": true})); + let before = s.doc.clone(); + assert!(err(&mut s, "modify.convert_to_symbol", json!({"folder": 999_999})).contains("no folder")); + assert!(err(&mut s, "modify.convert_to_symbol", json!({"kind": "sprite"})).contains("symbol type")); + assert_eq!(s.doc, before); + // The file keeps where it went. + let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap(); + assert_eq!(back.library_tree, s.doc.library_tree); +} From cb4f1c61cf763c8a7344afc2117519a163e8059c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:33:36 -0700 Subject: [PATCH 045/402] feat(shell): mixed on every Properties row, Swap Bitmap; Type sets every selected symbol (M2) --- crates/engine/src/cmds_draw.rs | 47 +++--- src/main.rs | 1 + src/mixed.rs | 293 +++++++++++++++++++++++++++++++++ src/panels.rs | 100 ++++++----- 4 files changed, 381 insertions(+), 60 deletions(-) create mode 100644 src/mixed.rs diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 4c2e0e8c..a84fe80a 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { 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))), - c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the selected instance's)}", true, set_symbol_kind), + 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("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))), @@ -526,30 +526,33 @@ fn set_loop(s: &mut Session, p: &Value) -> Result { /// A symbol's kind, for every instance of it: a graphic keeps step with the timeline it is /// placed on, a movie clip plays its own timeline on a loop, a button shows its Up frame. fn set_symbol_kind(s: &mut Session, p: &Value) -> Result { - let kind = match str_req(p, "kind")? { - "graphic" => SymbolKind::Graphic, - "movie_clip" | "movie clip" => SymbolKind::MovieClip, - "button" => SymbolKind::Button, - other => return Err(EngineError::Param(format!("unknown symbol kind '{other}' (graphic, movie_clip or button)"))), - }; - let id = match opt_u64(p, "symbol")? { - Some(id) => SymbolId(id), + let kind = crate::cmds_library::kind_of(str_req(p, "kind")?)?; + let ids: Vec = match opt_u64(p, "symbol")? { + Some(id) => vec![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()))? + // The symbols of the selected instances, on every layer (ADR 0053: a "mixed" Type + // row sets them all), in selection order. + let mut ids = Vec::new(); + for (layer, sel) in s.selection.iter() { + if let Some(ElementKind::Symbol { symbol, .. }) = s.elements_on(layer).iter().find(|e| e.id == sel).map(|e| &e.kind) + && !ids.contains(symbol) + { + ids.push(*symbol); + } + } + if ids.is_empty() { + return Err(EngineError::State(if s.selection.is_empty() { "select a symbol instance, or pass 'symbol'".into() } else { "the selection is not a symbol instance".into() })); + } + ids } }; - let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; - std::sync::Arc::make_mut(sym).kind = kind; - Ok(json!({"symbol": id.0, "kind": format!("{kind:?}")})) + for id in &ids { + let sym = s.doc.library.iter_mut().find(|x| x.id == *id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + if sym.kind != kind { + std::sync::Arc::make_mut(sym).kind = kind; + } + } + Ok(json!({"symbol": ids.first().map(|i| i.0), "symbols": ids.iter().map(|i| i.0).collect::>(), "kind": format!("{kind:?}")})) } fn rename(s: &mut Session, p: &Value) -> Result { diff --git a/src/main.rs b/src/main.rs index 38f7fe49..c3592603 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,6 +36,7 @@ mod icons; mod keymap; mod library; mod menus; +mod mixed; mod motion_editor; mod panels; mod motion_path; diff --git a/src/mixed.rs b/src/mixed.rs new file mode 100644 index 00000000..8fff5b41 --- /dev/null +++ b/src/mixed.rs @@ -0,0 +1,293 @@ +//! Which Properties rows say "mixed" for a selection of several elements (ADR 0053). +//! +//! A row is mixed when the selected elements it applies to differ there: the field shows the +//! first one's value, and a change applies to all of them. Each row compares only the elements +//! 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 std::sync::Arc; + +/// The rows whose values differ across the selection. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Mixed { + pub scale: bool, + pub rotation: bool, + /// The colour effect (the Alpha row). + pub alpha: bool, + /// The instances show different symbols (the Symbol row, Swap…). + pub symbol: bool, + /// Their symbols are of different types. + pub kind: bool, + pub filters: bool, + pub blend: bool, + pub looping: bool, + pub first_frame: bool, + pub fill: bool, + /// The bitmap a bitmap fill shows (Swap Bitmap). + pub bitmap: bool, + /// Stroke colour or width. + pub stroke: bool, + pub profile: bool, + /// Line style, caps, joins and dashes. + pub style: bool, +} + +/// Whether `values` holds two that differ. +fn differ(mut values: impl Iterator) -> bool { + match values.next() { + Some(first) => values.any(|v| v != first), + None => false, + } +} + +/// Close enough to show the same number in a field. +fn near(a: f32, b: f32) -> bool { + (a - b).abs() <= 1e-4 +} + +fn differ_f32(values: impl Iterator) -> bool { + let v: Vec = values.collect(); + v.first().is_some_and(|f| v.iter().any(|x| !near(*x, *f))) +} + +/// What Properties shows as mixed for `all` (the selection, in order). +pub fn of(doc: &Document, all: &[Arc]) -> Mixed { + if all.len() < 2 { + return Mixed::default(); + } + let kind_of = |e: &Element| match &e.kind { + ElementKind::Symbol { symbol, .. } => doc.symbol(*symbol).map(|s| s.kind), + _ => None, + }; + let decomposed: Vec<_> = all.iter().map(|e| e.transform.decompose()).collect(); + let instances = || all.iter().filter(|e| matches!(e.kind, ElementKind::Symbol { .. })); + // Blending and filters: movie clips and buttons (Animate offers them on those only). + let clips = || all.iter().filter(|e| kind_of(e).is_some_and(|k| k != SymbolKind::Graphic)); + let graphics = || all.iter().filter(|e| kind_of(e) == Some(SymbolKind::Graphic)); + let shapes: Vec<&Shape> = all + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(s) => Some(s), + _ => None, + }) + .collect(); + let strokes = || shapes.iter().filter_map(|s| s.stroke.as_ref()); + 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)), + symbol: differ(instances().filter_map(|e| match &e.kind { + ElementKind::Symbol { symbol, .. } => Some(*symbol), + _ => None, + })), + kind: differ(instances().map(|e| kind_of(e))), + filters: differ(clips().filter_map(|e| match &e.kind { + ElementKind::Symbol { filters, .. } => Some(filters), + _ => None, + })), + blend: differ(clips().filter_map(|e| match &e.kind { + ElementKind::Symbol { blend, .. } => Some(*blend), + _ => None, + })), + looping: differ(graphics().filter_map(|e| match &e.kind { + ElementKind::Symbol { loop_mode, .. } => Some(*loop_mode), + _ => None, + })), + first_frame: differ(graphics().filter_map(|e| match &e.kind { + ElementKind::Symbol { first_frame, .. } => Some(*first_frame), + _ => None, + })), + fill: differ(shapes.iter().map(|s| s.fill.as_ref())), + bitmap: differ(shapes.iter().filter_map(|s| match &s.fill { + Some(Paint::Bitmap { bitmap, .. }) => Some(*bitmap), + _ => None, + })), + // A shape without a line differs from one with a line. + stroke: differ(shapes.iter().map(|s| s.stroke.as_ref().map(|st| (st.color, st.width.to_bits())))), + profile: differ(strokes().map(|st| st.profile.as_ref())), + style: differ(strokes().map(|st| &st.style)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::sample; + use serde_json::json; + + fn run(s: &mut Session, id: &str, p: serde_json::Value) -> serde_json::Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) + } + + fn id(v: &serde_json::Value) -> u64 { + v["element"].as_u64().unwrap() + } + + /// The selection's elements, in order, from every layer. + fn selected(s: &Session) -> Vec> { + s.selection.iter().filter_map(|(l, e)| s.elements_on(l).iter().find(|x| x.id == e).cloned()).collect() + } + + fn mixed(s: &Session) -> Mixed { + of(&s.doc, &selected(s)) + } + + fn select(s: &mut Session, ids: &[u64]) { + run(s, "element.select", json!({"ids": ids})); + } + + /// Two movie clips and a graphic of the sample's Ball and Star, on two layers, and two shapes. + fn session() -> (Session, [u64; 3], [u64; 2]) { + let mut s = Session::new(sample::demo()); + run(&mut s, "edit.deselect", json!({})); + let sym = |s: &Session, n: &str| s.doc.library.iter().find(|x| x.name == n).unwrap().id.0; + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let a = id(&run(&mut s, "library.place", json!({"symbol": ball, "x": 100, "y": 100}))); + let b = id(&run(&mut s, "library.place", json!({"symbol": ball, "x": 200, "y": 100}))); + run(&mut s, "layer.new", json!({})); + let g = id(&run(&mut s, "library.place", json!({"symbol": star, "x": 300, "y": 100}))); + run(&mut s, "symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"})); + run(&mut s, "symbol.set_kind", json!({"symbol": star, "kind": "graphic"})); + let r1 = id(&run(&mut s, "draw.rect", json!({"x": 10, "y": 300, "w": 20, "h": 20, "fill": "#ff0000", "stroke": "#000000", "stroke_width": 2, "object": true}))); + let r2 = id(&run(&mut s, "draw.rect", json!({"x": 60, "y": 300, "w": 20, "h": 20, "fill": "#ff0000", "stroke": "#000000", "stroke_width": 2, "object": true}))); + (s, [a, b, g], [r1, r2]) + } + + #[test] + fn alike_elements_are_not_mixed_and_one_element_never_is() { + let (mut s, [a, b, g], [r1, r2]) = session(); + select(&mut s, &[a, b, g, r1, r2]); + // Positions differ, and so do the instances' symbols and types (Ball and Star): those + // rows say mixed; nothing else does. + assert_eq!(mixed(&s), Mixed { symbol: true, kind: true, ..Mixed::default() }); + select(&mut s, &[a, b]); + assert_eq!(mixed(&s), Mixed::default()); + select(&mut s, &[a]); + assert_eq!(mixed(&s), Mixed::default()); + } + + #[test] + fn scale_rotation_and_alpha_rows() { + let (mut s, [a, b, g], _) = session(); + 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); + 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); + // 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); + } + + #[test] + fn filters_and_blending_rows_compare_movie_clips_only() { + let (mut s, [a, b, g], [r1, _]) = session(); + select(&mut s, &[b]); + run(&mut s, "element.set_blend", json!({"mode": "multiply"})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]})); + select(&mut s, &[a, b, g, r1]); + let m = mixed(&s); + assert!(m.blend && m.filters); + // A graphic and a shape beside one movie clip: nothing to compare. + select(&mut s, &[b, g, r1]); + let m = mixed(&s); + assert!(!m.blend && !m.filters); + // Setting either across the selection makes the movie clips alike. + select(&mut s, &[a, b, g]); + run(&mut s, "element.set_blend", json!({"mode": "screen"})); + run(&mut s, "element.set_filters", json!({"filters": []})); + let m = mixed(&s); + assert!(!m.blend && !m.filters); + } + + #[test] + fn looping_and_first_frame_rows_compare_graphics_only() { + let (mut s, [a, _, g], _) = session(); + let star = s.doc.library.iter().find(|x| x.name == "Star").unwrap().id.0; + let g2 = id(&run(&mut s, "library.place", json!({"symbol": star, "x": 400, "y": 100}))); + select(&mut s, &[g2]); + run(&mut s, "element.set_loop", json!({"loop": "single_frame", "first_frame": 1})); + select(&mut s, &[g, g2, a]); + let m = mixed(&s); + assert!(m.looping && m.first_frame); + run(&mut s, "element.set_loop", json!({"loop": "play_once", "first_frame": 0})); + let m = mixed(&s); + assert!(!m.looping && !m.first_frame); + } + + #[test] + fn symbol_and_type_rows_and_editing_the_type_sets_every_symbol() { + let (mut s, [a, b, g], _) = session(); + select(&mut s, &[a, b]); + assert!(!mixed(&s).symbol && !mixed(&s).kind); + select(&mut s, &[a, g]); + assert!(mixed(&s).symbol && mixed(&s).kind); + // Type: every selected instance's symbol, in one undo step. + let v = run(&mut s, "symbol.set_kind", json!({"kind": "button"})); + assert_eq!(v["symbols"].as_array().map(Vec::len), Some(2)); + assert!(!mixed(&s).kind && mixed(&s).symbol); + s.undo().unwrap(); + assert!(mixed(&s).kind); + // Swap Symbol sets them all too. + let ball = s.doc.library.iter().find(|x| x.name == "Ball").unwrap().id.0; + run(&mut s, "element.swap_symbol", json!({"symbol": ball})); + assert!(!mixed(&s).symbol); + } + + #[test] + fn fill_and_bitmap_rows() { + let (mut s, _, [r1, r2]) = session(); + select(&mut s, &[r2]); + run(&mut s, "element.set_fill", json!({"color": "#00ff00"})); + select(&mut s, &[r1, r2]); + assert!(mixed(&s).fill); + run(&mut s, "element.set_fill", json!({"color": "#0000ff"})); + assert!(!mixed(&s).fill); + // Fill on beside fill off is mixed. + select(&mut s, &[r1]); + run(&mut s, "element.set_fill", json!({"color": null})); + select(&mut s, &[r1, r2]); + assert!(mixed(&s).fill); + // Two placed bitmaps of different images. + let mut ids = Vec::new(); + for (n, w) in [("a.png", 2), ("b.png", 3)] { + let b = anicraft_engine::doc::BitmapId(s.doc.alloc_id()); + let png = anicraft_engine::render::encode_png(w, 2, &[0, 0, 255, 255].repeat(w as usize * 2)).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_engine::doc::Bitmap::from_png(b, n, png).unwrap())); + ids.push((b, id(&run(&mut s, "library.place", json!({"bitmap": b.0}))))); + } + select(&mut s, &[ids[0].1, ids[1].1]); + assert!(mixed(&s).bitmap && mixed(&s).fill); + run(&mut s, "element.swap_bitmap", json!({"bitmap": ids[0].0.0})); + assert!(!mixed(&s).bitmap); + } + + #[test] + fn stroke_profile_and_style_rows() { + let (mut s, _, [r1, r2]) = session(); + select(&mut s, &[r2]); + run(&mut s, "element.set_stroke", json!({"width": 6})); + select(&mut s, &[r1, r2]); + assert!(mixed(&s).stroke && !mixed(&s).profile && !mixed(&s).style); + run(&mut s, "element.set_stroke", json!({"width": 3})); + assert!(!mixed(&s).stroke); + select(&mut s, &[r1]); + run(&mut s, "stroke.set_profile", json!({"profile": "taper_both"})); + run(&mut s, "element.set_stroke", json!({"style": "dashed"})); + select(&mut s, &[r1, r2]); + let m = mixed(&s); + assert!(m.profile && m.style && !m.stroke); + run(&mut s, "stroke.set_profile", json!({"profile": "taper_both"})); + run(&mut s, "element.set_stroke", json!({"style": "dashed"})); + let m = mixed(&s); + assert!(!m.profile && !m.style); + } +} diff --git a/src/panels.rs b/src/panels.rs index a22c3809..e944c954 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -485,7 +485,8 @@ fn mixed(ui: &mut egui::Ui, differs: bool) { /// 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; - let differs = |f: &dyn Fn(&anicraft_engine::doc::Element) -> f32| all.iter().any(|x| (f(x) - f(e)).abs() > 1e-4); + // Which rows differ across the selection (ADR 0053): they say "mixed", and a change sets all. + let m = crate::mixed::of(&app.s.doc, all); if let ElementKind::Symbol { symbol, events, .. } = &e.kind && app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic) { @@ -516,35 +517,32 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E } }); } - let scale_mixed = many && (differs(&|x| x.transform.decompose().sx) || differs(&|x| x.transform.decompose().sy)); row(ui, tr!("Scale"), |ui| { let a = ui.add(egui::DragValue::new(&mut sx).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale width")); let b = ui.add(egui::DragValue::new(&mut sy).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale height")); if a.changed() || b.changed() { live(app, tr_noop!("Scale"), "element.set_transform", json!({"sx": sx / 100.0, "sy": sy / 100.0})); } - mixed(ui, scale_mixed); + mixed(ui, m.scale); }); - let rot_mixed = many && differs(&|x| x.transform.decompose().rotation); row(ui, tr!("Rotation"), |ui| { if ui.add(egui::DragValue::new(&mut rot).suffix("°").speed(0.5).range(-360.0..=360.0).max_decimals(1)).named(tr!("Rotation")).changed() { live(app, tr_noop!("Rotate"), "element.set_transform", json!({"rotation": rot})); } - mixed(ui, rot_mixed); + mixed(ui, m.rotation); }); let mut alpha = e.color.alpha * 100.0; - let alpha_mixed = many && differs(&|x| x.color.alpha); 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, alpha_mixed); + mixed(ui, m.alpha); }); // 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) { - filter_rows(app, ui, filters); + filter_rows(app, ui, filters, m.filters); } if let ElementKind::Symbol { symbol, blend, .. } = &e.kind && app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic) @@ -552,14 +550,15 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E let current = *blend; row_prose(ui, tr!("Blending"), |ui| { egui::ComboBox::from_id_salt("prop_blend").selected_text(crate::i18n::t(current.label())).show_ui(ui, |ui| { - for m in anicraft_engine::doc::BlendMode::ALL { - if ui.selectable_label(m == current, crate::i18n::t(m.label())).clicked() && m != current { - app.run("element.set_blend", json!({"mode": m.key()})); + for mode in anicraft_engine::doc::BlendMode::ALL { + if ui.selectable_label(mode == current, crate::i18n::t(mode.label())).clicked() && (mode != current || m.blend) { + app.run("element.set_blend", json!({"mode": mode.key()})); } } }) .response .set_name(tr!("Blending")); + mixed(ui, m.blend); }); } if let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = &e.kind @@ -576,13 +575,15 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E (SymbolKind::MovieClip, "movie_clip", tr!("Plays its own timeline on a loop, from when it appears")), (SymbolKind::Button, "button", tr!("Shows its Up frame")), ] { - if ui.selectable_label(kind == k, symbol_kind_label(k)).on_hover_text(tip).clicked() && kind != k { - app.run("symbol.set_kind", json!({"symbol": symbol.0, "kind": id})); + if ui.selectable_label(kind == k, symbol_kind_label(k)).on_hover_text(tip).clicked() && (kind != k || m.kind) { + // Every selected instance's symbol (ADR 0053), or just this one's. + app.run("symbol.set_kind", if many { json!({"kind": id}) } else { json!({"symbol": symbol.0, "kind": id}) }); } } }) .response .set_name(tr!("Symbol type")); + mixed(ui, m.kind); }); // Swap Symbol (ADR 0050): another symbol in this instance's place, keeping its // transform, colour effect, filters and name. @@ -597,7 +598,7 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E for (id, path) in &choices { if ui.selectable_label(*id == current, path.as_str()).clicked() { ui.close(); - if *id != current { + if *id != current || m.symbol { app.run("element.swap_symbol", json!({"symbol": id.0})); } } @@ -607,6 +608,7 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E .response .on_hover_text(tr!("Show another symbol here, keeping position, colour effect, filters and name")) .set_name(tr!("Swap Symbol")); + mixed(ui, m.symbol); }); // The class scripts know the symbol by (kept, not run; ADR 0013), in documents // that use scripts. @@ -623,17 +625,18 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E } if kind == SymbolKind::Graphic { let names = [(LoopMode::Loop, "loop", tr!("Loop")), (LoopMode::PlayOnce, "play_once", tr!("Play once")), (LoopMode::SingleFrame, "single_frame", tr!("Single frame"))]; - let current = names.iter().find(|(m, _, _)| m == loop_mode).map_or(tr!("Loop"), |(_, _, l)| l); + let current = names.iter().find(|(mode, _, _)| mode == loop_mode).map_or(tr!("Loop"), |(_, _, l)| l); row_prose(ui, tr!("Looping"), |ui| { egui::ComboBox::from_id_salt("prop_loop").width(150.0).selected_text(current).show_ui(ui, |ui| { - for (m, id, l) in names { - if ui.selectable_label(m == *loop_mode, l).clicked() && m != *loop_mode { + for (mode, id, l) in names { + if ui.selectable_label(mode == *loop_mode, l).clicked() && (mode != *loop_mode || m.looping) { app.run("element.set_loop", json!({"loop": id})); } } }) .response .set_name(tr!("Looping")); + mixed(ui, m.looping); }); let mut first = first_frame + 1; row(ui, tr!("First frame"), |ui| { @@ -642,6 +645,7 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E live(app, tr_noop!("First frame"), "element.set_loop", json!({"first_frame": first.saturating_sub(1)})); } ui.label(text(Type::Caption, tr!("of {frames}", frames = frames))); + mixed(ui, m.first_frame); }); } else if kind == SymbolKind::MovieClip { ui.label(text(Type::Caption, trn!("Plays its {n}-frame timeline on a loop from when it appears.", "Plays its {n}-frame timeline on a loop from when it appears.", frames))); @@ -664,14 +668,6 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if let ElementKind::Shape(sh) = &e.kind { ui.add_space(4.0); let fill = sh.fill.as_ref().map(Paint::primary_color); - // Mixed: the selected shapes' fills, or lines, are not all alike. - let shapes: Vec<&anicraft_engine::doc::Shape> = all.iter().filter_map(|x| match &x.kind { - ElementKind::Shape(s) => Some(s), - _ => None, - }).collect(); - let fill_mixed = shapes.iter().any(|s| s.fill.as_ref().map(Paint::primary_color) != fill); - let line = |s: &anicraft_engine::doc::Shape| s.stroke.as_ref().map(|st| (st.color, st.width.to_bits())); - let stroke_mixed = shapes.iter().any(|s| line(s) != line(sh)); row(ui, tr!("Fill"), |ui| { let is_grad = matches!(sh.fill, Some(Paint::Linear { .. } | Paint::Radial { .. })); let mut c = rgb(fill.unwrap_or(Rgba::WHITE)); @@ -682,14 +678,14 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if crate::theme::checkbox(ui, &mut on, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off")).changed() { app.run("element.set_fill", if on { json!({"color": hex(c)}) } else { json!({"color": null}) }); } - if let Some(Paint::Bitmap { bitmap, .. }) = &sh.fill { - let name = app.s.doc.bitmap(*bitmap).map_or_else(|| tr!("missing bitmap").to_string(), |b| format!("{} · {}×{}", b.name, b.width, b.height)); - ui.label(text(Type::Caption, name)); - } else if is_grad { + if is_grad { ui.label(text(Type::Caption, tr!("gradient"))); } - mixed(ui, fill_mixed); + mixed(ui, m.fill); }); + if let Some(Paint::Bitmap { bitmap, .. }) = &sh.fill { + bitmap_row(app, ui, *bitmap, m.bitmap); + } let mut sc = rgb(sh.stroke.as_ref().map_or(app.s.style.stroke, |s| s.color)); let mut sw = sh.stroke.as_ref().map_or(0.0, |s| s.width); row(ui, tr!("Stroke"), |ui| { @@ -699,17 +695,16 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if ui.add(egui::DragValue::new(&mut sw).suffix(" px").speed(0.1).range(0.0..=200.0).max_decimals(1)).named(tr!("Stroke width")).changed() { live(app, tr_noop!("Stroke width"), "element.set_stroke", json!({"width": sw})); } - mixed(ui, stroke_mixed); + mixed(ui, m.stroke); }); if let Some(st) = &sh.stroke { // The width profile, as Animate's Width menu: built-ins with a picture of each. let current = st.profile.clone(); - if let Some(pick) = profile_picker(ui, ProfileRow::Selection, current.as_ref()) { + if let Some(pick) = profile_picker(ui, ProfileRow::Selection, current.as_ref(), m.profile) { app.run("stroke.set_profile", json!({"profile": pick.key()})); } // Style, caps and joins (ADR 0046). - let style_mixed = shapes.iter().any(|s| s.stroke.as_ref().map(|x| &x.style) != Some(&st.style)); - if let Some(edit) = line_style_rows(ui, ProfileRow::Selection, &st.style, style_mixed) { + if let Some(edit) = line_style_rows(ui, ProfileRow::Selection, &st.style, m.style) { if edit.drag { live(app, edit.label, "stroke.set_style", edit.params); } else { @@ -729,6 +724,33 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E } } +/// The bitmap a placed bitmap or bitmap fill shows, with Swap Bitmap (ADR 0053): another +/// Library bitmap in its place, for every selected bitmap. +fn bitmap_row(app: &mut App, ui: &mut egui::Ui, current: anicraft_engine::doc::BitmapId, differs: bool) { + let name = app.s.doc.bitmap(current).map_or_else(|| tr!("missing bitmap").to_string(), |b| format!("{} · {}×{}", b.name, b.width, b.height)); + let mut choices: Vec<(anicraft_engine::doc::BitmapId, String)> = app.s.doc.bitmaps.iter().map(|b| (b.id, app.s.doc.entry_path(anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Bitmap(b.id))))).collect(); + choices.sort_by_key(|(_, p)| p.to_lowercase()); + row_prose(ui, tr!("Bitmap"), |ui| { + ui.label(text(Type::Body, name)); + ui.menu_button(tr!("Swap…"), |ui| { + egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + for (id, path) in &choices { + if ui.selectable_label(*id == current, path.as_str()).clicked() { + ui.close(); + if *id != current || differs { + app.run("element.swap_bitmap", json!({"bitmap": id.0})); + } + } + } + }); + }) + .response + .on_hover_text(tr!("Show another bitmap from the Library here, keeping its position and transform")) + .set_name(tr!("Swap Bitmap")); + mixed(ui, differs); + }); +} + /// 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]) { @@ -753,7 +775,7 @@ fn instance_rows(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Ele /// The Filters rows of a movie clip or button instance: an Add menu, then each filter's values /// with a remove button. Every change replaces the list (`element.set_filters`), one undo step /// per gesture. -fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc::Filter]) { +fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc::Filter], differs: bool) { use anicraft_engine::doc::Filter; // As the renderer sees them (a file may hold values or ramps a command would refuse). let mut list: Vec = current.iter().map(Filter::sanitized).collect(); @@ -771,6 +793,7 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc }) .response .set_name(tr!("Add filter")); + mixed(ui, differs); }); let quality_names = [tr!("Low"), tr!("Medium"), tr!("High")]; let mut remove = None; @@ -1621,7 +1644,7 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { }); // The width profile new strokes get. let current = st.profile(); - if let Some(pick) = profile_picker(ui, ProfileRow::Tool, current.as_ref()) { + if let Some(pick) = profile_picker(ui, ProfileRow::Tool, current.as_ref(), false) { st.set_profile(pick); } // And their style, caps and joins (with the params the commands take). @@ -1777,7 +1800,7 @@ enum ProfileRow { } /// The Width row: a profile menu with a picture of each built-in. Returns the one picked. -fn profile_picker(ui: &mut egui::Ui, which: ProfileRow, current: Option<&anicraft_engine::doc::WidthProfile>) -> Option { +fn profile_picker(ui: &mut egui::Ui, which: ProfileRow, current: Option<&anicraft_engine::doc::WidthProfile>, differs: bool) -> Option { use anicraft_engine::doc::ProfilePreset; let preset = match current { None => Some(ProfilePreset::Uniform), @@ -1797,7 +1820,7 @@ fn profile_picker(ui: &mut egui::Ui, which: ProfileRow, current: Option<&anicraf let lab = ui.selectable_label(on, name); pic.clicked() || lab.clicked() }); - if r.inner && !on { + if r.inner && (!on || differs) { picked = Some(pr); } } @@ -1805,6 +1828,7 @@ fn profile_picker(ui: &mut egui::Ui, which: ProfileRow, current: Option<&anicraf .response .on_hover_text(tr!("How the stroke's width varies along it. Shape it by hand with the Width tool (U).")) .set_name(tr!("Stroke width profile")); + mixed(ui, differs); }); picked } From b378efbbe35d46a12af5b8f4d6ade8c3d85e1f51 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:36:03 -0700 Subject: [PATCH 046/402] feat(shell): drag Library items onto the stage, Place at the view centre (Enter), Convert to Symbol dialog with folder and type (M2) --- src/app.rs | 14 +++- src/convert_symbol.rs | 166 ++++++++++++++++++++++++++++++++++++++++++ src/library.rs | 149 +++++++++++++++++++++++++++++-------- src/main.rs | 1 + src/stage.rs | 2 + 5 files changed, 301 insertions(+), 31 deletions(-) create mode 100644 src/convert_symbol.rs diff --git a/src/app.rs b/src/app.rs index cdb5d8e0..6319592a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -294,6 +294,9 @@ pub struct App { pub last_tool: Tool, pub status: Option, pub prompt: Option, + /// The Convert to Symbol dialog, and what it chose last (ADR 0053). + pub convert: Option, + pub convert_last: crate::convert_symbol::Last, pub show_about: bool, pub show_files: bool, pub show_licenses: bool, @@ -482,6 +485,8 @@ impl App { last_tool: Tool::Select, status: None, prompt: None, + convert: None, + convert_last: Default::default(), show_about: false, show_files: false, show_licenses: false, @@ -1350,7 +1355,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.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() } /// The single entry point for user-initiated commands: asks first when the engine says the @@ -1575,6 +1580,11 @@ impl App { self.show_plugins = true; return; } + if id == "modify.convert_to_symbol" { + // Name, type and Library folder (ADR 0053). + crate::convert_symbol::open(self); + return; + } if id == "edit.paste" { // Paste in the centre of what you are looking at. let c = self.view_center_stage(); @@ -1599,7 +1609,6 @@ impl App { "file.import_to_library" => Some((tr_noop!("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)"), "path", "sound.wav".to_string())), "file.import" => Some((tr_noop!("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)"), "path", "drawing.svg".to_string())), "plugin.install" => Some((tr_noop!("Install plug-in (.wasm file)"), "path", "plugin.wasm".to_string())), - "modify.convert_to_symbol" => Some((tr_noop!("Convert to symbol — name"), "name", format!("Symbol {}", self.s.doc.library.len() + 1))), // i18n-exempt: a new symbol's default name is document text _ => None, }; if let Some((title, key, text)) = prompt { @@ -2152,6 +2161,7 @@ impl App { crate::a11y::name_splitter(&ctx, "timeline", tr!("Resize the timeline")); self.prompt_window(&ctx); + crate::convert_symbol::window(self, &ctx); self.about_window(&ctx); dialogs::show_all(self, &ctx); autosave::window(self, &ctx); diff --git a/src/convert_symbol.rs b/src/convert_symbol.rs new file mode 100644 index 00000000..08e36225 --- /dev/null +++ b/src/convert_symbol.rs @@ -0,0 +1,166 @@ +//! The Convert to Symbol dialog (F8, ADR 0053): name, type and Library folder, as in Animate. +//! It remembers the folder and type last used, so a run of conversions lands together. What it +//! changes is one `modify.convert_to_symbol`; the choices remembered are view state. + +use crate::a11y::Named; +use crate::app::App; +use crate::theme::{FORM_LABEL_DOCK, Type, form_row, text}; +use anicraft_engine::doc::{Document, FolderId, LibraryEntry, SymbolKind}; +use egui::Key; +use serde_json::json; + +/// The dialog while it is open. +pub struct ConvertDialog { + pub name: String, + pub kind: SymbolKind, + pub folder: Option, + /// The name field takes the keyboard on the first frame. + focus: bool, +} + +/// What the last conversion chose (kept for the next one). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Last { + pub folder: Option, + pub kind: SymbolKind, +} + +/// The folder to offer: the one used last, while it is still in the Library. +pub fn remembered(doc: &Document, last: Last) -> Option { + last.folder.filter(|f| doc.folder(*f).is_some()) +} + +/// Opens the dialog for the selection, with the next free "Symbol n" in the remembered folder. +pub fn open(app: &mut App) { + if app.s.selection.is_empty() { + // The engine says why ("select something to convert"). + app.request("modify.convert_to_symbol", json!({})); + return; + } + app.playing = false; + let folder = remembered(&app.s.doc, app.convert_last); + let name = app.s.doc.numbered_name(folder, "Symbol", app.s.doc.library.len() + 1); // i18n-exempt: a new symbol's default name is document text, as the engine gives it + app.convert = Some(ConvertDialog { name, kind: app.convert_last.kind, folder, focus: true }); +} + +fn kind_key(k: SymbolKind) -> &'static str { + match k { + SymbolKind::Graphic => "graphic", + SymbolKind::MovieClip => "movie_clip", + SymbolKind::Button => "button", + } +} + +/// Where `folder` is, as the dialog names it. +fn folder_label(doc: &Document, folder: Option) -> String { + match folder { + Some(f) => doc.entry_path(LibraryEntry::Folder(f)), + None => tr!("Library (top level)").to_string(), + } +} + +pub fn window(app: &mut App, ctx: &egui::Context) { + let Some(d) = &mut app.convert else { return }; + let doc = &app.s.doc; + if d.folder.is_some_and(|f| doc.folder(f).is_none()) { + d.folder = None; + } + let mut folders: Vec<(FolderId, String)> = doc.library_tree.folders.iter().map(|f| (f.id, doc.entry_path(LibraryEntry::Folder(f.id)))).collect(); + folders.sort_by_key(|(_, p)| p.to_lowercase()); + let (mut submit, mut cancel) = (false, false); + let title = tr!("Convert to Symbol"); + egui::Window::new(title).id(egui::Id::new("convert_symbol")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| { + ui.set_min_width(380.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!("Symbol 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_DOCK, tr!("Type"), |ui| { + egui::ComboBox::from_id_salt("convert_kind") + .width(200.0) + .selected_text(crate::panels::symbol_kind_label(d.kind)) + .show_ui(ui, |ui| { + for k in [SymbolKind::Graphic, SymbolKind::MovieClip, SymbolKind::Button] { + if ui.selectable_label(d.kind == k, crate::panels::symbol_kind_label(k)).clicked() { + d.kind = k; + } + } + }) + .response + .set_name(tr!("Symbol type")); + }); + form_row(ui, FORM_LABEL_DOCK, tr!("Folder"), |ui| { + egui::ComboBox::from_id_salt("convert_folder") + .width(200.0) + .selected_text(folder_label(doc, d.folder)) + .show_ui(ui, |ui| { + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + if ui.selectable_label(d.folder.is_none(), tr!("Library (top level)")).clicked() { + d.folder = None; + } + for (f, path) in &folders { + if ui.selectable_label(d.folder == Some(*f), path.as_str()).clicked() { + d.folder = Some(*f); + } + } + }); + }) + .response + .on_hover_text(tr!("The Library folder the new symbol goes into (the next conversion offers it again)")) + .set_name(tr!("Library folder")); + }); + // A name the folder already has gets a number, as the engine gives it. + let wanted = d.name.trim(); + if !wanted.is_empty() && doc.name_taken(d.folder, wanted, None) { + let becomes = doc.unique_name(d.folder, wanted); + ui.label(text(Type::Caption, tr!("{folder} already has “{name}”; the new symbol will be “{becomes}”.", folder = folder_label(doc, d.folder), name = wanted, becomes = becomes))); + } + 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 && let Some(d) = app.convert.take() { + let name = d.name.trim(); + let mut params = json!({"kind": kind_key(d.kind), "folder": d.folder.map(|f| f.0)}); + if !name.is_empty() { + params["name"] = json!(name); + } + app.convert_last = Last { folder: d.folder, kind: d.kind }; + if let Some(f) = d.folder { + app.library.expanded.extend(app.s.doc.folder_chain(f)); + } + app.request("modify.convert_to_symbol", params); + } else if cancel { + app.convert = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::sample; + + #[test] + fn the_remembered_folder_is_offered_while_it_exists() { + let mut s = Session::new(sample::demo()); + let f = FolderId(s.execute("library.new_folder", &json!({"name": "Props"})).unwrap()["folder"].as_u64().unwrap()); + let last = Last { folder: Some(f), kind: SymbolKind::MovieClip }; + assert_eq!(remembered(&s.doc, last), Some(f)); + s.execute("library.delete", &json!({"items": [{"folder": f.0}]})).unwrap(); + assert_eq!(remembered(&s.doc, last), None, "a deleted folder falls back to the top level"); + assert_eq!(remembered(&s.doc, Last::default()), None); + } +} diff --git a/src/library.rs b/src/library.rs index 02b61972..be45e5ca 100644 --- a/src/library.rs +++ b/src/library.rs @@ -1,6 +1,7 @@ //! The Library panel (ADR 0050): folders, sorting and search, inline rename, drag into and out //! of folders, multiple selection, an item preview (a symbol's first frame, a bitmap, a -//! sound's waveform with play) and the item's properties. Every change is a `library.*` +//! sound's waveform with play) and the item's properties. Items drag onto the stage, or Place on +//! Stage (Enter) puts them at the centre of the view (ADR 0053). Every change is a `library.*` //! command; what is sorted, filtered, expanded or selected is view state, kept here. use crate::a11y::{self, Named}; @@ -11,7 +12,7 @@ use anicraft_engine::StateId; use anicraft_engine::cmds_library::entry_json; use anicraft_engine::doc::library::MAX_FOLDER_DEPTH; use anicraft_engine::doc::{Document, FolderId, LibraryEntry, LibraryItem, SymbolKind}; -use egui::{Align2, Key, Modifiers, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use egui::{Align2, Key, Modifiers, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::json; use std::collections::{HashMap, HashSet}; @@ -214,7 +215,7 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) { if !app.library.keys || app.library.renaming.is_some() { return; } - let (rename, delete) = ctx.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::F2), i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace))); + let (rename, delete, place) = ctx.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::F2), i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace), i.consume_key(Modifiers::NONE, Key::Enter))); if rename && let [one] = app.library.sel.as_slice() { let e = *one; start_rename(app, e); @@ -222,6 +223,21 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) { if delete { delete_selection(app); } + // Enter: the keyboard's way to do what dragging onto the stage does (ADR 0053). + if place { + let items = selected_items(app); + if !items.is_empty() { + place_items(app, &items, None); + } + } +} + +/// The selected rows' items (folders left out), in selection order. +fn selected_items(app: &App) -> Vec { + app.library.sel.iter().filter_map(|e| match e { + LibraryEntry::Item(i) if app.s.doc.has_item(*i) => Some(*i), + _ => None, + }).collect() } fn start_rename(app: &mut App, e: LibraryEntry) { @@ -236,14 +252,90 @@ fn delete_selection(app: &mut App) { } } -/// Places an item: a symbol or bitmap at the stage centre, a sound on the active layer's -/// keyframe at the playhead (its span grown to fit). +/// The centre of what the stage shows, in the space being edited (inside an open symbol, its +/// own, ADR 0045): where Place on Stage puts things. +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), + } +} + +/// Places items at `at` (in the edited space; default: the centre of the view): symbols and +/// bitmaps on the active layer at the playhead, a sound on its keyframe there. One undo step +/// (`library.place`, ADR 0053). The stage then has the keyboard again. +pub fn place_items(app: &mut App, items: &[LibraryItem], at: Option<(f32, f32)>) { + let (x, y) = at.unwrap_or_else(|| view_centre(app)); + let list: Vec = items.iter().map(|i| entry_json(LibraryEntry::Item(*i))).collect(); + app.run("library.place", json!({"items": list, "x": x, "y": y})); + app.library.keys = false; +} + fn place(app: &mut App, item: LibraryItem) { - match item { - LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), - LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})), - LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})), - }; + place_items(app, &[item], None); +} + +/// What the Library rows being dragged hold that can be placed (folders left out). +fn dragged_items(app: &App, ctx: &egui::Context) -> Vec { + egui::DragAndDrop::payload::>(ctx).map_or_else(Vec::new, |p| { + p.iter().filter_map(|e| match e { + LibraryEntry::Item(i) if app.s.doc.has_item(*i) => Some(*i), + _ => None, + }).collect() + }) +} + +/// Library rows dragged over the stage (ADR 0053): a mark shows where they land and on which +/// layer; letting go places them there, sounds onto the active layer's keyframe at the playhead, +/// in one undo step. `to_stage` maps a screen point into the edited space. +pub fn stage_drop(app: &mut App, ui: &egui::Ui, resp: &egui::Response, to_stage: impl Fn(Pos2) -> Pos2, paused: bool) { + if resp.dnd_hover_payload::>().is_none() { + return; + } + let items = dragged_items(app, ui.ctx()); + let Some(p) = ui.input(|i| i.pointer.latest_pos()) else { return }; + if items.is_empty() { + return; + } + if let Some(_payload) = resp.dnd_release_payload::>() { + if paused { + app.status_ok(tr!("Previewing through the camera: artwork edits are paused. Turn off View › Preview Through Camera to edit.")); + return; + } + let at = to_stage(p); + place_items(app, &items, Some((at.x, at.y))); + return; + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Copy); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("library_drop"))); + let only_sounds = items.iter().all(|i| matches!(i, LibraryItem::Sound(_))); + if !only_sounds { + let r = 7.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 layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default(); + let frame = app.s.frame + 1; + let hint = if only_sounds { tr!("Put on {layer} at frame {frame}", layer = layer, frame = frame) } else { tr!("Place on {layer}", layer = layer) }; + let galley = painter.layout_no_wrap(hint, font(Type::Caption), color(Type::Body)); + let at = p + vec2(14.0, 10.0); + painter.rect_filled(Rect::from_min_size(at, galley.size()).expand(4.0), T.rc(), T.panel); + painter.galley(at, galley, color(Type::Body)); +} + +/// While Library rows are dragged, their names follow the pointer, so it is clear what is being +/// carried. +fn drag_ghost(app: &App, ctx: &egui::Context) { + let items = dragged_items(app, ctx); + let (Some(first), Some(p)) = (items.first(), ctx.input(|i| i.pointer.latest_pos())) else { return }; + let name = app.s.doc.item_name(*first).unwrap_or("").to_string(); + let label = if items.len() > 1 { trn!("{name} and {n} more", "{name} and {n} more", items.len() - 1, name = name) } else { name }; + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("library_ghost"))); + let galley = painter.layout_no_wrap(label, font(Type::Body), color(Type::Body)); + let at = p + vec2(14.0, -galley.size().y - 8.0); + painter.rect_filled(Rect::from_min_size(at, galley.size()).expand(4.0), T.rc(), T.accent_dim); + painter.galley(at, galley, color(Type::Body)); } /// A new folder in the selected row's folder (or the selected folder), opened, selected and @@ -295,6 +387,7 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) { return; } toolbar(app, ui); + drag_ghost(app, ui.ctx()); ui.add_space(4.0); let (uses, unused) = app.library.counts(&app.s); let list = rows(&app.s.doc, &app.library, &uses); @@ -593,13 +686,12 @@ fn row_menu(app: &mut App, ui: &mut egui::Ui, e: LibraryEntry) { } } } - if let LibraryEntry::Item(i) = e - && !many - { - let label = if matches!(i, LibraryItem::Sound(_)) { tr!("Place on Timeline") } else { tr!("Place on Stage") }; - if ui.button(label).clicked() { + let items = selected_items(app); + if !items.is_empty() { + let label = if items.iter().all(|i| matches!(i, LibraryItem::Sound(_))) { tr!("Place on Timeline") } else { tr!("Place on Stage") }; + if ui.button(label).on_hover_text(tr!("At the centre of the view, on the active layer (Enter; or drag onto the stage)")).clicked() { ui.close(); - place(app, i); + place_items(app, &items, None); } } if !many && ui.button(tr!("Rename")).clicked() { @@ -645,20 +737,19 @@ fn actions_row(app: &mut App, ui: &mut egui::Ui) { if del.clicked() { delete_selection(app); } - let current = app.library_sel.filter(|i| app.s.doc.has_item(*i)); - match current { - Some(LibraryItem::Sound(id)) => { - if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click its icon)")).clicked() { - place(app, LibraryItem::Sound(id)); - } - } - other => { - if ui.add_enabled(other.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre")).clicked() - && let Some(item) = other - { - place(app, item); - } + // The selected rows, else the item previewed. + let mut items = selected_items(app); + if items.is_empty() + && let Some(i) = app.library_sel.filter(|i| app.s.doc.has_item(*i)) + { + items.push(i); + } + if !items.is_empty() && items.iter().all(|i| matches!(i, LibraryItem::Sound(_))) { + if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (Enter, or drag it onto the stage)")).clicked() { + place_items(app, &items, None); } + } else if ui.add_enabled(!items.is_empty(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the centre of the view, on the active layer (Enter, or drag it onto the stage)")).clicked() { + place_items(app, &items, None); } }); } diff --git a/src/main.rs b/src/main.rs index c3592603..3f5dde9d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,6 +30,7 @@ mod envelope; mod erasertool; mod bone_tool; mod camera_tool; +mod convert_symbol; mod dialogs; mod gpu_stage; mod icons; diff --git a/src/stage.rs b/src/stage.rs index 43426016..282d23ef 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -262,6 +262,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // tools pause meanwhile (what they'd edit is in stage space, not where it shows). let preview = crate::camera_tool::previewing(app); 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); // ---- tools ---------------------------------------------------------------------------- From a4c653b9f677f042a9acfd839bb96b9f5612bc57 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:37:14 -0700 Subject: [PATCH 047/402] test(shell): screenshot states for Convert to Symbol, mixed rows and Swap Bitmap (M2) --- src/app.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/app.rs b/src/app.rs index 6319592a..37151273 100644 --- a/src/app.rs +++ b/src/app.rs @@ -799,6 +799,50 @@ impl App { crate::library::select_unused(self); } } + Some("convert") => { + // Convert to Symbol with folders to choose from, the last one used offered again + // (ADR 0053). + let folder = self.run("library.new_folder", json!({"name": "Characters"})).and_then(|v| v["folder"].as_u64()); + self.run("library.new_folder", json!({"name": "Props"})); + self.run("draw.rect", json!({"x": 820, "y": 120, "w": 140, "h": 90, "fill": "#e0a030", "object": true})); + self.convert_last = crate::convert_symbol::Last { folder: folder.map(anicraft_engine::doc::FolderId), kind: anicraft_engine::doc::SymbolKind::MovieClip }; + crate::convert_symbol::open(self); + } + Some("mixed") => { + // Two movie clips that differ in blending and filters, selected: those rows say + // "mixed" (ADR 0053). + if let Some(ball) = self.s.doc.library.first().map(|s| s.id.0) { + self.run("edit.deselect", json!({})); + self.run("symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"})); + let id = |v: Option| v.and_then(|v| v["element"].as_u64()).unwrap_or(0); + let a = id(self.run("library.place", json!({"symbol": ball, "x": 760, "y": 180}))); + let b = id(self.run("library.place", json!({"symbol": ball, "x": 900, "y": 220}))); + self.run("element.set_blend", json!({"mode": "multiply"})); + self.run("element.set_filters", json!({"filters": [{"type": "glow"}]})); + self.run("element.select", json!({"ids": [a, b]})); + } + } + Some("bitmap") => { + // Two placed bitmaps of different images, selected: the Bitmap row with Swap… + // says "mixed" (ADR 0053). + let dir = std::env::temp_dir().join("anicraft-shot-bitmaps"); + let _ = std::fs::create_dir_all(&dir); + let mut ids = Vec::new(); + for (name, w, h, px) in [("checker.png", 8u32, 8u32, [40u8, 120, 220, 255]), ("sunset.png", 12, 6, [230, 120, 40, 255])] { + let path = dir.join(name); + let Ok(png) = anicraft_engine::render::encode_png(w, h, &px.repeat((w * h) as usize)) else { continue }; + if std::fs::write(&path, png).is_err() { + continue; + } + if let Some(b) = self.run("file.import_to_library", json!({"path": path.display().to_string(), "name": name})).and_then(|v| v["bitmap"].as_u64()) { + let at = 700 + 160 * ids.len(); + if let Some(e) = self.run("library.place", json!({"bitmap": b, "x": at, "y": 200})).and_then(|v| v["element"].as_u64()) { + ids.push(e); + } + } + } + self.run("element.select", json!({"ids": ids})); + } Some(which @ ("onion" | "onionmenu")) => { // Onion skin ±5 on a frame with frames before and after it, the markers on the // ruler; with its menu open, in outlines (ADR 0047). From 42c839b45061a8a4f06481d26f717ff68358ae4c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:38:06 -0700 Subject: [PATCH 048/402] docs: ADR 0053 Library drag and drop, Swap Bitmap, Convert to Symbol folders, mixed Properties; roadmap and changelog (M2) --- CHANGELOG.md | 18 ++++ docs/accessibility.md | 4 + docs/adr/0050-library-management.md | 6 +- ...brary-drag-swap-bitmap-mixed-properties.md | 102 ++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 4 +- 6 files changed, 129 insertions(+), 6 deletions(-) create mode 100644 docs/adr/0053-library-drag-swap-bitmap-mixed-properties.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7862adc4..8346976c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## Unreleased +* **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. + One undo step, and it works inside a symbol open for editing. The stage shows where they + land and on which layer. + * **Place on Stage** (the Library's button, right-click, or **Enter** in the list) puts the + selected items at the centre of the view. + * **Swap Bitmap** in Properties › Bitmap: a placed bitmap keeps its position and transform + and takes the new bitmap's size; a shape painted with a bitmap fill keeps its outline. + * **Convert to Symbol** (F8) asks for a name, a type and a **Library folder**, and offers the + folder and type you used last. + * **"mixed" on every Properties row** when several elements differ: Symbol, Type, Filters, + Blending, Looping, First frame, Bitmap and Width now join Scale, Rotation, Alpha, Fill, + Stroke and Style. A change sets them all; Type sets the type of every selected instance's + symbol. + * Headless: `library.place {items: [..], x, y}` (and `{sound}`), `element.swap_bitmap`, + `kind` and `folder` on `modify.convert_to_symbol`; `symbol.set_kind` without `symbol` sets + every selected instance's symbol. * **Edit Multiple Frames, complete; onion skin inside symbols** (ADR 0051, M1). * With Edit Multiple Frames on, **Cut, Copy, Paste, Paste in Place and Clear** act on the artwork selected on every keyframe between the markers. Paste in Place puts artwork copied diff --git a/docs/accessibility.md b/docs/accessibility.md index b6cb6ce0..456e0d23 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -25,6 +25,10 @@ work yet. Design decisions are in ADR 0022; the rules for contributors are in shortcut works, including Enter (play) and the arrows (nudge). With a button or checkbox focused, the other shortcuts still work but Enter, Space and the arrows belong to it. In a text field every key types. Esc leaves a field. +* **Library items without dragging** (ADR 0053): after clicking a Library row, **Enter** places + 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. diff --git a/docs/adr/0050-library-management.md b/docs/adr/0050-library-management.md index 56c82456..86e7e42c 100644 --- a/docs/adr/0050-library-management.md +++ b/docs/adr/0050-library-management.md @@ -120,7 +120,7 @@ watching the program. Nothing was copied. ## Not yet -Dragging Library items onto the stage, Animate's Properties dialog (the properties are inline), +(Dragging items onto the stage, choosing a folder in Convert to Symbol and Swap Bitmap came in +ADR 0053.) Animate's Properties dialog (the properties are inline), linkage on bitmaps and sounds, bitmap compression settings, Update and Import of library items -from another document (shared libraries), folder expansion saved in the file, sorting by size, -choosing a folder in Convert to Symbol, and Swap Bitmap. +from another document (shared libraries), folder expansion saved in the file and sorting by size. diff --git a/docs/adr/0053-library-drag-swap-bitmap-mixed-properties.md b/docs/adr/0053-library-drag-swap-bitmap-mixed-properties.md new file mode 100644 index 00000000..a10f91df --- /dev/null +++ b/docs/adr/0053-library-drag-swap-bitmap-mixed-properties.md @@ -0,0 +1,102 @@ +# ADR 0053: Library drag and drop, Swap Bitmap, Convert to Symbol folders, mixed Properties + +* Status: accepted (2026-11-11) +* Relates to: ADR 0050 (Library management), ADR 0044 (selection across layers), ADR 0045 + (symbols edited in place), ADR 0020/0039 (sounds on keyframes), ADR 0004 (destructive actions), + ADR 0022 (accessibility), ADR 0040 (interface languages), roadmap M2 + +## Context + +ADR 0050 left the everyday Library gestures Animate users reach for first: dragging an item +onto the stage, swapping the bitmap an instance shows, choosing a folder when converting to a +symbol. ADR 0044 showed "mixed" on only some Properties rows (Scale, Rotation, Alpha, Fill, +Stroke, Style), so a selection of movie clips with different blending looked alike. Behaviour +was learned from Adobe's public help pages and from watching the program; nothing was copied. + +## Decision + +1. **One command places what a drop carries.** `library.place` takes one item + (`{symbol | bitmap | sound: id, x?, y?}`, as before) or a list + (`{items: [{symbol | bitmap | sound: id}, ..], x?, y?}`, up to 1,000). Symbols stand with + their registration point on `x`/`y`, bitmaps are centred on it, all in the active layer's + keyframe at the playhead (auto-key rules as for any edit), and everything placed is selected. + A sound goes onto that keyframe (a blank keyframe is made on an empty frame, the span grows + to the sound's length, as Place on Timeline did); a keyframe holds one sound, so two + different sounds in one drop are refused. Positions are in the edited space, so inside a + symbol open for editing (ADR 0045) a drop lands where the pointer is. Folders can't be + placed; locked layers, folders, the camera and armature layers refuse as for drawing. One + command means a drop of many items is one undo step, and the CLI, MCP and plug-ins (the + `library` namespace) can do it too. + + *Rejected:* a gesture of one `library.place` per item. It would be one undo step in the + shell only, and a script dropping several items would get several. + +2. **Dragging onto the stage.** Library rows already carry their selection as a drag payload + (folder moves). The stage accepts the same payload: while it is over the stage the pointer + shows a copy cursor, a cross where artwork lands and "Place on " (for sounds alone, + "Put on at frame n"); the rows' names follow the pointer everywhere. Letting go runs + `library.place` at the pointer, mapped into the edited space. Folders in the payload are + left out. While previewing through the camera, artwork edits are paused (ADR 0027) and the + drop says so instead. + +3. **The keyboard way (ADR 0022).** Place on Stage (the Library's button, its right-click menu, + and **Enter** while the list has the keyboard) places the selected rows at the **centre of + the view** (what the stage shows, in the edited space), no longer the stage's centre: what + you see is where it lands, as a drop at the centre would put it. With several rows selected + it places them all, one undo step. + +4. **Swap Bitmap** (`element.swap_bitmap {bitmap}`, per layer, ADR 0044's "where it applies" + class). A bitmap placed from the Library is a rectangle of the bitmap's size filled with it + (identity fill matrix, no repeat). Such a shape keeps its transform, so its top-left corner + (Animate's registration point for bitmaps) stays put, takes the new bitmap's size, and its + name follows when it was the old bitmap's. Any other bitmap-filled shape (painted with a + bitmap fill) keeps its outline and fill transform, and only the bitmap changes. Properties + shows a **Bitmap** row under Fill with the bitmap's name and size and **Swap…**, listing the + Library's bitmaps by path, as Swap Symbol does. + +5. **Convert to Symbol (F8) is a dialog** with Name, Type (Graphic, Movie clip, Button) and + Folder (the Library's folders by path, or the top level). It offers the folder and type used + last, while that folder still exists (view state, `convert_symbol::Last`, not saved). + `modify.convert_to_symbol` takes `kind` and `folder`; a name the folder already holds gets a + number ("Ball 2", `Document::unique_name`) rather than an error, and the dialog says so + before you press OK. Without a name it is the next free "Symbol n" in that folder. Without + `folder` it stays at the top level, so scripts behave as before. + +6. **"Mixed" on every Properties row** that edits several elements (`src/mixed.rs`, pure and + tested per row): Scale, Rotation, Alpha (the colour effect; tint has no row yet), Symbol + (Swap…), Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke (colour and + width), Width (profile) and Style. Each row compares only the elements it edits: Blending and + Filters movie clips and buttons, Looping and First frame graphics, Fill, Stroke, Width and + Style shapes, the Bitmap row bitmap fills. So a shape beside a movie clip never makes + Blending mixed. Fill compares the whole paint (on beside off, two bitmaps, two gradients). + Position never says mixed: with several elements it is the combined box (ADR 0044). + + Editing a mixed row sets all, as the hint says. Choosing the value the field already shows + applies it too when the row is mixed (otherwise a menu pick of the first element's value did + nothing). For **Type**, `symbol.set_kind` without `symbol` now changes the symbols of + **every** selected instance in one step (it was the first one's, ADR 0044 decision 2). The + type belongs to the symbol, as in our model since ADR 0013, so this changes those symbols' + other instances too, as picking the type in the Library does. Filters edits the first + element's list and gives it to all. + +## Consequences + +* Dragging from the Library to the stage, Place on Stage with Enter, Swap Bitmap, a folder in + Convert to Symbol and mixed rows behave as an Animate user expects, headless included. +* Tests: `crates/engine/src/place_tests.rs` (a drop of symbols, a bitmap and a sound in one + undo step; positions; refusals that change nothing; locked layers; inside an open symbol; + Swap Bitmap on a placed bitmap and on a tiled fill on two layers; Convert to Symbol into a + folder, with clashing names, types and the file round trip), `src/mixed.rs` (one test per + row group, including "editing a mixed row sets all"), `src/convert_symbol.rs` (the + remembered folder). `panic_hunt_every_command` fuzzes mixed item lists, two sounds, far + points, 1,500 items, and Swap Bitmap on a placed bitmap. +* `library.place`'s result gains `elements` and `sound`; `element` stays. `symbol.set_kind`'s + result gains `symbols`. + +## Not yet + +Dropping files from the desktop onto the stage, a ghost picture of the item while dragging +(the name follows the pointer), snapping a drop to objects, a New Folder button in the Convert +to Symbol dialog and a registration-point grid, Swap Bitmap from the Library's own menu +(Animate's "Swap Bitmap" on the item, which swaps every use), "mixed" on text style rows and on +the instance name and events, and a Colour Effect row with tint and brightness. diff --git a/docs/adr/README.md b/docs/adr/README.md index 6261aa89..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 | -| 0053 | M2 Library and Properties polish | Library drag and drop, Swap Bitmap, mixed Properties | diff --git a/docs/roadmap.md b/docs/roadmap.md index f3f0d15c..3dec722d 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): 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`. Not yet: dragging items onto the stage, shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, a folder choice in Convert to Symbol, Swap Bitmap. | +| 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. | | 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); ~~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); ~~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); not yet: `.fla` variants of the corpus, sound and video items; ~~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 b871683cb3eeb80f1cecf4d03f3704b3cab721ee Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:38:46 -0700 Subject: [PATCH 049/402] test(shell): accessibility audit covers Convert to Symbol, mixed rows and Swap Bitmap (M2) --- src/a11y.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/a11y.rs b/src/a11y.rs index d4f76bb9..2e829dc5 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"] { + 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"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. From 0b592e90b9aa56fc202a3cd4a83ec3acf3c63433 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:47:25 -0700 Subject: [PATCH 050/402] feat(xfl): harden the .fla zip reader against hostile archives (M4) ZIP64, data descriptors, CP437 and Unicode-path names; refuses overlapping entries, lying sizes and checksums, ratio bombs, unsafe and duplicate paths, deep nesting and truncated directories with readable errors; a 1 GiB read budget. Tests use an independent in-memory zip writer (tests/support/fla.rs). --- crates/xfl/src/tests.rs | 2 +- crates/xfl/src/zip.rs | 442 ++++++++++++++++++++++++-------- crates/xfl/src/zip_tests.rs | 284 ++++++++++++++++++++ crates/xfl/tests/support/fla.rs | 328 ++++++++++++++++++++++++ 4 files changed, 950 insertions(+), 106 deletions(-) create mode 100644 crates/xfl/src/zip_tests.rs create mode 100644 crates/xfl/tests/support/fla.rs diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index a8ea11f3..8e0e1fb7 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -193,7 +193,7 @@ fn shapes_become_fills_and_strokes() { #[test] fn a_fla_archive_imports_the_same() { - let z = crate::zip::tests::make_zip(&[("DOMDocument.xml", DOC.as_bytes(), true), ("LIBRARY/Characters/Ball.xml", BALL.as_bytes(), true)]); + let z = crate::zip::pack::write(&[crate::zip::pack::Raw::new("DOMDocument.xml", DOC.as_bytes(), true), crate::zip::pack::Raw::new("LIBRARY/Characters/Ball.xml", BALL.as_bytes(), true)], false); let dir = std::env::temp_dir().join(format!("anicraft-xfl-test-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let fla = dir.join("scene.fla"); diff --git a/crates/xfl/src/zip.rs b/crates/xfl/src/zip.rs index 7b3e1c87..52dbf819 100644 --- a/crates/xfl/src/zip.rs +++ b/crates/xfl/src/zip.rs @@ -1,169 +1,401 @@ -//! Reading files out of a `.fla` (a zip archive of an XFL folder). +//! Reading files out of a `.fla` (a zip archive of an XFL folder), ADR 0009 and ADR 0054. //! -//! Implements the parts of the published ZIP format (PKWARE APPNOTE) that `.fla` files use: -//! the end-of-central-directory record, central directory entries and local headers, with -//! "stored" and "deflate" entries (inflated by `miniz_oxide`). ZIP64 and encryption are refused -//! with a clear error. Every offset and size is checked; sizes are capped so a zip bomb can't -//! exhaust memory. Never panics. +//! Implements the parts of the published ZIP format (PKWARE APPNOTE 6.3) that archive tools +//! write: the end-of-central-directory record (and its ZIP64 form), central directory entries +//! with ZIP64 sizes, local headers, data descriptors, "stored" and "deflate" entries (inflated +//! by `miniz_oxide`), UTF-8 names (flag bit 11 or the Info-ZIP Unicode path field) and CP437 +//! names. Encryption, other compression methods and split archives are refused with a clear +//! error. +//! +//! The archive is treated as hostile. Every offset and size is checked against the bytes it +//! comes from; entries may not overlap each other or the central directory; a name that would +//! leave the package (`..`, absolute or drive paths), is listed twice or is nested deeper than +//! [`MAX_DEPTH`] refuses the archive; an entry may not claim more than deflate can produce from +//! its bytes ([`MAX_RATIO`]), more than [`MAX_ENTRY`], or a size or checksum it doesn't have; +//! and the archive hands out at most [`MAX_TOTAL`] bytes in all. Nothing is ever written to +//! disk. Never panics. +use std::cell::Cell; use std::collections::HashMap; /// Largest single entry inflated (bytes). pub const MAX_ENTRY: usize = 256 * 1024 * 1024; +/// Most bytes one archive hands out, over every read (the import's memory budget). +pub const MAX_TOTAL: u64 = 1024 * 1024 * 1024; +/// Most entries an archive may list (files and folders). +pub const MAX_ENTRIES: usize = 100_000; +/// Most folders a path may be inside (Animate's library nests a few deep). +pub const MAX_DEPTH: usize = 32; +/// Largest size-to-compressed-size ratio believed: deflate itself can't pass about 1032 : 1, +/// so an entry claiming more is a zip bomb or a damaged size, refused before inflating. +pub const MAX_RATIO: u64 = 1024; -#[derive(Debug, thiserror::Error, PartialEq)] +#[derive(Debug, Clone, thiserror::Error, PartialEq)] pub enum ZipError { #[error("not a zip archive (no end-of-directory record)")] NotZip, #[error("the archive is damaged: {0}")] Damaged(&'static str), - #[error("'{0}' uses an unsupported zip feature ({1})")] + #[error("the archive is damaged: '{0}' {1}")] + DamagedEntry(String, &'static str), + #[error("the archive uses a zip feature AniCraft can't read ({0})")] + UnsupportedArchive(&'static str), + #[error("'{0}' uses a zip feature AniCraft can't read ({1})")] Unsupported(String, &'static str), #[error("'{0}' is too large to read")] TooLarge(String), + #[error("the archive asks for more than {} MB in all", MAX_TOTAL / (1024 * 1024))] + TooMuch, + #[error("the archive lists more than {MAX_ENTRIES} files")] + TooMany, + #[error("'{0}' claims to expand more than compression allows (a zip bomb or a damaged archive)")] + Bomb(String), + #[error("'{0}' and '{1}' share bytes in the archive (a zip bomb or a damaged archive)")] + Overlap(String, String), + #[error("'{0}' points outside the document")] + Unsafe(String), + #[error("'{0}' is in the archive twice")] + Duplicate(String), + #[error("'{0}' is inside more than {MAX_DEPTH} folders")] + TooDeep(String), } #[derive(Debug, Clone)] struct Entry { method: u16, flags: u16, + crc: u32, comp: usize, size: usize, - offset: usize, + /// Where its (compressed) bytes start. + data: usize, } pub struct Archive<'a> { data: &'a [u8], entries: HashMap, + folders: usize, + /// Bytes still to hand out ([`MAX_TOTAL`] at first). + budget: Cell, } +const END: u32 = 0x0605_4b50; +const END64: u32 = 0x0606_4b50; +const LOCATOR64: u32 = 0x0706_4b50; +const CENTRAL: u32 = 0x0201_4b50; +const LOCAL: u32 = 0x0403_4b50; + +fn get(d: &[u8], at: usize, len: usize) -> Option<&[u8]> { + d.get(at..at.checked_add(len)?) +} fn u16_at(d: &[u8], i: usize) -> Option { - Some(u16::from_le_bytes(d.get(i..i + 2)?.try_into().ok()?)) + Some(u16::from_le_bytes(get(d, i, 2)?.try_into().ok()?)) } fn u32_at(d: &[u8], i: usize) -> Option { - Some(u32::from_le_bytes(d.get(i..i + 4)?.try_into().ok()?)) + Some(u32::from_le_bytes(get(d, i, 4)?.try_into().ok()?)) +} +fn u64_at(d: &[u8], i: usize) -> Option { + Some(u64::from_le_bytes(get(d, i, 8)?.try_into().ok()?)) +} + +/// The body of the extra field `id`, if `extra` has one. +fn extra_field(mut extra: &[u8], id: u16) -> Option<&[u8]> { + while extra.len() >= 4 { + let (tag, len) = (u16_at(extra, 0)?, u16_at(extra, 2)? as usize); + let body = get(extra, 4, len)?; + if tag == id { + return Some(body); + } + extra = extra.get(4 + len..)?; + } + None +} + +/// CRC-32 tables for eight bytes at a time ("slicing by 8"): `TABLES[0]` is the classic +/// byte table, `TABLES[k][b]` the checksum of byte `b` followed by `k` zero bytes. +const TABLES: [[u32; 256]; 8] = { + let mut t = [[0u32; 256]; 8]; + 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[0][i] = c; + i += 1; + } + let mut k = 1; + while k < 8 { + let mut i = 0; + while i < 256 { + let prev = t[k - 1][i]; + t[k][i] = (prev >> 8) ^ t[0][(prev & 0xff) as usize]; + i += 1; + } + k += 1; + } + t +}; + +/// CRC-32 (ISO-HDLC, the zip checksum), eight bytes at a time. +pub fn crc32(data: &[u8]) -> u32 { + let t = &TABLES; + let mut c = !0u32; + let (blocks, rest) = data.as_chunks::<8>(); + for b in blocks { + let lo = c ^ u32::from_le_bytes([b[0], b[1], b[2], b[3]]); + c = t[7][(lo & 0xff) as usize] ^ t[6][((lo >> 8) & 0xff) as usize] ^ t[5][((lo >> 16) & 0xff) as usize] ^ t[4][(lo >> 24) as usize] ^ t[3][b[4] as usize] ^ t[2][b[5] as usize] ^ t[1][b[6] as usize] ^ t[0][b[7] as usize]; + } + for &b in rest { + c = t[0][((c ^ b as u32) & 0xff) as usize] ^ (c >> 8); + } + !c +} + +/// Code page 437, bytes 0x80 to 0xFF: the zip format's name encoding without the UTF-8 flag. +const CP437: [char; 128] = [ + 'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å', // + 'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', '£', '¥', '₧', 'ƒ', // + 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '⌐', '¬', '½', '¼', '¡', '«', '»', // + '░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐', // + '└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧', // + '╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀', // + 'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'µ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩', // + '≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', '\u{a0}', +]; + +/// An entry's name as text: the Info-ZIP Unicode path field when it matches the name, UTF-8 +/// when flag bit 11 says so, else CP437 as the format specifies. Many writers store UTF-8 +/// without setting the flag, so a name that is valid UTF-8 is read as UTF-8 (ASCII, which +/// nearly every name is, reads the same either way). +fn decode_name(raw: &[u8], utf8: bool, extra: &[u8]) -> Result { + if let Some(up) = extra_field(extra, 0x7075) + && up.first() == Some(&1) + && u32_at(up, 1) == Some(crc32(raw)) + && let Some(Ok(s)) = up.get(5..).map(std::str::from_utf8) + { + return Ok(s.to_string()); + } + match std::str::from_utf8(raw) { + Ok(s) => Ok(s.to_string()), + Err(_) if utf8 => Err(ZipError::Damaged("an entry's name is not the UTF-8 it says it is")), + Err(_) => Ok(raw.iter().map(|&b| if b < 0x80 { b as char } else { CP437.get((b - 0x80) as usize).copied().unwrap_or('\u{fffd}') }).collect()), + } +} + +/// A name as a plain path inside the package: `\` read as `/`, empty and `.` parts dropped. +/// Names that would leave the package are refused, though nothing is ever extracted: every +/// lookup stays unambiguous, as the folder form's reader also refuses them. +fn clean_path(name: &str) -> Result { + let unix = name.replace('\\', "/"); + let shown = || name.chars().take(200).collect::(); + if unix.starts_with('/') || unix.contains('\0') { + return Err(ZipError::Unsafe(shown())); + } + let mut parts = Vec::new(); + for (i, part) in unix.split('/').enumerate() { + match part { + "" | "." => {} + ".." => return Err(ZipError::Unsafe(shown())), + // `C:`, `C:x`: a drive. + p if i == 0 && p.contains(':') => return Err(ZipError::Unsafe(shown())), + p => parts.push(p), + } + } + if parts.len() > MAX_DEPTH + 1 { + return Err(ZipError::TooDeep(shown())); + } + Ok(parts.join("/")) +} + +fn method_name(method: u16) -> &'static str { + match method { + 9 => "Deflate64 compression", + 12 => "bzip2 compression", + 14 => "LZMA compression", + 93 => "Zstandard compression", + 95 => "XZ compression", + 99 => "AES encryption", + _ => "an unknown compression method", + } +} + +/// The end of the central directory: (entry count, its size, its offset, where it must end). +fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { + // The end record is in the last 22 + 65535 bytes (it may carry a comment). + let lo = data.len().saturating_sub(22 + 65_535); + let eocd = (lo..data.len().saturating_sub(21)).rev().find(|&i| u32_at(data, i) == Some(END)).ok_or(ZipError::NotZip)?; + let field16 = |o: usize| u16_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); + let field32 = |o: usize| u32_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); + let (disk, dir_disk, on_disk, count) = (field16(4)?, field16(6)?, field16(8)?, field16(10)?); + let (size, offset) = (field32(12)?, field32(16)?); + if count != 0xffff && size != 0xffff_ffff && offset != 0xffff_ffff { + if disk != 0 || dir_disk != 0 || on_disk != count { + return Err(ZipError::UnsupportedArchive("split across several files")); + } + return Ok((count.into(), size.into(), offset.into(), eocd)); + } + // ZIP64: a locator just before the end record points at the ZIP64 end record. + let locator = eocd.checked_sub(20).filter(|&l| u32_at(data, l) == Some(LOCATOR64)).ok_or(ZipError::Damaged("the ZIP64 end record is missing"))?; + let missing = ZipError::Damaged("the ZIP64 end record is missing"); + let at = u64_at(data, locator + 8).and_then(|a| usize::try_from(a).ok()).filter(|&a| a < locator).ok_or(missing.clone())?; + if u32_at(data, at) != Some(END64) { + return Err(missing); + } + let cut = ZipError::Damaged("the ZIP64 end record is cut short"); + let (disk, dir_disk) = (u32_at(data, at + 16).ok_or(cut.clone())?, u32_at(data, at + 20).ok_or(cut.clone())?); + let (on_disk, count) = (u64_at(data, at + 24).ok_or(cut.clone())?, u64_at(data, at + 32).ok_or(cut.clone())?); + if disk != 0 || dir_disk != 0 || on_disk != count { + return Err(ZipError::UnsupportedArchive("split across several files")); + } + Ok((count, u64_at(data, at + 40).ok_or(cut.clone())?, u64_at(data, at + 48).ok_or(cut)?, at)) } impl<'a> Archive<'a> { pub fn open(data: &'a [u8]) -> Result, ZipError> { - // The end record is in the last 22 + 65535 bytes (it may carry a comment). - let lo = data.len().saturating_sub(22 + 65_535); - let eocd = (lo..data.len().saturating_sub(21)).rev().find(|&i| u32_at(data, i) == Some(0x0605_4b50)).ok_or(ZipError::NotZip)?; - let count = u16_at(data, eocd + 10).ok_or(ZipError::Damaged("end record"))? as usize; - let dir = u32_at(data, eocd + 16).ok_or(ZipError::Damaged("end record"))? as usize; - if count == 0xffff || dir == 0xffff_ffff { - return Err(ZipError::Unsupported("archive".into(), "ZIP64")); + let (count, dir_size, dir_at, dir_limit) = find_end(data)?; + let past = ZipError::Damaged("the central directory is outside the archive"); + let dir_at = usize::try_from(dir_at).map_err(|_| past.clone())?; + let dir_end = usize::try_from(dir_size).ok().and_then(|s| dir_at.checked_add(s)).filter(|&e| e <= dir_limit).ok_or(past.clone())?; + let dir = data.get(dir_at..dir_end).ok_or(past)?; + if count > MAX_ENTRIES as u64 { + return Err(ZipError::TooMany); } - let mut entries = HashMap::with_capacity(count.min(100_000)); - let mut i = dir; + let count = count as usize; + // Every central entry is at least 46 bytes. + let cut = ZipError::Damaged("the central directory is cut short"); + if count.saturating_mul(46) > dir.len() { + return Err(cut); + } + let mut entries = HashMap::with_capacity(count); + let mut folders = 0; + // (start, end, name) of every entry's local header and data. + let mut spans: Vec<(usize, usize, String)> = Vec::with_capacity(count); + let mut i = 0usize; for _ in 0..count { - if u32_at(data, i) != Some(0x0201_4b50) { - return Err(ZipError::Damaged("central directory")); + if u32_at(dir, i) != Some(CENTRAL) { + return Err(cut); } - let field = |o: usize| u32_at(data, i + o).ok_or(ZipError::Damaged("central directory")); - let short = |o: usize| u16_at(data, i + o).ok_or(ZipError::Damaged("central directory")); + let short = |o: usize| u16_at(dir, i + o).ok_or(cut.clone()); + let long = |o: usize| u32_at(dir, i + o).ok_or(cut.clone()); let (flags, method) = (short(8)?, short(10)?); - let (comp, size) = (field(20)? as usize, field(24)? as usize); + let crc = long(16)?; + let (comp32, size32, offset32) = (long(20)?, long(24)?, long(42)?); let (nlen, xlen, clen) = (short(28)? as usize, short(30)? as usize, short(32)? as usize); - let offset = field(42)? as usize; - let name = data.get(i + 46..i + 46 + nlen).ok_or(ZipError::Damaged("entry name"))?; - let name = String::from_utf8_lossy(name).replace('\\', "/"); - entries.insert(name, Entry { method, flags, comp, size, offset }); + let raw_name = get(dir, i + 46, nlen).ok_or(cut.clone())?; + let extra = get(dir, i + 46 + nlen, xlen).ok_or(cut.clone())?; + get(dir, i + 46 + nlen + xlen, clen).ok_or(cut.clone())?; i += 46 + nlen + xlen + clen; + + let name = decode_name(raw_name, flags & 0x0800 != 0, extra)?; + let shown = || name.chars().take(200).collect::(); + // ZIP64: each 32-bit field that overflowed is in the extra field, in this order. + let (mut size, mut comp, mut offset) = (u64::from(size32), u64::from(comp32), u64::from(offset32)); + if size32 == u32::MAX || comp32 == u32::MAX || offset32 == u32::MAX { + let z = extra_field(extra, 0x0001).ok_or_else(|| ZipError::DamagedEntry(shown(), "has no ZIP64 sizes"))?; + let mut at = 0; + for (wide, value) in [(size32, &mut size), (comp32, &mut comp), (offset32, &mut offset)] { + if wide == u32::MAX { + *value = u64_at(z, at).ok_or_else(|| ZipError::DamagedEntry(shown(), "has its ZIP64 sizes cut short"))?; + at += 8; + } + } + } + let outside = || ZipError::DamagedEntry(shown(), "is outside the archive"); + let offset = usize::try_from(offset).map_err(|_| outside())?; + let comp = usize::try_from(comp).map_err(|_| outside())?; + // An entry's size is checked when it is read: one too large to read may sit unused. + let size = usize::try_from(size).unwrap_or(usize::MAX); + + // Its local header, then its data, all before the central directory. + if u32_at(data, offset) != Some(LOCAL) { + return Err(ZipError::DamagedEntry(shown(), "has no local header")); + } + let lnlen = u16_at(data, offset + 26).ok_or_else(outside)? as usize; + let lxlen = u16_at(data, offset + 28).ok_or_else(outside)? as usize; + let start = offset + 30 + lnlen + lxlen; + let end = start.checked_add(comp).filter(|&e| e <= dir_at).ok_or_else(outside)?; + spans.push((offset, end, shown())); + + let folder = name.ends_with('/') || name.ends_with('\\'); + let path = clean_path(&name)?; + if folder || path.is_empty() { + if size != 0 || comp > 2 { + return Err(ZipError::DamagedEntry(shown(), "is a folder with data")); + } + folders += 1; + continue; + } + if method == 8 && size as u64 > (comp as u64).saturating_mul(MAX_RATIO).saturating_add(4096) { + return Err(ZipError::Bomb(shown())); + } + if method == 0 && flags & 0x41 == 0 && size != comp { + return Err(ZipError::DamagedEntry(shown(), "is stored with two different sizes")); + } + if entries.insert(path, Entry { method, flags, crc, comp, size, data: start }).is_some() { + return Err(ZipError::Duplicate(shown())); + } } - Ok(Archive { data, entries }) + // No two entries may share bytes (the overlapping-entries zip bomb). + spans.sort_unstable_by_key(|s| s.0); + if let Some(w) = spans.windows(2).find(|w| w[0].1 > w[1].0) { + return Err(ZipError::Overlap(w[0].2.clone(), w[1].2.clone())); + } + Ok(Archive { data, entries, folders, budget: Cell::new(MAX_TOTAL) }) } + /// The files' paths (`/`-separated, folders left out). pub fn names(&self) -> impl Iterator { self.entries.keys().map(String::as_str) } - /// The bytes of entry `name` (path inside the archive, `/`-separated). + /// How many files and folder entries the archive lists. + pub fn counts(&self) -> (usize, usize) { + (self.entries.len(), self.folders) + } + + /// The bytes of entry `name` (path inside the archive, `/`-separated), checked against + /// its size and checksum. pub fn read(&self, name: &str) -> Result>, ZipError> { let Some(e) = self.entries.get(name) else { return Ok(None) }; - if e.flags & 1 != 0 { + if e.flags & 0x41 != 0 { return Err(ZipError::Unsupported(name.into(), "encryption")); } + if !matches!(e.method, 0 | 8) { + return Err(ZipError::Unsupported(name.into(), method_name(e.method))); + } if e.size > MAX_ENTRY || e.comp > MAX_ENTRY { return Err(ZipError::TooLarge(name.into())); } - let d = self.data; - if u32_at(d, e.offset) != Some(0x0403_4b50) { - return Err(ZipError::Damaged("local header")); + let left = self.budget.get(); + if e.size as u64 > left { + return Err(ZipError::TooMuch); } - let nlen = u16_at(d, e.offset + 26).ok_or(ZipError::Damaged("local header"))? as usize; - let xlen = u16_at(d, e.offset + 28).ok_or(ZipError::Damaged("local header"))? as usize; - let start = e.offset + 30 + nlen + xlen; - let raw = d.get(start..start + e.comp).ok_or(ZipError::Damaged("entry data"))?; - match e.method { - 0 => Ok(Some(raw.to_vec())), - 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.clamp(1, MAX_ENTRY)).map(Some).map_err(|_| ZipError::Damaged("deflate data")), - _ => Err(ZipError::Unsupported(name.into(), "compression method")), + let raw = get(self.data, e.data, e.comp).ok_or_else(|| ZipError::DamagedEntry(name.into(), "is outside the archive"))?; + let out = match e.method { + 0 => raw.to_vec(), + _ => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1)).map_err(|err| { + let why = if err.status == miniz_oxide::inflate::TINFLStatus::HasMoreOutput { "expands past the size it gives" } else { "has damaged compressed data" }; + ZipError::DamagedEntry(name.into(), why) + })?, + }; + if out.len() != e.size { + return Err(ZipError::DamagedEntry(name.into(), "is not the size it gives")); } + if crc32(&out) != e.crc { + return Err(ZipError::DamagedEntry(name.into(), "fails its checksum")); + } + self.budget.set(left - e.size as u64); + Ok(Some(out)) } } #[cfg(test)] -pub(crate) mod tests { - use super::*; +#[path = "../tests/support/fla.rs"] +pub(crate) mod pack; - /// Builds a zip with stored and deflated entries (for tests). - pub fn make_zip(files: &[(&str, &[u8], bool)]) -> Vec { - let mut out = Vec::new(); - let mut dir = Vec::new(); - for (name, body, deflate) in files { - let data = if *deflate { miniz_oxide::deflate::compress_to_vec(body, 6) } else { body.to_vec() }; - let offset = out.len() as u32; - let method: u16 = if *deflate { 8 } else { 0 }; - out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); - out.extend_from_slice(&[20, 0, 0, 0]); - out.extend_from_slice(&method.to_le_bytes()); - out.extend_from_slice(&[0; 8]); // time, date, crc (not checked) - out.extend_from_slice(&(data.len() as u32).to_le_bytes()); - out.extend_from_slice(&(body.len() as u32).to_le_bytes()); - out.extend_from_slice(&(name.len() as u16).to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); - out.extend_from_slice(name.as_bytes()); - out.extend_from_slice(&data); - dir.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); - dir.extend_from_slice(&[20, 0, 20, 0, 0, 0]); - dir.extend_from_slice(&method.to_le_bytes()); - dir.extend_from_slice(&[0; 8]); - dir.extend_from_slice(&(data.len() as u32).to_le_bytes()); - dir.extend_from_slice(&(body.len() as u32).to_le_bytes()); - dir.extend_from_slice(&(name.len() as u16).to_le_bytes()); - dir.extend_from_slice(&[0; 12]); - dir.extend_from_slice(&offset.to_le_bytes()); - dir.extend_from_slice(name.as_bytes()); - } - let dir_at = out.len() as u32; - out.extend_from_slice(&dir); - out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); - out.extend_from_slice(&[0; 4]); - out.extend_from_slice(&(files.len() as u16).to_le_bytes()); - out.extend_from_slice(&(files.len() as u16).to_le_bytes()); - out.extend_from_slice(&(dir.len() as u32).to_le_bytes()); - out.extend_from_slice(&dir_at.to_le_bytes()); - out.extend_from_slice(&[0, 0]); - out - } - - #[test] - fn reads_stored_and_deflated_entries() { - let z = make_zip(&[("DOMDocument.xml", b"", true), ("LIBRARY\\Ball.xml", b"", false)]); - let a = Archive::open(&z).unwrap(); - assert_eq!(a.read("DOMDocument.xml").unwrap().unwrap(), b""); - assert_eq!(a.read("LIBRARY/Ball.xml").unwrap().unwrap(), b"", "backslashes normalised"); - assert_eq!(a.read("missing").unwrap(), None); - } - - #[test] - fn damaged_archives_are_errors() { - assert_eq!(Archive::open(b"not a zip").err(), Some(ZipError::NotZip)); - let mut z = make_zip(&[("a", b"hello", true)]); - let n = z.len(); - // Point the directory past the end. - z[n - 6] = 0xff; - assert!(Archive::open(&z).is_err()); - } -} +#[cfg(test)] +#[path = "zip_tests.rs"] +mod tests; diff --git a/crates/xfl/src/zip_tests.rs b/crates/xfl/src/zip_tests.rs new file mode 100644 index 00000000..97386a3c --- /dev/null +++ b/crates/xfl/src/zip_tests.rs @@ -0,0 +1,284 @@ +//! The zip reader against the layouts writers produce and the archives an attacker would +//! (ADR 0054). Archives are made by the independent writer in `tests/support/fla.rs`. + +use super::pack::{self, Raw, write}; +use super::*; + +fn zip(files: &[(&str, &[u8], bool)]) -> Vec { + write(&files.iter().map(|(n, b, d)| Raw::new(n, b, *d)).collect::>(), false) +} + +/// The error opening `z`, or reading every file in it. +fn error(z: &[u8]) -> ZipError { + match Archive::open(z) { + Err(e) => e, + Ok(a) => { + let names: Vec = a.names().map(str::to_string).collect(); + names.iter().find_map(|n| a.read(n).err()).expect("an error") + } + } +} + +#[test] +fn reads_stored_and_deflated_entries() { + let z = zip(&[("DOMDocument.xml", b"", true), ("LIBRARY\\Ball.xml", b"", false)]); + let a = Archive::open(&z).unwrap(); + assert_eq!(a.read("DOMDocument.xml").unwrap().unwrap(), b""); + assert_eq!(a.read("LIBRARY/Ball.xml").unwrap().unwrap(), b"", "backslashes normalised"); + assert_eq!(a.read("missing").unwrap(), None); +} + +#[test] +fn the_checksum_matches_the_published_check_value() { + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + assert_eq!(crc32(b""), 0); + let bytes: Vec = (0..5000u32).map(|i| (i * 7 + i / 13) as u8).collect(); + assert_eq!(crc32(&bytes), pack::crc32(&bytes), "the table matches the bitwise form"); +} + +#[test] +fn every_layout_a_writer_uses_reads_the_same() { + let files: std::collections::BTreeMap> = [("DOMDocument.xml", ""), ("LIBRARY/Café/Ünïcödé ★.xml", ""), ("bin/M 1 1.dat", "data")].iter().map(|(p, b)| (p.to_string(), b.as_bytes().to_vec())).collect(); + for v in pack::VARIANTS { + let z = pack::pack(&files, v); + let a = Archive::open(&z).unwrap_or_else(|e| panic!("{}: {e}", v.name)); + assert_eq!(a.counts().0, 3 + usize::from(v.mimetype), "{}", v.name); + for (path, body) in &files { + assert_eq!(a.read(path).unwrap_or_else(|e| panic!("{}: {e}", v.name)).as_deref(), Some(body.as_slice()), "{}: {path}", v.name); + } + } +} + +#[test] +fn names_are_cp437_unless_flagged_or_utf8() { + // "Café.xml" in CP437 (é is 0x82), not valid UTF-8, without the flag. + let mut r = Raw::new("", b"x", false); + (r.name, r.utf8) = (b"LIBRARY/Caf\x82.xml".to_vec(), false); + let z = write(&[r.clone()], false); + assert_eq!(Archive::open(&z).unwrap().names().collect::>(), ["LIBRARY/Café.xml"]); + assert_eq!(pack::cp437("LIBRARY/Café.xml").unwrap(), b"LIBRARY/Caf\x82.xml"); + // Flagged as UTF-8 but isn't: refused, not guessed. + r.utf8 = true; + assert!(matches!(Archive::open(&write(&[r], false)).err(), Some(ZipError::Damaged(_)))); + // A Unicode path field whose checksum doesn't match the name it stands in for is ignored. + let mut r = Raw::new("plain.xml", b"x", false); + r.utf8 = false; + r.extra = [0x75, 0x70, 9, 0, 1, 0, 0, 0, 0, b'o', b't', b'h', b'r'].to_vec(); + assert_eq!(Archive::open(&write(&[r], false)).unwrap().names().collect::>(), ["plain.xml"]); +} + +#[test] +fn damaged_archives_are_errors() { + assert_eq!(Archive::open(b"not a zip").err(), Some(ZipError::NotZip)); + assert_eq!(Archive::open(b"").err(), Some(ZipError::NotZip)); + let mut z = zip(&[("a", b"hello", true)]); + let n = z.len(); + // Point the directory past the end. + z[n - 6] = 0xff; + assert!(Archive::open(&z).is_err()); +} + +#[test] +fn a_truncated_central_directory_is_damaged() { + let z = zip(&[("DOMDocument.xml", b"", true), ("b.xml", b"", true), ("c.xml", b"", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + let end = z.len() - 22; + // Every cut inside the directory, keeping the end record (which still claims 3 entries). + for cut in dir_at..end { + let mut t = z[..cut].to_vec(); + t.extend_from_slice(&z[end..]); + let e = Archive::open(&t).err().unwrap_or_else(|| panic!("cut at {cut} opened")); + assert!(!e.to_string().is_empty()); + } + // The end record says more entries than there are. + let mut t = z.clone(); + t[end + 8] = 9; + t[end + 10] = 9; + assert_eq!(Archive::open(&t).err(), Some(ZipError::Damaged("the central directory is cut short"))); + // Cut short anywhere at all: an error, never a panic. + for cut in 0..z.len() { + let _ = Archive::open(&z[..cut]).map(|a| a.read("DOMDocument.xml")); + } +} + +#[test] +fn overlapping_entries_are_refused() { + // Two names for one local header (the overlapping-file zip bomb). + let mut b = Raw::new("b.xml", b"", true); + b.share = Some(0); + let z = write(&[Raw::new("a.xml", b"", true), b], false); + assert!(matches!(Archive::open(&z).err(), Some(ZipError::Overlap(..))), "{:?}", Archive::open(&z).err()); + // An entry whose stated compressed size runs into the next one. + let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false), ("b.xml", b"bbbbbbbbbb", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + z[dir_at + 20] = 20; // a's compressed size, in its central record + z[dir_at + 24] = 20; + assert!(matches!(Archive::open(&z).err(), Some(ZipError::Overlap(..)))); +} + +#[test] +fn entries_never_reach_past_their_data() { + // An entry's data running into the central directory, or past the end. + for size in [64u32, 0xffff_fff0] { + let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + z[dir_at + 20..dir_at + 24].copy_from_slice(&size.to_le_bytes()); + assert_eq!(Archive::open(&z).err(), Some(ZipError::DamagedEntry("a.xml".into(), "is outside the archive"))); + } + // A local header offset past the end. + let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false)]); + let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize; + z[dir_at + 42..dir_at + 46].copy_from_slice(&0x7fff_0000u32.to_le_bytes()); + assert_eq!(Archive::open(&z).err(), Some(ZipError::DamagedEntry("a.xml".into(), "has no local header"))); +} + +#[test] +fn lying_sizes_and_checksums_are_damaged() { + // Says 100 bytes, inflates to 1000. + let body = vec![b'x'; 1000]; + let mut r = Raw::new("a.xml", &body, true); + r.size = Some(100); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "expands past the size it gives")); + // Says 2000, inflates to 1000. + let mut r = Raw::new("a.xml", &body, true); + r.size = Some(2000); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "is not the size it gives")); + // A stored entry with two sizes. + let mut r = Raw::new("a.xml", &body, false); + r.size = Some(10); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "is stored with two different sizes")); + // The wrong checksum. + let mut r = Raw::new("a.xml", &body, true); + r.crc = Some(12345); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "fails its checksum")); + // Garbage instead of deflate data. + let mut r = Raw::new("a.xml", &body, true); + r.compressed = Some(vec![0xff; 40]); + assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "has damaged compressed data")); +} + +#[test] +fn compression_bombs_are_refused() { + // A real 64 MB of zeros deflates past the ratio cap: refused before inflating. + let zeros = vec![0u8; 64 << 20]; + let z = zip(&[("bomb.xml", &zeros, true)]); + assert!(z.len() < 100_000, "{}", z.len()); + assert_eq!(Archive::open(&z).err(), Some(ZipError::Bomb("bomb.xml".into()))); + // A size claim no deflate stream of that length could meet. + let mut r = Raw::new("a.xml", &[7; 100], true); + r.size = Some(200 << 20); + assert_eq!(Archive::open(&write(&[r], false)).err(), Some(ZipError::Bomb("a.xml".into()))); + // One entry larger than an entry may be, at a believable ratio: refused before inflating. + let mut r = Raw::new("big.dat", b"", true); + r.compressed = Some(vec![0; 300 << 10]); + r.size = Some(MAX_ENTRY as u64 + 1); + let z = write(&[r], false); + assert_eq!(error(&z), ZipError::TooLarge("big.dat".into())); +} + +#[test] +fn the_archive_hands_out_at_most_its_budget() { + let body = vec![b'a'; 4096]; + let z = zip(&[("a.xml", &body, true)]); + let a = Archive::open(&z).unwrap(); + a.budget.set(10_000); + assert!(a.read("a.xml").is_ok() && a.read("a.xml").is_ok()); + assert_eq!(a.read("a.xml").err(), Some(ZipError::TooMuch), "a third read passes 10,000 bytes"); +} + +#[test] +fn unsafe_paths_are_refused() { + for name in ["../escape.xml", "LIBRARY/../../escape.xml", "/etc/passwd", "\\Windows\\win.ini", "C:\\Windows\\win.ini", "C:escape.xml", "LIBRARY\\..\\..\\x", "a\0b"] { + let z = zip(&[("DOMDocument.xml", b"", true), (name, b"x", false)]); + assert!(matches!(Archive::open(&z).err(), Some(ZipError::Unsafe(_))), "{name:?}: {:?}", Archive::open(&z).err()); + } + // Harmless odd names are tidied, not refused. + let z = zip(&[("./LIBRARY//a.xml", b"x", false)]); + assert_eq!(Archive::open(&z).unwrap().names().collect::>(), ["LIBRARY/a.xml"]); +} + +#[test] +fn duplicate_names_are_refused() { + let z = zip(&[("LIBRARY/a.xml", b"one", false), ("LIBRARY\\a.xml", b"two", false)]); + assert_eq!(Archive::open(&z).err(), Some(ZipError::Duplicate("LIBRARY\\a.xml".into()))); + // Folders listed twice are harmless. + let z = zip(&[("LIBRARY/", b"", false), ("LIBRARY\\", b"", false), ("LIBRARY/a.xml", b"one", false)]); + assert_eq!(Archive::open(&z).unwrap().counts(), (1, 2)); +} + +#[test] +fn deeply_nested_folders_are_refused() { + let ok = format!("{}a.xml", "f/".repeat(MAX_DEPTH)); + assert!(Archive::open(&zip(&[(&ok, b"x", false)])).is_ok()); + let deep = format!("{}a.xml", "f/".repeat(MAX_DEPTH + 1)); + assert!(matches!(Archive::open(&zip(&[(&deep, b"x", false)])).err(), Some(ZipError::TooDeep(_)))); + // As deep as a name can be: refused quickly, not recursed into. + let deepest = "f/".repeat(30_000); + assert!(matches!(Archive::open(&zip(&[(&deepest, b"", false)])).err(), Some(ZipError::TooDeep(_)))); +} + +#[test] +fn unsupported_features_say_what_they_are() { + let mut r = Raw::new("a.xml", b"secret", false); + r.flags = 1; + assert_eq!(error(&write(&[r], false)), ZipError::Unsupported("a.xml".into(), "encryption")); + let mut r = Raw::new("a.xml", b"x", false); + r.method = Some(14); + assert_eq!(error(&write(&[r], false)), ZipError::Unsupported("a.xml".into(), "LZMA compression")); + // Split archives. + let mut z = zip(&[("a.xml", b"x", false)]); + let end = z.len() - 22; + z[end + 4] = 1; + assert_eq!(Archive::open(&z).err(), Some(ZipError::UnsupportedArchive("split across several files"))); + // Too many entries for the directory to hold, and more than the cap. + let mut z = zip(&[("a.xml", b"x", false)]); + let end = z.len() - 22; + z[end + 8..end + 12].copy_from_slice(&[0xfe, 0xff, 0xfe, 0xff]); + assert!(Archive::open(&z).is_err()); +} + +#[test] +fn zip64_archives_open_and_their_damage_is_named() { + let mut a = Raw::new("a.xml", b"", true); + a.zip64 = true; + let mut b = Raw::new("b.xml", b"", false); + (b.zip64, b.descriptor) = (true, true); + let z = write(&[a.clone(), b], true); + let arch = Archive::open(&z).unwrap(); + assert_eq!(arch.read("b.xml").unwrap().unwrap(), b""); + // The locator gone. + let mut t = z.clone(); + let loc = t.len() - 22 - 20; + t[loc] = 0; + assert_eq!(Archive::open(&t).err(), Some(ZipError::Damaged("the ZIP64 end record is missing"))); + // An entry that says ZIP64 without the extra field. + a.zip64 = false; + let mut t = write(&[a], false); + let dir_at = u32_at(&t, t.len() - 6).unwrap() as usize; + t[dir_at + 24..dir_at + 28].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(Archive::open(&t).err(), Some(ZipError::DamagedEntry("a.xml".into(), "has no ZIP64 sizes"))); +} + +#[test] +fn errors_read_as_sentences() { + let all = [ + ZipError::NotZip, + ZipError::Damaged("the central directory is cut short"), + ZipError::DamagedEntry("a.xml".into(), "fails its checksum"), + ZipError::UnsupportedArchive("split across several files"), + ZipError::Unsupported("a.xml".into(), "encryption"), + ZipError::TooLarge("a.xml".into()), + ZipError::TooMuch, + ZipError::TooMany, + ZipError::Bomb("a.xml".into()), + ZipError::Overlap("a.xml".into(), "b.xml".into()), + ZipError::Unsafe("../a.xml".into()), + ZipError::Duplicate("a.xml".into()), + ZipError::TooDeep("f/f/a.xml".into()), + ]; + for e in all { + let s = e.to_string(); + assert!(s.len() > 12 && !s.contains("{") && s.chars().next().is_some_and(|c| !c.is_uppercase() || c == 'A'), "{s}"); + } + assert_eq!(ZipError::TooMuch.to_string(), "the archive asks for more than 1024 MB in all"); +} diff --git a/crates/xfl/tests/support/fla.rs b/crates/xfl/tests/support/fla.rs new file mode 100644 index 00000000..b873c2c5 --- /dev/null +++ b/crates/xfl/tests/support/fla.rs @@ -0,0 +1,328 @@ +//! Test support: packs an XFL package into `.fla` (zip) archives in memory, in each of the ways +//! zip writers lay one out (ADR 0054), and writes hand-made entries for hostile archives. +//! +//! Written from the published format (PKWARE APPNOTE 6.3), independently of the reader in +//! `src/zip.rs` (it has its own checksum), so a misreading in one is caught by the other. +//! Shared by the xfl crate's unit and corpus tests and the engine's golden tests (`#[path]`). +#![allow(dead_code)] + +use std::collections::BTreeMap; + +/// How a variant compresses its entries. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Compression { + Deflate, + Stored, + /// XML deflated, images stored (as most writers do), the rest alternating. + Mixed, +} + +/// How a variant writes entry names. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Names { + /// UTF-8 with flag bit 11 set. + Utf8Flag, + /// UTF-8 without the flag (common, though the format says CP437). + Utf8Unflagged, + /// CP437 bytes without the flag, as the format specifies (names CP437 can't spell are + /// written as UTF-8 with the flag). + Cp437, + /// An ASCII stand-in name with the real one in the Info-ZIP Unicode path field. + UnicodeExtra, +} + +/// One way of packing a package. +#[derive(Clone, Copy, Debug)] +pub struct Variant { + pub name: &'static str, + pub compression: Compression, + /// An entry for every folder, before the files in it. + pub folders: bool, + /// The `mimetype` entry first, stored, as Animate writes it. + pub mimetype: bool, + /// `\` between folders, as some Windows tools write. + pub backslashes: bool, + pub names: Names, + /// Sizes and checksums after the data (bit 3), as streaming writers do. + pub descriptors: bool, + /// ZIP64 sizes on every entry and a ZIP64 end record. + pub zip64: bool, +} + +const BASE: Variant = Variant { name: "", compression: Compression::Deflate, folders: false, mimetype: false, backslashes: false, names: Names::Utf8Flag, descriptors: false, zip64: false }; + +/// Every variant each corpus package is checked in. +pub const VARIANTS: &[Variant] = &[ + Variant { name: "as Animate writes it (mimetype first, deflated)", mimetype: true, ..BASE }, + Variant { name: "stored", compression: Compression::Stored, ..BASE }, + Variant { name: "mixed, with folder entries", compression: Compression::Mixed, folders: true, mimetype: true, ..BASE }, + Variant { name: "Windows separators, unflagged UTF-8 names", backslashes: true, folders: true, names: Names::Utf8Unflagged, ..BASE }, + Variant { name: "CP437 names", names: Names::Cp437, compression: Compression::Mixed, ..BASE }, + Variant { name: "Unicode path fields", names: Names::UnicodeExtra, ..BASE }, + Variant { name: "data descriptors", descriptors: true, compression: Compression::Mixed, ..BASE }, + Variant { name: "ZIP64", zip64: true, compression: Compression::Mixed, ..BASE }, + Variant { name: "everything at once", compression: Compression::Mixed, folders: true, mimetype: true, backslashes: true, names: Names::Cp437, descriptors: true, zip64: true }, +]; + +/// One entry as written. Fields a hostile test may change are public. +#[derive(Clone, Debug, Default)] +pub struct Raw { + /// The name's bytes as stored. + pub name: Vec, + /// The uncompressed bytes. + pub body: Vec, + pub deflate: bool, + /// General purpose flag bits besides 3 and 11 (bit 0: encrypted). + pub flags: u16, + pub utf8: bool, + pub descriptor: bool, + pub zip64: bool, + /// Overrides: the method, the uncompressed size and the checksum the headers give. + pub method: Option, + pub size: Option, + pub crc: Option, + /// Extra field bytes in the central directory (besides ZIP64's). + pub extra: Vec, + /// Points this entry's central record at entry `n`'s local header instead of its own. + pub share: Option, + /// Stored as compressed bytes: these instead of compressing `body`. + pub compressed: Option>, +} + +impl Raw { + pub fn new(name: &str, body: &[u8], deflate: bool) -> Raw { + Raw { name: name.as_bytes().to_vec(), body: body.to_vec(), deflate, utf8: true, ..Raw::default() } + } +} + +/// CRC-32 (ISO-HDLC), bit by bit. +pub fn crc32(data: &[u8]) -> u32 { + let mut c = !0u32; + for &b in data { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 != 0 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 }; + } + } + !c +} + +/// `s` in CP437, if every character is in it. +pub fn cp437(s: &str) -> Option> { + const HIGH: &str = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u{a0}"; + s.chars().map(|c| if c.is_ascii() { Some(c as u8) } else { HIGH.chars().position(|h| h == c).map(|i| 0x80 + i as u8) }).collect() +} + +fn le16(out: &mut Vec, v: u16) { + out.extend_from_slice(&v.to_le_bytes()); +} +fn le32(out: &mut Vec, v: u32) { + out.extend_from_slice(&v.to_le_bytes()); +} +fn le64(out: &mut Vec, v: u64) { + out.extend_from_slice(&v.to_le_bytes()); +} + +/// Writes `entries` as a zip archive, with a ZIP64 end record if `zip64_end`. +pub fn write(entries: &[Raw], zip64_end: bool) -> Vec { + let mut out = Vec::new(); + let mut central = Vec::new(); + let mut offsets = Vec::new(); + // (time, date): 2025-11-11 12:00. + let (time, date) = (0x6000u16, 0x5B6Bu16); + for e in entries { + let data = match &e.compressed { + Some(c) => c.clone(), + None if e.deflate => miniz_oxide::deflate::compress_to_vec(&e.body, 6), + None => e.body.clone(), + }; + let method = e.method.unwrap_or(if e.deflate { 8 } else { 0 }); + let crc = e.crc.unwrap_or_else(|| crc32(&e.body)); + let size = e.size.unwrap_or(e.body.len() as u64); + let comp = data.len() as u64; + let flags = e.flags | if e.descriptor { 8 } else { 0 } | if e.utf8 { 0x800 } else { 0 }; + let version: u16 = if e.zip64 { 45 } else { 20 }; + let offset = out.len() as u64; + offsets.push(offset); + // The local header. + le32(&mut out, 0x0403_4b50); + le16(&mut out, version); + le16(&mut out, flags); + le16(&mut out, method); + le16(&mut out, time); + le16(&mut out, date); + let local_extra = if e.zip64 { + let mut x = Vec::new(); + le16(&mut x, 1); + le16(&mut x, 16); + le64(&mut x, if e.descriptor { 0 } else { size }); + le64(&mut x, if e.descriptor { 0 } else { comp }); + x + } else { + Vec::new() + }; + if e.descriptor { + out.extend_from_slice(&[0; 12]); + } else { + le32(&mut out, crc); + le32(&mut out, if e.zip64 { u32::MAX } else { comp as u32 }); + le32(&mut out, if e.zip64 { u32::MAX } else { size as u32 }); + } + le16(&mut out, e.name.len() as u16); + le16(&mut out, local_extra.len() as u16); + out.extend_from_slice(&e.name); + out.extend_from_slice(&local_extra); + out.extend_from_slice(&data); + if e.descriptor { + le32(&mut out, 0x0807_4b50); + le32(&mut out, crc); + if e.zip64 { + le64(&mut out, comp); + le64(&mut out, size); + } else { + le32(&mut out, comp as u32); + le32(&mut out, size as u32); + } + } + // Its central record. + let at = e.share.and_then(|n| offsets.get(n).copied()).unwrap_or(offset); + let mut extra = Vec::new(); + if e.zip64 { + le16(&mut extra, 1); + le16(&mut extra, 24); + le64(&mut extra, size); + le64(&mut extra, comp); + le64(&mut extra, at); + } + extra.extend_from_slice(&e.extra); + le32(&mut central, 0x0201_4b50); + le16(&mut central, version); + le16(&mut central, version); + le16(&mut central, flags); + le16(&mut central, method); + le16(&mut central, time); + le16(&mut central, date); + le32(&mut central, crc); + le32(&mut central, if e.zip64 { u32::MAX } else { comp as u32 }); + le32(&mut central, if e.zip64 { u32::MAX } else { size as u32 }); + le16(&mut central, e.name.len() as u16); + le16(&mut central, extra.len() as u16); + le16(&mut central, 0); // comment + le16(&mut central, 0); // disk + le16(&mut central, 0); // internal attributes + let folder = e.name.last().is_some_and(|&c| c == b'/' || c == b'\\'); + le32(&mut central, if folder { 0x10 } else { 0 }); + le32(&mut central, if e.zip64 { u32::MAX } else { at as u32 }); + central.extend_from_slice(&e.name); + central.extend_from_slice(&extra); + } + let dir_at = out.len() as u64; + out.extend_from_slice(¢ral); + let n = entries.len() as u64; + if zip64_end { + let record = out.len() as u64; + le32(&mut out, 0x0606_4b50); + le64(&mut out, 44); + le16(&mut out, 45); + le16(&mut out, 45); + le32(&mut out, 0); + le32(&mut out, 0); + le64(&mut out, n); + le64(&mut out, n); + le64(&mut out, central.len() as u64); + le64(&mut out, dir_at); + le32(&mut out, 0x0706_4b50); + le32(&mut out, 0); + le64(&mut out, record); + le32(&mut out, 1); + } + le32(&mut out, 0x0605_4b50); + le32(&mut out, 0); // disks + let (count, size, at) = if zip64_end { (u16::MAX, u32::MAX, u32::MAX) } else { (n as u16, central.len() as u32, dir_at as u32) }; + le16(&mut out, count); + le16(&mut out, count); + le32(&mut out, size); + le32(&mut out, at); + le16(&mut out, 0); + out +} + +/// The entries `files` (paths inside the package) become in `v`. +pub fn entries(files: &BTreeMap>, v: &Variant) -> Vec { + let mut out = Vec::new(); + let named = |path: &str, body: &[u8], deflate: bool| { + let shown = if v.backslashes { path.replace('/', "\\") } else { path.to_string() }; + let mut r = Raw::new(&shown, body, deflate); + r.descriptor = v.descriptors; + r.zip64 = v.zip64; + match v.names { + Names::Utf8Flag => {} + Names::Utf8Unflagged => r.utf8 = false, + Names::Cp437 => { + if let Some(b) = cp437(&shown) { + (r.name, r.utf8) = (b, false); + } + } + Names::UnicodeExtra => { + let stand_in: Vec = shown.chars().map(|c| if c.is_ascii() { c as u8 } else { b'_' }).collect(); + le16(&mut r.extra, 0x7075); + le16(&mut r.extra, (5 + shown.len()) as u16); + r.extra.push(1); + le32(&mut r.extra, crc32(&stand_in)); + r.extra.extend_from_slice(shown.as_bytes()); + (r.name, r.utf8) = (stand_in, false); + } + } + r + }; + if v.mimetype { + out.push(named("mimetype", b"application/vnd.adobe.xfl", false)); + } + let mut made = std::collections::BTreeSet::new(); + for (i, (path, body)) in files.iter().enumerate() { + if v.folders { + let parts: Vec<&str> = path.split('/').collect(); + for k in 1..parts.len() { + let folder = format!("{}/", parts[..k].join("/")); + if made.insert(folder.clone()) { + out.push(named(&folder, b"", false)); + } + } + } + let image = [".png", ".jpg", ".jpeg", ".gif"].iter().any(|x| path.to_ascii_lowercase().ends_with(x)); + let deflate = match v.compression { + Compression::Deflate => true, + Compression::Stored => false, + Compression::Mixed => path.ends_with(".xml") || (!image && i % 2 == 0), + }; + out.push(named(path, body, deflate)); + } + out +} + +/// `files` packed as a `.fla` in variant `v`. +pub fn pack(files: &BTreeMap>, v: &Variant) -> Vec { + write(&entries(files, v), v.zip64) +} + +/// A package folder's files by their path inside it, leaving out its `golden/` renders. +pub fn package(dir: &std::path::Path) -> BTreeMap> { + fn walk(dir: &std::path::Path, prefix: &str, out: &mut BTreeMap>) { + let mut list: Vec<_> = std::fs::read_dir(dir).map(|r| r.flatten().collect()).unwrap_or_default(); + list.sort_by_key(|e| e.file_name()); + for e in list { + let name = e.file_name().to_string_lossy().into_owned(); + let path = if prefix.is_empty() { name.clone() } else { format!("{prefix}/{name}") }; + if e.path().is_dir() { + if path != "golden" { + walk(&e.path(), &path, out); + } + } else if let Ok(b) = std::fs::read(e.path()) { + out.insert(path, b); + } + } + } + let mut out = BTreeMap::new(); + walk(dir, "", &mut out); + out +} From 4b2155d87ec8d402199cec7097bde9fc25ecd0b8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:47:25 -0700 Subject: [PATCH 051/402] test(xfl): the corpus as .fla variants and a hostile .fla fuzz (M4) Every package in nine zip layouts imports identically to its folder; the folder, its .xfl, its DOMDocument.xml, the .fla and a renamed .fla open the same; 9,664 hostile archives never panic. import_fla_with_fonts; .fla recognised by content; Flash CS4 binary .fla named in the error. --- crates/xfl/src/import.rs | 35 ++++- crates/xfl/src/lib.rs | 2 +- crates/xfl/tests/fla.rs | 327 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 359 insertions(+), 5 deletions(-) create mode 100644 crates/xfl/tests/fla.rs diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 870fd762..a0dbe1bd 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -885,21 +885,48 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do /// Largest `.fla` archive read. pub const MAX_FLA_BYTES: u64 = crate::zip::MAX_ENTRY as u64 * 4; -/// Imports a `.fla` archive from its bytes (a file the browser handed over, say). +/// The first bytes of a compound (OLE) file: a `.fla` saved by Flash CS4 or earlier. +const OLE_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]; + +/// Imports a `.fla` archive from its bytes (a file the browser handed over, say). Text is laid +/// out with the fonts on this computer. pub fn import_fla(data: &[u8]) -> Result<(Document, Report), XflError> { + fla_from(data, None) +} + +/// Imports a `.fla` archive, laying text out with `fonts` (tests, and hosts with their own +/// font library). +pub fn import_fla_with_fonts(data: &[u8], fonts: &Fonts) -> Result<(Document, Report), XflError> { + fla_from(data, Some(fonts)) +} + +fn fla_from(data: &[u8], fonts: Option<&Fonts>) -> Result<(Document, Report), XflError> { if data.len() as u64 > MAX_FLA_BYTES { return Err(XflError::NotXfl("the file is too large".into())); } + if data.starts_with(&OLE_MAGIC) { + return Err(XflError::NotXfl("this .fla was saved by Flash CS4 or earlier, in a format AniCraft can't read: open it in Animate and save it again".into())); + } let archive = crate::zip::Archive::open(data)?; let read = |p: &str| -> Result>, XflError> { Ok(archive.read(p)?) }; - import_with(&read) + import_from(&read, fonts) } -/// Imports from disk: an XFL folder, its `.xfl` file, or a `.fla` archive. +/// Whether the file at `path` starts as a zip archive or an old binary `.fla` does. +fn looks_like_fla(path: &std::path::Path) -> bool { + use std::io::Read; + let mut head = [0u8; 8]; + let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut head)).unwrap_or(0); + head.get(..n).is_some_and(|h| h.starts_with(b"PK\x03\x04") || h.starts_with(b"PK\x05\x06") || h.starts_with(&OLE_MAGIC)) +} + +/// Imports from disk: an XFL folder, its `.xfl` file (or any file in the folder, such as its +/// `DOMDocument.xml`), or a `.fla` archive (recognised by its contents too, so a renamed one +/// opens). pub fn import_path(path: &std::path::Path) -> Result<(Document, Report), XflError> { let meta = std::fs::metadata(path)?; let is_fla = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("fla")); - if meta.is_file() && is_fla { + if meta.is_file() && (is_fla || looks_like_fla(path)) { if meta.len() > MAX_FLA_BYTES { return Err(XflError::NotXfl("the file is too large".into())); } diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index 2a204ed8..ed4b2a96 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -13,7 +13,7 @@ pub mod text; pub use anicraft_xml as xml; pub mod zip; -pub use import::{MAX_FLA_BYTES, Report, XflError, import_fla, import_path, import_with, import_with_fonts}; +pub use import::{MAX_FLA_BYTES, Report, XflError, import_fla, import_fla_with_fonts, import_path, import_with, import_with_fonts}; #[cfg(test)] mod tests; diff --git a/crates/xfl/tests/fla.rs b/crates/xfl/tests/fla.rs new file mode 100644 index 00000000..5953447f --- /dev/null +++ b/crates/xfl/tests/fla.rs @@ -0,0 +1,327 @@ +//! The XFL corpus as `.fla` archives (ADR 0054): every package, packed every way zip writers +//! lay one out, imports exactly as its folder does (same document, same report); hostile +//! archives built from the corpus never panic and fail with a readable error; and a generated +//! 50 MB `.fla` measures import time (`cargo test --release -p anicraft-xfl --test fla -- +//! --ignored --nocapture`). The golden renders of the `.fla` forms are checked in +//! `crates/engine/tests/xfl_corpus.rs`. + +#[path = "support/fla.rs"] +mod pack; + +use anicraft_doc::{Document, evaluate}; +use anicraft_text::Fonts; +use anicraft_xfl::{Report, XflError, import_fla_with_fonts, import_with_fonts}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +fn corpus() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus") +} + +fn cases() -> Vec { + let mut out: Vec = std::fs::read_dir(corpus()).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + out.sort(); + out +} + +fn no_fonts() -> Fonts { + Fonts::from_faces(Vec::new()) +} + +fn from_folder(files: &BTreeMap>, fonts: &Fonts) -> (Document, Report) { + let read = |p: &str| -> Result>, XflError> { Ok(files.get(p).cloned()) }; + import_with_fonts(&read, fonts).unwrap() +} + +#[test] +fn every_package_imports_identically_from_every_fla_variant() { + let fonts = no_fonts(); + let mut checked = 0; + for case in cases() { + let files = pack::package(&corpus().join(&case)); + let (doc, report) = from_folder(&files, &fonts); + for v in pack::VARIANTS { + let fla = pack::pack(&files, v); + let (d, r) = import_fla_with_fonts(&fla, &fonts).unwrap_or_else(|e| panic!("{case}, {}: {e}", v.name)); + assert!(d == doc, "{case}, {}: the document differs from the folder's", v.name); + assert_eq!(r, report, "{case}, {}: the report differs", v.name); + checked += 1; + } + } + assert_eq!(checked, cases().len() * pack::VARIANTS.len()); +} + +/// From disk, through the same entry point the app uses, with this computer's fonts: the +/// folder, its `.xfl` file, its `DOMDocument.xml`, the `.fla`, and the `.fla` renamed. +#[test] +fn every_package_opens_the_same_from_disk_in_every_form() { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-fla-forms"); + std::fs::create_dir_all(&dir).unwrap(); + for case in cases() { + let folder = corpus().join(&case); + let (doc, report) = anicraft_xfl::import_path(&folder).unwrap_or_else(|e| panic!("{case}: {e}")); + let fla = dir.join(format!("{case}.fla")); + std::fs::write(&fla, pack::pack(&pack::package(&folder), &pack::VARIANTS[0])).unwrap(); + let renamed = dir.join(format!("{case} (copy).zip")); + std::fs::copy(&fla, &renamed).unwrap(); + for path in [folder.join(format!("{case}.xfl")), folder.join("DOMDocument.xml"), fla, renamed] { + let (d, r) = anicraft_xfl::import_path(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + assert!(d == doc && r == report, "{} opens differently from its folder", path.display()); + } + } +} + +/// Names outside ASCII, in every encoding: the symbols package with a library file renamed. +#[test] +fn non_ascii_names_import_identically_in_every_encoding() { + let fonts = no_fonts(); + let mut files = pack::package(&corpus().join("symbols")); + let doc_xml = String::from_utf8(files["DOMDocument.xml"].clone()).unwrap(); + let old = files.keys().find(|p| p.starts_with("LIBRARY/") && p.ends_with(".xml")).unwrap().clone(); + let href = old.trim_start_matches("LIBRARY/").to_string(); + let new_href = format!("Café ü/Ünïcödé ½ {href}"); + assert!(doc_xml.contains(&format!("href=\"{href}\"")), "{href}"); + files.insert("DOMDocument.xml".into(), doc_xml.replace(&format!("href=\"{href}\""), &format!("href=\"{new_href}\"")).into_bytes()); + let body = files.remove(&old).unwrap(); + files.insert(format!("LIBRARY/{new_href}"), body); + let (doc, report) = from_folder(&files, &fonts); + assert!(doc.library.len() >= 5, "the renamed symbol still imports"); + for v in pack::VARIANTS { + let (d, r) = import_fla_with_fonts(&pack::pack(&files, v), &fonts).unwrap_or_else(|e| panic!("{}: {e}", v.name)); + assert!(d == doc && r == report, "{}", v.name); + } +} + +#[test] +fn an_old_binary_fla_says_what_to_do() { + let mut old = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]; + old.resize(4096, 0); + let e = anicraft_xfl::import_fla(&old).err().unwrap().to_string(); + assert!(e.contains("Flash CS4 or earlier") && e.contains("save it again"), "{e}"); + let e = anicraft_xfl::import_fla(b"PK\x03\x04 cut short").err().unwrap().to_string(); + assert_eq!(e, "not a zip archive (no end-of-directory record)"); +} + +/// A small deterministic generator (xorshift64*). +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +/// Imports a hostile archive: it may fail, with a readable error, but must not panic, and +/// what it imports must evaluate. +fn survive(fla: &[u8], fonts: &Fonts, what: &str, errors: &mut BTreeMap) { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match import_fla_with_fonts(fla, fonts) { + Ok((doc, _)) => { + let n = doc.frame_count(); + for f in [0, n / 2, n.saturating_sub(1)] { + let _ = evaluate(&doc, f); + } + None + } + Err(e) => { + // Grouped by kind for the summary: `Zip(Bomb`, `Xml(…`. + let kind: String = format!("{e:?}").split('(').take(2).collect::>().join("("); + Some((e.to_string(), kind)) + } + })); + match result { + Err(_) => panic!("panicked on {what}"), + Ok(Some((e, kind))) => { + assert!(e.len() > 10 && !e.contains("Error") && !e.contains('{'), "{what}: an unreadable error: {e:?}"); + *errors.entry(kind).or_default() += 1; + } + Ok(None) => *errors.entry("(imported)".into()).or_default() += 1, + } +} + +/// Offsets of every central record in `z` (found through the end record, or its ZIP64 form). +fn central_records(z: &[u8]) -> Vec { + let end = z.len() - 22; + let mut at = u32::from_le_bytes(z[end + 16..end + 20].try_into().unwrap()) as usize; + if at == u32::MAX as usize { + let record = u64::from_le_bytes(z[end - 12..end - 4].try_into().unwrap()) as usize; + at = u64::from_le_bytes(z[record + 48..record + 56].try_into().unwrap()) as usize; + } + let mut out = Vec::new(); + let mut i = at; + while z.get(i..i + 4) == Some(&[0x50, 0x4b, 1, 2]) { + out.push(i); + let n = |o: usize| u16::from_le_bytes([z[i + o], z[i + o + 1]]) as usize; + i += 46 + n(28) + n(30) + n(32); + } + out +} + +/// A change to an archive's entries before it is written. +type Edit = Box)>; + +/// Each corpus package as a `.fla`, attacked: every header field of every entry set to edge +/// values, random bytes changed in the headers and anywhere, cut short, entries pointed at each +/// other, and names made unsafe. +#[test] +fn hostile_fla_archives_never_panic_and_fail_readably() { + let fonts = no_fonts(); + let start = std::time::Instant::now(); + let mut errors = BTreeMap::new(); + let mut variants = 0; + for case in cases() { + let files = pack::package(&corpus().join(&case)); + for v in [&pack::VARIANTS[0], &pack::VARIANTS[7]] { + let z = pack::pack(&files, v); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15 ^ (case.len() as u64) << 20 ^ z.len() as u64); + let records = central_records(&z); + assert!(records.len() >= files.len(), "{case}"); + // Header fields at edge values: (offset in the central record, width). + const FIELDS: &[(usize, usize)] = &[(8, 2), (10, 2), (16, 4), (20, 4), (24, 4), (28, 2), (30, 2), (32, 2), (34, 2), (42, 4)]; + for &rec in records.iter().take(6) { + for &(off, width) in FIELDS { + for value in [0u32, 1, 0x7f, 0xffff, 0x7fff_ffff, 0xffff_ffff, rng.next() as u32] { + let mut t = z.clone(); + t[rec + off..rec + off + width].copy_from_slice(&value.to_le_bytes()[..width]); + survive(&t, &fonts, &format!("{case}: record at {rec}, field {off} = {value:#x}"), &mut errors); + variants += 1; + } + } + // The local header's lengths too. + let local = u32::from_le_bytes(z[rec + 42..rec + 46].try_into().unwrap()) as usize; + for (off, value) in [(26usize, 0xffffu16), (28, 0xffff), (28, 0), (18, 0xffff), (22, 0)] { + let mut t = z.clone(); + if let Some(f) = t.get_mut(local + off..local + off + 2) { + f.copy_from_slice(&value.to_le_bytes()); + } + survive(&t, &fonts, &format!("{case}: local header at {local}, field {off}"), &mut errors); + variants += 1; + } + } + // Random bytes in the central directory and end record, then anywhere. + let dir_at = records.first().copied().unwrap_or(0); + for n in 0..60 { + let mut t = z.clone(); + let lo = if n < 40 { dir_at } else { 0 }; + for _ in 0..1 + rng.below(4) { + let i = lo + rng.below(t.len() - lo); + t[i] = rng.next() as u8; + } + survive(&t, &fonts, &format!("{case}: random bytes #{n}"), &mut errors); + variants += 1; + } + // Cut short. + for k in 0..24 { + survive(&z[..z.len() * k / 24], &fonts, &format!("{case}: cut at {k}/24"), &mut errors); + variants += 1; + } + } + // Built hostile: names that leave the package, duplicates, overlaps, lying sizes. + let mut entries = pack::entries(&files, &pack::VARIANTS[0]); + let last = entries.len() - 1; + let edits: Vec<(&str, Edit)> = vec![ + ("a .. name", Box::new(move |e| e[last].name = b"LIBRARY/../../../x.xml".to_vec())), + ("an absolute name", Box::new(move |e| e[last].name = b"/etc/x.xml".to_vec())), + ("a drive name", Box::new(move |e| e[last].name = b"C:\\x.xml".to_vec())), + ("a duplicate", Box::new(|e| e.push(e[1].clone()))), + ("a duplicate by separator", Box::new(|e| { + let mut d = e[1].clone(); + d.name = d.name.iter().map(|&c| if c == b'/' { b'\\' } else { c }).collect(); + e.push(d); + })), + ("overlapping entries", Box::new(|e| { + let mut d = e[1].clone(); + d.name = b"other.xml".to_vec(); + d.share = Some(1); + e.push(d); + })), + ("a lying size", Box::new(|e| e[1].size = Some(3))), + ("a lying checksum", Box::new(|e| e[1].crc = Some(1))), + ("a ratio bomb", Box::new(|e| e[1].size = Some(200 << 20))), + ("deep folders", Box::new(|e| e[1].name = "d/".repeat(200).into_bytes())), + ]; + for (what, edit) in &edits { + let mut t = entries.clone(); + edit(&mut t); + let z = pack::write(&t, false); + let before = errors.get("(imported)").copied(); + survive(&z, &fonts, &format!("{case}: {what}"), &mut errors); + assert_eq!(errors.get("(imported)").copied(), before, "{case}: {what} imported"); + variants += 1; + } + entries.clear(); + } + assert!(variants > 5000, "{variants}"); + eprintln!("{variants} hostile .fla archives in {:?}: {errors:#?}", start.elapsed()); +} + +/// A generated `.fla` of about 50 MB: 400 symbols with long edge lists (deflated XML) and 24 +/// noisy PNG bitmaps (stored), placed on a 240-frame timeline. +fn big_fla() -> (Vec, usize) { + let mut files = BTreeMap::new(); + let mut rng = Rng(42); + let mut includes = String::new(); + for s in 0..400 { + let mut edges = String::new(); + for e in 0..600 { + let (x, y) = (rng.below(20_000), rng.below(20_000)); + edges.push_str(&format!("", x + 200, y + e, x + 100, y + 300)); + } + let xml = format!("{edges}", rng.next() & 0xffffff); + files.insert(format!("LIBRARY/Symbols/Symbol {s}.xml"), xml.into_bytes()); + includes.push_str(&format!("")); + } + let mut media = String::new(); + for b in 0..24 { + let (w, h) = (1024u32, 512u32); + let pixels: Vec = (0..w * h * 4).map(|_| rng.next() as u8).collect(); + let mut png = Vec::new(); + { + let mut enc = png::Encoder::new(&mut png, w, h); + enc.set_color(png::ColorType::Rgba); + enc.set_compression(png::Compression::Fast); + let mut wr = enc.write_header().unwrap(); + wr.write_image_data(&pixels).unwrap(); + } + files.insert(format!("LIBRARY/Images/noise {b}.png"), png); + media.push_str(&format!("")); + } + let mut frames = String::new(); + for f in 0..240 { + frames.push_str(&format!("", f % 400, f % 24)); + } + let doc = format!("{media}{includes}{frames}"); + files.insert("DOMDocument.xml".into(), doc.into_bytes()); + let n = files.len(); + (pack::pack(&files, &pack::VARIANTS[2]), n) +} + +#[test] +#[ignore = "a measurement: run with --release -- --ignored --nocapture"] +fn measure_importing_a_50_mb_fla() { + let (fla, files) = big_fla(); + let fonts = no_fonts(); + let mut times = Vec::new(); + for _ in 0..5 { + let t = std::time::Instant::now(); + let a = anicraft_xfl::zip::Archive::open(&fla).unwrap(); + let open = t.elapsed(); + let names: Vec = a.names().map(str::to_string).collect(); + let t = std::time::Instant::now(); + let bytes: usize = names.iter().map(|n| a.read(n).unwrap().map_or(0, |b| b.len())).sum(); + let read = t.elapsed(); + let t = std::time::Instant::now(); + let (doc, _) = import_fla_with_fonts(&fla, &fonts).unwrap(); + let import = t.elapsed(); + assert_eq!((doc.library.len(), doc.bitmaps.len()), (400, 24)); + times.push((open, read, bytes, import)); + } + eprintln!("{:.1} MB .fla, {files} files:", fla.len() as f64 / 1e6); + for (open, read, bytes, import) in times { + eprintln!(" open {open:?}, read every entry {read:?} ({:.1} MB, {:.0} MB/s), import {import:?}", bytes as f64 / 1e6, bytes as f64 / 1e6 / read.as_secs_f64()); + } +} From f29a63754906d449e84706c23ff608e4f9298755 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:48:22 -0700 Subject: [PATCH 052/402] test(engine): the corpus opens from .fla files with the same golden frames (M4) --- Cargo.lock | 1 + crates/engine/Cargo.toml | 2 ++ crates/engine/tests/xfl_corpus.rs | 48 +++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 02888be6..83ed3ad2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -283,6 +283,7 @@ dependencies = [ "anicraft-text", "anicraft-xfl", "gif", + "miniz_oxide 0.8.9", "png 0.17.16", "rayon", "serde", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 5fce8c7e..d5329679 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -25,6 +25,8 @@ gif.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). wat = "1.228" diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index 26fa9b41..f24fc0e8 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -6,10 +6,15 @@ //! package's `golden/` folder. Probes then check, by hand-worked colours, what the golden //! should show. `UPDATE_GOLDENS=1` rewrites the goldens (see `golden/mod.rs`). //! +//! Each package also opens as a `.fla` archive, packed in every layout zip writers use, with +//! `file.open`, as the same document and the same golden frames (ADR 0054). +//! //! The report and structure of each package, and its hostile variants, are checked in the xfl //! crate (`crates/xfl/tests/corpus.rs`). mod golden; +#[path = "../../xfl/tests/support/fla.rs"] +mod pack; use anicraft_engine::Session; use anicraft_engine::doc::Document; @@ -204,3 +209,46 @@ fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() { assert!(raw_total > 0 && merged_total > 0, "the corpus has raw shapes, merged: {raw_total} shapes, {merged_total} keyframes"); assert!(failures.is_empty(), "merged raw shapes look different:\n{}", failures.join("\n")); } + +/// Each package as a `.fla` file, in every zip layout (ADR 0054), opens with `file.open` as +/// the same document as its folder and renders the same golden frames. +#[test] +fn every_package_opens_from_a_fla_with_the_same_golden_frames() { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-fla"); + std::fs::create_dir_all(&dir).unwrap(); + let mut failures = Vec::new(); + let mut checked = 0; + for (case, frames) in FRAMES { + let folder = corpus().join(case); + let mut s = Session::default(); + let want = s.execute("file.open", &json!({"path": folder.display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); + // Animate's own pointer file inside the folder opens it too. + let mut x = Session::default(); + x.execute("file.open", &json!({"path": folder.join(format!("{case}.xfl")).display().to_string()})).unwrap_or_else(|e| panic!("{case}.xfl: {e}")); + assert!(x.doc == s.doc, "{case}: the .xfl opens differently from its folder"); + let files = pack::package(&folder); + for (n, v) in pack::VARIANTS.iter().enumerate() { + let path = dir.join(format!("{case}-{n}.fla")); + std::fs::write(&path, pack::pack(&files, v)).unwrap(); + let mut t = Session::default(); + let got = t.execute("file.open", &json!({"path": path.display().to_string()})).unwrap_or_else(|e| panic!("{case}, {}: {e}", v.name)); + assert_eq!(got["report"], want["report"], "{case}, {}", v.name); + assert!(t.doc == s.doc, "{case}, {}: the .fla opens differently from the folder", v.name); + } + // The goldens (imported without fonts, as they were made), rendered from the .fla in + // its most unusual layout. + let fla = pack::pack(&files, &pack::VARIANTS[pack::VARIANTS.len() - 1]); + let (doc, _) = anicraft_xfl::import_fla_with_fonts(&fla, &Fonts::from_faces(Vec::new())).unwrap_or_else(|e| panic!("{case}: {e}")); + for &f in *frames { + let (w, h, rgba) = render(&doc, f); + let golden = corpus().join(case).join("golden").join(format!("frame-{f:03}.png")); + if let Err(e) = golden::compare(&golden, &format!("{case}-fla-frame-{f:03}"), w, h, &rgba, golden::DEFAULT) { + failures.push(e); + } + checked += 1; + } + } + assert!(failures.is_empty(), "{} of {checked} .fla frames differ from their goldens: +{}", failures.len(), failures.join(" +")); +} From 2a8dc349b3fe717fab0137836f1ba9a0c01c53fb Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:49:36 -0700 Subject: [PATCH 053/402] docs: ADR 0054, .fla import numbers, roadmap and changelog (M4) --- ATTRIBUTION.md | 2 +- CHANGELOG.md | 14 ++++ docs/adr/0009-xfl-import.md | 7 ++ .../adr/0035-xfl-corpus-and-golden-renders.md | 4 +- ...-fla-packages-and-a-hardened-zip-reader.md | 83 +++++++++++++++++++ docs/adr/README.md | 1 - docs/performance.md | 18 ++++ docs/roadmap.md | 4 +- 8 files changed, 128 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0054-fla-packages-and-a-hardened-zip-reader.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 6c5e0e90..7cc10202 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -96,7 +96,7 @@ OR Apache-2.0) is noted in the table. | 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. | | 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` | PKWARE APPNOTE.TXT (published ZIP specification); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries; no ZIP64 or encryption. | +| 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). | | 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 7862adc4..705ce679 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +* **`.fla` files open reliably, and hostile ones safely** (ADR 0054, M4). + * The `.fla` reader takes the layouts zip tools write: folder entries, Windows `\` + separators, CP437 and UTF-8 names (and Info-ZIP Unicode names), data descriptors and + ZIP64. Each entry's size and checksum are checked. + * Damaged or hostile archives fail with a sentence that names the problem: entries sharing + bytes, sizes or checksums that lie, compression bombs (a 1024 : 1 ratio cap, 256 MB per + entry, 1 GiB in all), paths with `..`, absolute or drive paths, duplicate names, more than + 32 nested folders, a central directory cut short. Nothing is ever extracted to disk. + * A renamed `.fla` opens (it is recognised by its contents), and a `.fla` saved by Flash CS4 + or earlier says to open it in Animate and save it again. + * Every corpus package, packed nine ways, imports identically to its folder and renders the + same golden frames; a fuzz throws 9,664 hostile archives at the reader. A 54.6 MB `.fla` + imports in 311–328 ms (checksums by slicing by 8: reading every entry 53 ms, was 130 ms). + * **Edit Multiple Frames, complete; onion skin inside symbols** (ADR 0051, M1). * With Edit Multiple Frames on, **Cut, Copy, Paste, Paste in Place and Clear** act on the artwork selected on every keyframe between the markers. Paste in Place puts artwork copied diff --git a/docs/adr/0009-xfl-import.md b/docs/adr/0009-xfl-import.md index a98fef37..2ff17c54 100644 --- a/docs/adr/0009-xfl-import.md +++ b/docs/adr/0009-xfl-import.md @@ -59,3 +59,10 @@ own timelines, nested to any depth. must never panic (`crates/xfl/tests/corpus.rs`), and golden renders of chosen frames by the CPU oracle with hand-worked colour probes (`crates/engine/tests/xfl_corpus.rs`, regenerated with `UPDATE_GOLDENS=1`). A feature the importer learns gets a corpus file in the same change. +* **`.fla` archives** (ADR 0054): every corpus package, packed by an independent in-memory zip + writer in nine layouts (Animate's `mimetype` first, stored, mixed with folder entries, + Windows separators, CP437 and Unicode-path names, data descriptors, ZIP64, all at once), + imports identically to its folder and renders the same goldens; a fuzz of 9,664 hostile + archives built from the corpus never panics, and the zip reader refuses overlapping entries, + lying sizes and checksums, ratio bombs, unsafe and duplicate paths and deep nesting with a + readable error (`crates/xfl/src/zip_tests.rs`, `crates/xfl/tests/fla.rs`). diff --git a/docs/adr/0035-xfl-corpus-and-golden-renders.md b/docs/adr/0035-xfl-corpus-and-golden-renders.md index 24efc3b5..d7712e36 100644 --- a/docs/adr/0035-xfl-corpus-and-golden-renders.md +++ b/docs/adr/0035-xfl-corpus-and-golden-renders.md @@ -95,6 +95,8 @@ hand from the public descriptions of the format. it can share our misreadings of the format. Where we were unsure (the default symbol type, the custom ease and shape-hint forms) this ADR says so, and a file saved by Animate that disagrees should become a corpus fix, not a special case. -* Not in this slice: `.fla` (zip) variants of the corpus, sound and video items, motion tweens +* `.fla` (zip) variants of the corpus are checked since ADR 0054: every package, packed nine + ways, imports identically to its folder and renders the same goldens. +* Not in this slice: sound and video items, motion tweens with property curves, and per-character text styles (all reported, and kept for their own slices). diff --git a/docs/adr/0054-fla-packages-and-a-hardened-zip-reader.md b/docs/adr/0054-fla-packages-and-a-hardened-zip-reader.md new file mode 100644 index 00000000..edf43447 --- /dev/null +++ b/docs/adr/0054-fla-packages-and-a-hardened-zip-reader.md @@ -0,0 +1,83 @@ +# ADR 0054: `.fla` packages: corpus variants and a hardened zip reader + +* Status: accepted (2026-11-11) +* Relates to: ADR 0009 (XFL import, own zip reader), ADR 0035 (the XFL corpus and golden + renders), ADR 0036 (web build: a `.fla` handed over as bytes), roadmap M4 + +## Context + +Artists open `.fla` files: a zip archive of the same XFL tree the corpus (ADR 0035) tests as +folders. The zip reader from ADR 0009 read stored and deflate entries and capped entry sizes, +but nothing tested it against the layouts real zip writers produce (folder entries, `\` +separators, unflagged or CP437 names, data descriptors, ZIP64), and nothing tested it against +an archive made to hurt: entries sharing bytes (the overlapping-file zip bomb), sizes and +checksums that lie, names with `..`, absolute or drive paths, the same name twice, very deep +folders, a central directory cut short. A `.fla` arrives from anywhere (mail, the web build's +file picker), so it is hostile input. + +## Decision + +1. **Read what writers write.** The reader (`crates/xfl/src/zip.rs`, from PKWARE's APPNOTE + 6.3) takes stored and deflate entries; folder entries; `\` read as `/`; empty and `.` path + parts dropped; data descriptors (sizes come from the central directory, which always has + them); **ZIP64** end records and per-entry sizes (cheap to read, written by some tools for + small files too, and refused archives would be a worse answer); names as UTF-8 when flag + bit 11 or the Info-ZIP Unicode path field (0x7075, checked against the name's CRC) says so, + else **CP437** as the format specifies, except that a name that is valid UTF-8 is read as + UTF-8 (many writers store UTF-8 without the flag; ASCII reads the same either way, and CP437 + text that happens to be valid UTF-8 is vanishingly rare). A name flagged UTF-8 that isn't is + an error, not a guess. +2. **Refuse, with a sentence, what no honest writer makes.** Opening checks the whole archive + before any entry is inflated: every offset and length is checked against the bytes it + comes from; each entry's local header and data must end before the central directory, and + **no two entries may share bytes** (sorted spans); a path that would leave the package is + refused (`..`, leading `/` or `\`, a drive in the first part, NUL), as are **duplicate + paths** (after `\` → `/`), paths inside more than **32 folders**, more than **100,000 + entries**, and split archives. Reading an entry refuses encryption and other methods by + name ("LZMA compression"), and checks the result: an entry must inflate to exactly its + stated size (inflation stops at that size) and match its **CRC-32**. +3. **Bombs: a ratio cap, an entry cap and a total budget.** Deflate can't pass about 1032 : 1, + so an entry claiming more than **1024 : 1** (plus 4 KB) is refused before inflating as a + bomb or a damaged size; no entry inflates past **256 MB**; and one archive hands out at + most **1 GiB** over every read, so a document that names one large entry many times can't + multiply it. The `.fla` itself is capped at 1 GiB, as before. +4. **Nothing is extracted.** The reader only answers lookups from the importer, in memory; it + never writes a file, so path checks keep lookups unambiguous and match the folder reader, + which also refuses `..`, empty parts and drives. Safe Rust slicing means no read leaves the + archive's bytes. +5. **Every file form opens the same.** `import_path` takes an XFL folder, the `.xfl` pointer + file inside it (or any file there, such as `DOMDocument.xml`), or a `.fla`, recognised by + its first bytes too, so a renamed archive opens. A `.fla` saved by Flash CS4 or earlier (a + compound binary file) is named in the error, with what to do: open it in Animate and save + it again. `import_fla_with_fonts` joins `import_with_fonts` for tests and hosts. +6. **The corpus in every layout, by an independent writer.** `crates/xfl/tests/support/fla.rs` + packs a package into `.fla` archives in memory, written from the specification separately + from the reader (its own CRC), in nine variants: as Animate writes it (the stored + `mimetype` entry first), stored, mixed (XML deflated, images stored) with folder entries, + Windows separators with unflagged names, CP437 names, Unicode path fields, data + descriptors, ZIP64, and all of these at once. Every package must import **identically** + to its folder (the same `Document`, the same report), from bytes and from disk, and render + the same golden frames (`crates/engine/tests/xfl_corpus.rs`); one package is also checked + with library names outside ASCII in every encoding. +7. **A fuzz built from the corpus.** `hostile_fla_archives_never_panic_and_fail_readably` + sets every central header field of the first entries to edge values, changes random bytes + (in the directory, then anywhere), cuts each archive short, and builds archives with unsafe + names, duplicates, overlaps, lying sizes and checksums, ratio bombs and deep folders: + 9,664 archives per run, none may panic, every failure must be a readable sentence, and the + built attacks must all be refused. +8. **CRC-32 by slicing by 8** (eight table lookups per eight bytes, Kounavis and Berry, 2005): + checking every entry costs little. On a generated 54.6 MB `.fla` (400 symbols, 24 stored + PNGs, 65.8 MB inflated), reading every entry fell from 128–140 ms (byte-wise table) to + 53–54 ms, and the whole import from 388–458 ms to 311–328 ms (`docs/performance.md`). + +## Consequences + +* A damaged or hostile `.fla` fails at once with a sentence that names the entry and the + problem, and never takes the app down or its memory. +* A good archive that some writer lays out in a way we haven't seen fails loudly rather than + importing wrongly; a real file that does should become a new variant in the packer, not a + special case. +* Not in this slice: archives with data before the first entry (self-extracting zips, whose + offsets are shifted), an XFL folder zipped inside a top folder (`name/DOMDocument.xml`), + encrypted archives and other compression methods (all refused with a clear error), and + sound and video items (reported, as before). diff --git a/docs/adr/README.md b/docs/adr/README.md index f70942cf..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 | -| 0054 | m4/fla-packages | `.fla` packages: corpus variants and a hardened zip reader | diff --git a/docs/performance.md b/docs/performance.md index e034b22c..8063616f 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -97,6 +97,24 @@ flushed to disk, renamed). With the default "every minute or 25 changes", even the 262 MB document keeps the worker busy for about 1% of the time, and the UI never waits for it. +**Opening a 50 MB `.fla` (2026-11-11, ADR 0054; release, 32 threads, one used).** A generated +archive (`measure_importing_a_50_mb_fla` in `crates/xfl/tests/fla.rs`: 400 symbols of 600 +edges each, deflated, and 24 noisy 1024 × 512 PNGs, stored; 54.6 MB, 425 files, 65.8 MB +inflated), five runs each: + +```sh +cargo test --release -p anicraft-xfl --test fla -- --ignored --nocapture +``` + +| Step | CRC-32 byte by byte | CRC-32 by slicing by 8 | +|---|---|---| +| Open (end record, central directory, every local header, overlap check) | 0.19–0.25 ms | 0.18–0.24 ms | +| Read and check every entry (inflate, size, CRC) | 128–140 ms (471–516 MB/s) | 53–54 ms (1.22–1.24 GB/s) | +| Whole import (read, XML, edges, library, timeline) | 388–458 ms | **311–328 ms** | + +The checks on every entry (exact size, checksum) now cost about 30 ms of the import; the rest +is parsing and building the document. + ### GPU stage (M3, ADR 0019) `cargo run --release -p anicraft-gpu --example gpu_bench` (2026-11-09, RTX 5090 over Vulkan, diff --git a/docs/roadmap.md b/docs/roadmap.md index f3f0d15c..d173147f 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): 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). 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`. Not yet: dragging items onto the stage, shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, a folder choice in Convert to Symbol, Swap Bitmap. | | 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. | @@ -35,7 +35,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); ~~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); not yet: `.fla` variants of the corpus, sound and video items; ~~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~~ ✅. | | **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. | | **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 ebd29c19ebc6698a96ffd4f07efb85997dc84527 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:54:37 -0700 Subject: [PATCH 054/402] test(shell): a drop on the stage, Enter in the Library and the Convert to Symbol dialog, headless (M2) --- src/convert_symbol.rs | 72 ++++++++++++++++++++++++++++++++------ src/library.rs | 80 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 11 deletions(-) diff --git a/src/convert_symbol.rs b/src/convert_symbol.rs index 08e36225..875826fa 100644 --- a/src/convert_symbol.rs +++ b/src/convert_symbol.rs @@ -131,22 +131,28 @@ pub fn window(app: &mut App, ctx: &egui::Context) { } }); }); - if submit && let Some(d) = app.convert.take() { - let name = d.name.trim(); - let mut params = json!({"kind": kind_key(d.kind), "folder": d.folder.map(|f| f.0)}); - if !name.is_empty() { - params["name"] = json!(name); - } - app.convert_last = Last { folder: d.folder, kind: d.kind }; - if let Some(f) = d.folder { - app.library.expanded.extend(app.s.doc.folder_chain(f)); - } - app.request("modify.convert_to_symbol", params); + if submit { + accept(app); } else if cancel { app.convert = None; } } +/// OK: converts with the dialog's choices and remembers the folder and type for next time. +fn accept(app: &mut App) { + let Some(d) = app.convert.take() else { return }; + let name = d.name.trim(); + let mut params = json!({"kind": kind_key(d.kind), "folder": d.folder.map(|f| f.0)}); + if !name.is_empty() { + params["name"] = json!(name); + } + app.convert_last = Last { folder: d.folder, kind: d.kind }; + if let Some(f) = d.folder { + app.library.expanded.extend(app.s.doc.folder_chain(f)); + } + app.request("modify.convert_to_symbol", params); +} + #[cfg(test)] mod tests { use super::*; @@ -163,4 +169,48 @@ mod tests { assert_eq!(remembered(&s.doc, last), None, "a deleted folder falls back to the top level"); assert_eq!(remembered(&s.doc, Last::default()), None); } + + #[test] + fn ok_converts_into_the_folder_and_the_next_dialog_offers_it_again() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + // Nothing selected: no dialog, the engine says why. + app.run("edit.deselect", json!({})); + open(&mut app); + assert!(app.convert.is_none()); + let f = FolderId(app.run("library.new_folder", json!({"name": "Props"})).unwrap()["folder"].as_u64().unwrap()); + app.run("draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "object": true})); + open(&mut app); + let d = app.convert.as_mut().expect("the dialog opens"); + assert_eq!(d.folder, None, "the top level the first time"); + assert!(d.name.starts_with("Symbol ")); + d.folder = Some(f); + d.kind = SymbolKind::Button; + d.name = " Lamp ".into(); + accept(&mut app); + assert!(app.convert.is_none()); + let sym = app.s.doc.library.iter().find(|s| s.name == "Lamp").expect("converted, the name trimmed"); + assert_eq!(sym.kind, SymbolKind::Button); + assert_eq!(app.s.doc.parent_of(LibraryEntry::Item(anicraft_engine::doc::LibraryItem::Symbol(sym.id))), Some(f)); + assert!(app.library.expanded.contains(&f), "the folder opens in the Library"); + // The next conversion offers Props and Button again; an empty name takes the default. + app.run("draw.rect", json!({"x": 60, "y": 10, "w": 20, "h": 20, "object": true})); + open(&mut app); + let d = app.convert.as_mut().expect("the dialog opens"); + assert_eq!((d.folder, d.kind), (Some(f), SymbolKind::Button)); + d.name = String::new(); + accept(&mut app); + assert_eq!(app.s.doc.library_children(Some(f)).len(), 2); + // The dialog draws (the clash note too) without the document changing. + app.run("draw.rect", json!({"x": 90, "y": 10, "w": 20, "h": 20, "object": true})); + open(&mut app); + if let Some(d) = app.convert.as_mut() { + d.name = "Lamp".into(); + } + let before = app.s.doc.clone(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| window(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.convert.is_some()); + assert_eq!(app.s.doc, before); + } } diff --git a/src/library.rs b/src/library.rs index be45e5ca..bc8660fe 100644 --- a/src/library.rs +++ b/src/library.rs @@ -969,6 +969,86 @@ mod tests { assert_eq!(names(&s, &mut v)[2..], [n(0, "Star"), n(0, "Ball copy")]); } + fn pointer(pos: egui::Pos2, pressed: Option) -> egui::RawInput { + let mut events = vec![egui::Event::PointerMoved(pos)]; + if let Some(pressed) = pressed { + events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1600.0, 940.0))), events, ..Default::default() } + } + + fn app() -> (egui::Context, App) { + let ctx = egui::Context::default(); + let app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + (ctx, app) + } + + fn frame(ctx: &egui::Context, app: &mut App, input: egui::RawInput) { + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + } + + fn instances(app: &App, symbol: u64) -> Vec { + app.s.timeline().layers.iter().filter_map(|l| l.keyframe_at(app.s.frame)).flat_map(|k| &k.elements).filter(|e| matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { symbol: x, .. } if x.0 == symbol)).map(|e| e.transform.apply(anicraft_engine::geom::Vec2::ZERO)).collect() + } + + #[test] + fn dropping_rows_on_the_stage_places_them_at_the_pointer_in_one_step() { + let (ctx, mut app) = app(); + for _ in 0..3 { + frame(&ctx, &mut app, pointer(pos2(5.0, 935.0), None)); + } + let star = app.s.doc.library.iter().find(|x| x.name == "Star").unwrap().id; + let before = instances(&app, star.0).len(); + let steps = app.s.history().undo_len(); + let canvas = app.stage_cache.canvas; + assert!(canvas.width() > 100.0, "the stage was laid out"); + // The press starts outside the stage (as on a Library row), the rows ride along. + frame(&ctx, &mut app, pointer(pos2(5.0, 935.0), Some(true))); + egui::DragAndDrop::set_payload(&ctx, vec![LibraryEntry::Item(LibraryItem::Symbol(star)), LibraryEntry::Folder(FolderId(424_242))]); + let at = canvas.center(); + for _ in 0..2 { + frame(&ctx, &mut app, pointer(at, None)); + } + assert_eq!(instances(&app, star.0).len(), before, "hovering places nothing"); + frame(&ctx, &mut app, pointer(at, Some(false))); + let now = instances(&app, star.0); + assert_eq!(now.len(), before + 1, "letting go places the symbol (folders are left out)"); + assert_eq!(app.s.history().undo_len(), steps + 1, "one undo step"); + assert!(!app.library.keys, "the stage has the keyboard again"); + // Where the pointer was, in stage space. + let size = vec2(app.s.doc.stage.width as f32, app.s.doc.stage.height as f32); + let origin = canvas.center() + app.view.pan - size * app.view.zoom * 0.5; + let want = (at - origin) / app.view.zoom; + let got = now.iter().find(|p| (p.x - want.x).abs() < 1.5 && (p.y - want.y).abs() < 1.5); + assert!(got.is_some(), "{now:?} near {want:?}"); + } + + #[test] + fn enter_places_the_selected_rows_at_the_centre_of_the_view() { + let (ctx, mut app) = app(); + for _ in 0..3 { + frame(&ctx, &mut app, pointer(pos2(5.0, 935.0), None)); + } + let star = app.s.doc.library.iter().find(|x| x.name == "Star").unwrap().id; + let before = instances(&app, star.0).len(); + app.library.sel = vec![LibraryEntry::Item(LibraryItem::Symbol(star)), LibraryEntry::Folder(FolderId(424_242))]; + app.library.keys = true; + let mut input = pointer(pos2(5.0, 935.0), None); + input.events.push(egui::Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + frame(&ctx, &mut app, input); + let now = instances(&app, star.0); + assert_eq!(now.len(), before + 1); + let c = app.view_center_stage(); + assert!(now.iter().any(|p| (p.x - c.x).abs() < 0.01 && (p.y - c.y).abs() < 0.01), "{now:?} at {c:?}"); + // Inside a symbol open for editing, the centre of the view in its space. + app.run("symbol.edit", json!({"symbol": star.0})); + let ball = app.s.doc.library.iter().find(|x| x.name == "Ball").unwrap().id; + place_items(&mut app, &[LibraryItem::Symbol(ball)], None); + let (x, y) = view_centre(&app); + assert!(instances(&app, ball.0).iter().any(|p| (p.x - x).abs() < 0.01 && (p.y - y).abs() < 0.01)); + } + #[test] fn a_search_shows_matches_inside_closed_folders() { let (s, _, _) = session(); From 578fd1454057ee59c418f83c6b5a9070462ee668 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 01:16:56 -0700 Subject: [PATCH 055/402] 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 056/402] 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 057/402] 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 058/402] 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 059/402] 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 060/402] 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 061/402] 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 062/402] 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 063/402] 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 064/402] 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 065/402] 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 066/402] 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 067/402] 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 068/402] 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 069/402] 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 070/402] 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 071/402] 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 072/402] 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 073/402] 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 074/402] 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 075/402] 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 076/402] 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 077/402] 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 078/402] 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 079/402] 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 080/402] 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 081/402] 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 082/402] 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 083/402] 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 084/402] 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 085/402] 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 086/402] 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 087/402] 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 088/402] 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 089/402] 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 090/402] 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 091/402] 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 092/402] 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 093/402] 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 094/402] 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 095/402] 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 096/402] 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 097/402] 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 098/402] 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 099/402] 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 100/402] 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 101/402] 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 102/402] 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 103/402] 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 104/402] 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 105/402] 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 106/402] 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 107/402] 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 108/402] 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 109/402] 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 110/402] 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 111/402] 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 112/402] 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 113/402] 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 114/402] 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 115/402] 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 116/402] 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 117/402] 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 118/402] 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 119/402] 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 120/402] 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 121/402] 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 122/402] 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 123/402] =?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 124/402] 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 125/402] 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 126/402] 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 127/402] 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 128/402] 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 129/402] 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 130/402] 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 131/402] 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 132/402] 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 133/402] 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 134/402] 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 135/402] 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 136/402] 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 137/402] 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 `` / `