Merge main into fix/text-bidi
No files matched your search
@@ -1,5 +1,8 @@
|
||||
# build output
|
||||
/target/
|
||||
# sample plug-ins built by examples/plugins/build.sh (sources are committed, binaries never)
|
||||
/examples/plugins/dist/
|
||||
/examples/plugins/target/
|
||||
|
||||
# generated screenshots and exports (regenerate with --screenshot / anicraft-cli)
|
||||
/shots/
|
||||
@@ -12,3 +15,6 @@
|
||||
*.swp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# parallel milestone worktrees (AGENTS.md › Milestone tracks)
|
||||
/.worktrees/
|
||||
@@ -9,6 +9,7 @@ is written **AniCraft**; machine names are lowercase (`anicraft-*`). Read `docs/
|
||||
```text
|
||||
crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing
|
||||
crates/xml L0 Bounded XML element reader shared by the importers (XFL, SVG)
|
||||
crates/plugins L0 Sandboxed WebAssembly plug-ins: wasmi host, ABI v1, limits, registry (ADR 0017)
|
||||
crates/doc L1 Document model, easing, timeline evaluation, sample scene
|
||||
crates/text L1 Fonts on this computer, shaping and line layout into outlines (ADR 0012)
|
||||
crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG)
|
||||
@@ -91,6 +92,18 @@ a new crate needs a row here and in its `LAYERS` table.
|
||||
Run `git config core.hooksPath scripts/git-hooks` once per clone.
|
||||
* Branches marked hidden in your local git config (`git config --add anicraft.hidden <branch>`)
|
||||
never leave the machine: `pre-push` refuses them and anything built on them.
|
||||
* **Milestone tracks.** Milestones that don't depend on unfinished work run in parallel, one
|
||||
agent per track (`docs/roadmap.md` › Parallel tracks). Each track works in its own git
|
||||
worktree under `.worktrees/<track>` (git-ignored), on branches named `m<N>/<topic>`, and
|
||||
every commit subject and PR title ends with its milestone, e.g.
|
||||
`feat(audio): audio layers with waveforms (M5)`. Worktrees share the one `target/` through
|
||||
`CARGO_TARGET_DIR`. Before opening or updating a PR, rebase on `origin/main` and keep shared
|
||||
files (CHANGELOG, roadmap, Cargo.lock, the workspace map) conflict-free. A track never merges
|
||||
its own PR: the lead reviews it (principal engineer and senior designer) and merges it when
|
||||
CI is green.
|
||||
* **Outside pull requests** that match a roadmap task are reviewed and their good ideas
|
||||
considered. The work stays first-party: a track waits on an outside PR only if it is
|
||||
complete and fits our architecture and flow.
|
||||
* Commit in small, green steps (build + tests pass), with conventional messages:
|
||||
`feat(render): …`, `fix(engine): …`, `docs: …`, `perf: …`, `test: …`. Record measured
|
||||
numbers in `perf:` commit bodies.
|
||||
|
||||
@@ -21,6 +21,8 @@ shaders or SDK code).
|
||||
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
|
||||
| `assets/icons/anicraft-*.svg` (10 files: align, distribute, mask and masked layer) | Align panel and layer-type icons | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (32 files: tools, transport, layer toggles, folders, guide, image, text, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set | 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)) |
|
||||
| `docs/images/` (screenshots and `sample-animation.gif`) | README | AniCraft contributors | Original work: AniCraft's own screenshots (`--screenshot`) and sample animation (`anicraft-cli gif`) | MIT OR Apache-2.0 |
|
||||
| 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 |
|
||||
| Colour theme | UI | AniCraft contributors | Original work (`src/theme.rs`) | MIT OR Apache-2.0 |
|
||||
@@ -45,8 +47,8 @@ here.
|
||||
| Inter Regular | UI prose (primary) | The Inter Project Authors (Rasmus Andersson) | SIL OFL 1.1, shipped as `OFL-Inter.txt` |
|
||||
| JetBrains Mono Regular | UI data: timeline, readouts, values, shortcuts (primary) | The JetBrains Mono Project Authors | SIL OFL 1.1, shipped as `OFL-JetBrainsMono.txt` |
|
||||
|
||||
No image, icon, sound or font *files* are committed. Everything above is either embedded by a
|
||||
dependency crate or generated by our code.
|
||||
No sound or font *files* are committed, and every committed image is listed above. Everything
|
||||
else is either embedded by a dependency crate or generated by our code.
|
||||
|
||||
## Algorithms and published techniques
|
||||
|
||||
@@ -74,6 +76,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| 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") | `crates/geom/src/fit.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. |
|
||||
| WebAssembly plug-in host (module validation, limits, fuel, resumable host calls) | `crates/plugins` | W3C WebAssembly Core Specification 1.0 / 2.0 (W3C Royalty-Free Patent Policy); the `wasmi` interpreter (MIT OR Apache-2.0) | Host model ported from PhotoCraft's filter plug-ins (same project family and licence) and extended with the AniCraft request ABI (ADR 0017). |
|
||||
| De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | |
|
||||
|
||||
## Rust dependencies
|
||||
|
||||
@@ -2,6 +2,58 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Plug-ins** (Commands › Plug-ins; ADR 0017, `docs/plugins.md`). Plug-ins are WebAssembly
|
||||
files that add commands: generators such as the sample **Star Field**, and selection effects
|
||||
such as the sample **Jitter Selection**. A plug-in with settings opens a dialog with a live
|
||||
preview on the stage; OK keeps the result as one undo step named after the plug-in. Install
|
||||
with Commands › Install Plug-in…, see and remove them in Commands › Manage Plug-ins…; they
|
||||
load from the `plugins` folder in AniCraft's settings folder (or `ANICRAFT_PLUGINS`), and the
|
||||
command palette finds them too. Plug-ins run sandboxed: they change the open document through
|
||||
AniCraft's own commands, never files, the clipboard or the undo history, and a runaway or
|
||||
broken plug-in stops with a message and leaves the document as it was. Headless:
|
||||
`plugin.install/list/run/remove/reload`, `anicraft-cli --plugins <folder>`. The samples and a
|
||||
small Rust SDK are in `examples/plugins`.
|
||||
* **Motion tweens and the Motion Editor** (ADR 0016). Insert › Create Motion Tween (also in
|
||||
the timeline header, the right-click menu and Properties) makes a span animate its object
|
||||
property by property: X, Y, scale, rotation, skew, alpha and tint each have their own curve
|
||||
with property keyframes anywhere in the span. Move, scale, rotate or fade the object at a
|
||||
later frame and it keys those properties there (no timeline keyframes); F6 inside the span
|
||||
keys every property. The Motion Editor (a tab beside the Timeline, Window › Motion Editor, or
|
||||
double-click a motion span) lists the properties with their values at the playhead (drag one
|
||||
to key it) and draws the selected property's curve: drag keys up and down, drag a segment's
|
||||
two Bézier handles to shape its ease (overshoot allowed), pick an ease preset, click to move
|
||||
the playhead, double-click to add a key. Each drag is one undo step. Motion spans are sky blue
|
||||
on the timeline with a diamond at each property keyframe. Several objects become one graphic
|
||||
symbol first, and a one-frame span grows to a second, as in Animate. Every export sees the
|
||||
motion. Headless: `timeline.create_motion_tween`, `motion.set_key`, `motion.remove_key`,
|
||||
`motion.set_ease`, `motion.info`. Not yet: motion paths on the stage, moving keys in time,
|
||||
importing motion tweens from Animate files.
|
||||
* **Crash recovery.** AniCraft keeps a recovery copy of unsaved work in the background (every
|
||||
minute, or after 25 changes, whichever comes first; Preferences › Files › Autosave changes
|
||||
both or turns it off). If AniCraft closes unexpectedly, the next start shows what was left
|
||||
behind: **Restore** opens it as unsaved work, and Save puts it back where it was (or asks for
|
||||
a name if that file was saved after the copy); **Discard** deletes it after a second click;
|
||||
**Later** keeps it for File › Recover Autosaved Documents…. Copies live in the settings
|
||||
folder, are written atomically, never replace your own files, and go away when you save or
|
||||
close normally. Drawing never waits for them: the 65 MB stress document is copied in 0.18 s
|
||||
on a background thread. Headless: `file.recovery_list`, `file.recover`,
|
||||
`file.discard_recovery`, `file.autosave`.
|
||||
* **App icon**: an engraved rabbit on AniCraft yellow, on the same rounded tile as the other
|
||||
Crafting Apps. It shows on the window, the macOS Dock (on Apple's icon grid), the Windows
|
||||
taskbar and `anicraft.exe`, and in Help › About. Files and how to regenerate them are in
|
||||
`assets/app-icon/`.
|
||||
* **README**: screenshots of the app and the sample animation, and a quick start.
|
||||
* **Text in Animate documents.** Opening a `.fla` or XFL now brings its text across as text
|
||||
you can edit: titles, captions and paragraphs keep their font, size, colour, bold and
|
||||
italic, alignment, letter and line spacing, position, and fixed width (wrapping) or
|
||||
auto-size. A field whose lines use different styles (a big title over smaller lines)
|
||||
becomes one text block per style, stacked as in Animate; a line that mixes styles takes
|
||||
the style of most of its characters, and the report counts it. Fonts that aren't on this
|
||||
computer fall back to the default, and the status bar names them ("Fonts not on this
|
||||
computer, drawn in Arial: Futura."). Dynamic and input text come across as static text and
|
||||
are reported. The import report now also shows in the status bar when a document is
|
||||
opened from the command line (ADR 0014).
|
||||
|
||||
* **ActionScript on the roadmap** (ADR 0013, low priority, M6): first keep the scripts in
|
||||
imported Animate files, with an Actions panel, then play the common timeline controls (stop,
|
||||
play, go to a frame or label, button clicks) in Test Movie and HTML canvas export. Until
|
||||
|
||||
@@ -188,6 +188,7 @@ dependencies = [
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"winresource",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -218,6 +219,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anicraft-doc",
|
||||
"anicraft-geom",
|
||||
"anicraft-plugins",
|
||||
"anicraft-render",
|
||||
"anicraft-svg",
|
||||
"anicraft-text",
|
||||
@@ -228,6 +230,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"wat",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -238,6 +241,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-plugins"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"wasmi",
|
||||
"wat",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-render"
|
||||
version = "0.1.0"
|
||||
@@ -277,6 +291,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anicraft-doc",
|
||||
"anicraft-geom",
|
||||
"anicraft-text",
|
||||
"anicraft-xml",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png 0.17.16",
|
||||
@@ -1176,6 +1191,12 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
@@ -1347,7 +1368,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash",
|
||||
"foldhash 0.2.0",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
@@ -1481,6 +1502,15 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
|
||||
dependencies = [
|
||||
"foldhash 0.1.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.16.1"
|
||||
@@ -1489,7 +1519,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
||||
dependencies = [
|
||||
"allocator-api2",
|
||||
"equivalent",
|
||||
"foldhash",
|
||||
"foldhash 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1498,7 +1528,7 @@ version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
"foldhash 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1660,6 +1690,12 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -2782,6 +2818,15 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -2929,6 +2974,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
|
||||
[[package]]
|
||||
name = "spirv"
|
||||
version = "0.4.0+sdk-1.4.341.0"
|
||||
@@ -2944,6 +2995,16 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "string-interner"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0"
|
||||
dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
@@ -3058,10 +3119,25 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
name = "toml"
|
||||
version = "1.2.1+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
|
||||
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"serde_core",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
@@ -3087,6 +3163,12 @@ dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.2.0+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
@@ -3297,6 +3379,99 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser 0.263.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27"
|
||||
dependencies = [
|
||||
"spin",
|
||||
"wasmi_collections",
|
||||
"wasmi_core",
|
||||
"wasmi_ir",
|
||||
"wasmparser 0.228.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_collections"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557"
|
||||
dependencies = [
|
||||
"string-interner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_core"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_ir"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6"
|
||||
dependencies = [
|
||||
"wasmi_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.228.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"indexmap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wast"
|
||||
version = "263.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"leb128fmt",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
"wasm-encoder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wat"
|
||||
version = "1.263.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7"
|
||||
dependencies = [
|
||||
"wast",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-backend"
|
||||
version = "0.3.17"
|
||||
@@ -3911,6 +4086,16 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winresource"
|
||||
version = "0.1.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
|
||||
dependencies = [
|
||||
"toml",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
|
||||
@@ -23,6 +23,7 @@ anicraft-xfl = { path = "crates/xfl" }
|
||||
anicraft-xml = { path = "crates/xml" }
|
||||
anicraft-svg = { path = "crates/svg" }
|
||||
anicraft-text = { path = "crates/text" }
|
||||
anicraft-plugins = { path = "crates/plugins" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
@@ -76,6 +77,10 @@ serde.workspace = true
|
||||
fontdb.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
# Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets.
|
||||
winresource = "0.1"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png" width="128" height="128" alt="AniCraft icon: an engraved rabbit on a yellow tile">
|
||||
</p>
|
||||
|
||||
<h1 align="center">AniCraft</h1>
|
||||
|
||||
<p align="center">
|
||||
@@ -16,16 +21,15 @@
|
||||
<p align="center">
|
||||
A native 2D vector animation editor with timeline, layers, keyframes, classic and shape tweens,
|
||||
onion skinning, and an egui stage. It runs natively on macOS, Windows, Linux and FreeBSD,
|
||||
and in the browser via WebAssembly.<br>
|
||||
<i>By the ArtCraft team.</i>
|
||||
and in the browser via WebAssembly. Built by the ArtCraft team.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="100% Rust" src="https://img.shields.io/badge/100%25-Rust-b7410e?style=flat-square&logo=rust">
|
||||
<img alt="egui" src="https://img.shields.io/badge/UI-egui-14a9c4?style=flat-square">
|
||||
<img alt="macOS · Windows · Linux · FreeBSD · Web" src="https://img.shields.io/badge/macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20Web-native-2f7bf5?style=flat-square">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-3a3a3a?style=flat-square">
|
||||
<img alt="Status: early alpha" src="https://img.shields.io/badge/status-early%20alpha-d69e2e?style=flat-square">
|
||||
<img alt="Status: early alpha" src="https://img.shields.io/badge/status-early%20alpha-dac604?style=flat-square">
|
||||
<img alt="Written in pure Rust" src="https://img.shields.io/badge/pure-Rust-b7410e?style=flat-square&logo=rust&logoColor=white">
|
||||
<img alt="Runs on macOS, Windows, Linux, FreeBSD and the web" src="https://img.shields.io/badge/runs%20on-macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20Web-555555?style=flat-square">
|
||||
<img alt="MCP server for agents" src="https://img.shields.io/badge/agents-MCP%20server-555555?style=flat-square">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-555555?style=flat-square">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -40,117 +44,157 @@
|
||||
|
||||
<br>
|
||||
|
||||
> [!NOTE]
|
||||
> **ArtCraft is a community of artists from all walks of life.** Painters, photographers,
|
||||
> filmmakers, illustrators, designers, animators, hobbyists, and people who picked up a pencil
|
||||
> last week. If you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
|
||||
|
||||
<p align="center">
|
||||
<a href="#why-anicraft">Why AniCraft</a> ·
|
||||
<a href="#features">Features</a> ·
|
||||
<a href="#build-and-run">Build and run</a> ·
|
||||
<a href="#headless--agents">Headless & Agents</a> ·
|
||||
<a href="#architecture">Architecture</a> ·
|
||||
<a href="#status">Status</a> ·
|
||||
<a href="#downloads">Downloads</a> ·
|
||||
<a href="#the-crafting-apps">Crafting Apps</a> ·
|
||||
<a href="https://discord.gg/artcraft">Discord</a>
|
||||
<img src="docs/images/shot-1-stage.png" alt="AniCraft with the sample animation open: the stage shows a ball, a star and a sun over hills at dusk; the timeline below has five layers with violet classic-tween spans, and the Properties panel shows the selected tween's easing curve" width="100%">
|
||||
<br><sub><b>The sample animation</b>: stage, tools, timeline with classic tweens, and Properties with the easing curve · <code>cargo run</code></sub>
|
||||
</p>
|
||||
|
||||
<br>
|
||||
> [!NOTE]
|
||||
> **ArtCraft is a community of artists from all walks of life.** Painters, animators, filmmakers,
|
||||
> illustrators, game makers — if you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
|
||||
|
||||
<p align="center">
|
||||
<a href="#a-look-around">A look around</a> ·
|
||||
<a href="#made-in-anicraft">Made in AniCraft</a> ·
|
||||
<a href="#why-anicraft">Why AniCraft</a> ·
|
||||
<a href="#features">Features</a> ·
|
||||
<a href="#quick-start">Quick start</a> ·
|
||||
<a href="#status">Status</a> ·
|
||||
<a href="#downloads">Downloads</a> ·
|
||||
<a href="#the-crafting-apps">The Crafting Apps</a> ·
|
||||
<a href="#license-and-credits">License</a>
|
||||
</p>
|
||||
|
||||
## A look around
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="25%" valign="top">
|
||||
<h3>🎛️ Familiar by design</h3>
|
||||
Stage, tools, timeline, layers, keyframes, properties and library are where your hands expect them. If you know Adobe Animate or Flash, you already know AniCraft.
|
||||
</td>
|
||||
<td width="25%" valign="top">
|
||||
<h3>⚡ Native and fast</h3>
|
||||
A pure Rust engine with a deterministic analytic anti-aliasing CPU oracle renderer, GPU-ready via wgpu / egui, and rayon row parallelism. No Electron, no webview, no waiting.
|
||||
</td>
|
||||
<td width="25%" valign="top">
|
||||
<h3>🎞️ Vector tweens</h3>
|
||||
Classic tweens with easing presets and shape tweens with arbitrary contour morphing (<code>geom::morph</code>). The document is plain data, and the picture at a frame is a pure function <code>evaluate(doc, frame)</code>.
|
||||
</td>
|
||||
<td width="25%" valign="top">
|
||||
<h3>🤖 Headless first</h3>
|
||||
Every action is an engine command. Drive the exact same engine from the UI, the CLI or the JSON-lines agent channel.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img src="docs/images/shot-2-subselection.png" alt="The Subselection tool showing anchor points and Bézier handles on a blue shape, next to a wavy line drawn with the Pencil; the Properties panel shows the shape's position, scale, fill and stroke" width="100%">
|
||||
<p align="center"><sub><b>Subselection, Pen and Pencil</b>: real Bézier anchors and handles, curve-fitted freehand lines</sub></p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<img src="docs/images/shot-3-frames.png" alt="A block of frames selected across three layers in the timeline, with the ball squashed mid-tween on the stage" width="100%">
|
||||
<p align="center"><sub><b>Timeline</b>: frame ranges across layers, keyframes you drag, classic and shape tweens</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img src="docs/images/shot-4-transform.png" alt="Free Transform on the ball with corner and edge handles; the Properties panel shows the symbol instance's position, scale, rotation, alpha and looping" width="100%">
|
||||
<p align="center"><sub><b>Free Transform and symbols</b>: scale, rotate and move instances with nested timelines</sub></p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<img src="docs/images/shot-5-palette.png" alt="The command palette open over the stage, searching for key and listing the keyframe commands with their shortcuts" width="100%">
|
||||
<p align="center"><sub><b>Command palette</b>: every engine command, one search away (<code>Ctrl+K</code>)</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img src="docs/images/shot-6-shortcuts.png" alt="The Keyboard Shortcuts editor listing essentials and tools with their keys, a filter box and reset buttons" width="100%">
|
||||
<p align="center"><sub><b>Shortcut editor</b>: rebind, add or clear the key for any command or tool (<code>F1</code>)</sub></p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<img src="docs/images/shot-7-preferences.png" alt="The Preferences window with interface and data fonts, interface scale, stage rendering mode, timeline, file dialog and safety settings" width="100%">
|
||||
<p align="center"><sub><b>Preferences</b>: fonts, interface scale, stage rendering and confirmations</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br>
|
||||
## Made in AniCraft
|
||||
|
||||
The sample animation, exported as an animated GIF by AniCraft's own renderer from the command line
|
||||
(`anicraft-cli gif --sample --out sample.gif --scale 0.5`).
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/sample-animation.gif" alt="The sample animation: a ball bounces and squashes across hills at dusk while a star spins and the sun pulses" width="640">
|
||||
<br><sub><b>Sample animation</b>: classic tweens with easing, symbols with their own timelines, 48 frames at 24 fps</sub>
|
||||
</p>
|
||||
|
||||
## Why AniCraft
|
||||
|
||||
AniCraft is a clean-room, native 2D vector animation studio designed for animators, motion designers,
|
||||
and game developers. Built from scratch in pure Rust, it delivers a modern, lightweight, high-performance
|
||||
alternative to Adobe Animate with zero runtime bloat:
|
||||
|
||||
* **Pure Rust & memory safe**: No webviews, no Electron, and no unsafe code (`unsafe_code = "forbid"`).
|
||||
* **Deterministic CPU oracle renderer**: Analytic anti-aliasing via signed-area coverage accumulation, non-zero and even-odd fill rules, linear and radial gradients, round-join strokes, and multi-threaded band rendering.
|
||||
* **Non-destructive & live**: Edits render live in the same frame. Layered architecture with structural sharing (`Arc`) keeps undo and history instant and memory-proportional.
|
||||
* **Interchange ready**: Open Adobe Animate documents (`.fla`, `.xfl`, XFL folders), import SVG drawings straight to the stage, export PNG frames and sequences, animated GIFs with palette quantization, and SVG vector frames.
|
||||
- **Familiar.** Stage, tools, timeline, layers, keyframes, Properties and Library are where your hands
|
||||
expect them. If you know Adobe Animate or Flash, you already know AniCraft.
|
||||
- **Fast.** A pure Rust engine with a deterministic, analytic anti-aliasing CPU renderer, band-parallel
|
||||
rendering, a tiled stage and a background render worker. No Electron, no webview, no waiting.
|
||||
- **Robust.** No `unsafe` code (`unsafe_code = "forbid"`), no panics on input, every command fuzzed, and
|
||||
undo with structural sharing (`Arc`), so history stays instant and memory-proportional.
|
||||
- **Time is a function.** The document is plain data, and the picture at a frame is a pure function,
|
||||
`evaluate(doc, frame)`. Classic tweens with easing presets and shape tweens with contour morphing.
|
||||
- **Open.** A documented native format (`.anicraft`, JSON). Opens Adobe Animate documents (`.fla`,
|
||||
`.xfl`, XFL folders), imports SVG to the stage, and exports PNG frames and sequences, animated GIF,
|
||||
SVG frames, sprite sheets, Lottie, and WebM/MP4 through your own ffmpeg.
|
||||
- **Agent-native.** Every action is an engine command. Drive the same engine from the UI, the CLI, a
|
||||
JSON-lines channel or the **MCP server**, so Claude and other agents can draw, animate and export.
|
||||
|
||||
## Features
|
||||
|
||||
### Stage and Drawing Tools
|
||||
* **Selection & Subselection**: Select, move, nudge with arrow keys, anchor and Bézier handle editing on paths (`Subselection (A)`), add and delete points.
|
||||
* **Vector Drawing**: Pen (`P`) with smooth handles and corner conversion, Pencil (`Shift+Y`) with Schneider curve fitting and smoothing, Rectangle (with corner radii), Oval, PolyStar, and Line tools.
|
||||
* **Free Transform (`Q`)**: Interactive scaling, corner/edge handles with proportional Shift and centre Alt modifiers, and rotation with 15° snapping.
|
||||
* **Fills and Strokes**: Paint Bucket (`K`) with smart gap closure detection, Ink Bottle (`S`), solid colors, linear/radial gradients, and stroke styling.
|
||||
* **Arrangement & Alignment**: Align left/center/right/top/middle/bottom (with stage alignment support), distribute, rotate 90° CW/CCW, and horizontal/vertical flipping.
|
||||
### Stage and drawing tools
|
||||
* **Selection & Subselection**: select, move, nudge with arrow keys, anchor and Bézier handle editing on paths (`Subselection (A)`), add and delete points.
|
||||
* **Vector drawing**: Pen (`P`) with smooth handles and corner conversion, Pencil (`Shift+Y`) with Schneider curve fitting and smoothing, Rectangle (with corner radii), Oval, PolyStar, Line and Text (`T`).
|
||||
* **Free Transform (`Q`)**: interactive scaling, corner/edge handles with proportional Shift and centre Alt modifiers, and rotation with 15° snapping.
|
||||
* **Fills and strokes**: Paint Bucket (`K`) with gap closing, Ink Bottle (`S`), solid colours, linear/radial gradients, bitmap fills and stroke styling.
|
||||
* **Arrangement & alignment**: align left/center/right/top/middle/bottom (with stage alignment), distribute, rotate 90° CW/CCW, and horizontal/vertical flipping.
|
||||
|
||||
### Timeline & Animation
|
||||
* **Layers & Organization**: Normal layers, guide layers, and mask layers (stencil grouping where masked layers clip cleanly under the mask).
|
||||
* **Frame Management**: Keyframes (`F6`), blank keyframes (`F7`), frame insertion (`F5`), frame span dragging, multi-frame selection across layers, and cut/copy/paste frames.
|
||||
* **Classic & Shape Tweens**: Classic tweens with 8 easing presets and custom ease curves; shape tweens morphing between arbitrary vector contours.
|
||||
* **Onion Skinning**: Visual range before and after the playhead for precise in-betweening.
|
||||
* **Symbols & Instances**: Graphic symbols with nested timelines, independent loop modes (Loop, Play Once, Single Frame), and first-frame offsets.
|
||||
### Timeline and animation
|
||||
* **Layers & organization**: normal, guide, motion-guide and mask layers, and nestable layer folders.
|
||||
* **Frame management**: keyframes (`F6`), blank keyframes (`F7`), frame insertion (`F5`), span dragging, multi-frame selection across layers, and cut/copy/paste frames.
|
||||
* **Classic & shape tweens**: classic tweens with 8 easing presets and custom ease curves; shape tweens morphing between arbitrary vector contours.
|
||||
* **Onion skinning**: a visual range before and after the playhead for in-betweening.
|
||||
* **Symbols & instances**: graphic symbols with nested timelines and loop modes (Loop, Play Once, Single Frame), movie clips, filters and blend modes, and scenes.
|
||||
|
||||
### Workflow & Customization
|
||||
* **Shortcut Editor (`F1`)**: Interactive keymap editor to customize, rebind, or clear any tool or command shortcut.
|
||||
* **Command Palette (`Ctrl+K`)**: Quick fuzzy search and execution of all engine commands.
|
||||
* **Safety & Recovery**: Tiered confirmation for destructive actions, unsaved changes guards, and non-overwriting untitled imports.
|
||||
### Workflow and customization
|
||||
* **Shortcut editor (`F1`)**: interactive keymap editor to customize, rebind or clear any tool or command shortcut.
|
||||
* **Command palette (`Ctrl+K`)**: quick fuzzy search and execution of all engine commands.
|
||||
* **Safety & recovery**: tiered confirmation for destructive actions, unsaved-changes guards, crash-recovery autosave, and non-overwriting untitled imports.
|
||||
|
||||
## Build and run
|
||||
## Quick start
|
||||
|
||||
```sh
|
||||
cargo build # whole workspace
|
||||
cargo run # desktop app with the sample animation
|
||||
cargo run -- --screenshot shots/now.png # draw ~120 frames, save the window, exit
|
||||
cargo test # all crates
|
||||
git clone https://github.com/storytold/anicraft
|
||||
cd anicraft
|
||||
|
||||
cargo run --release # desktop app with the sample animation
|
||||
cargo run --release -- --screenshot shots/now.png # draw ~120 frames, save the window, exit
|
||||
cargo run --release -p anicraft-cli -- info --sample
|
||||
cargo run --release -p anicraft-cli -- render --sample --frame 12 --out frame12.png
|
||||
cargo run --release -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5
|
||||
cargo run --release -p anicraft-cli -- gif --sample --out animation.gif
|
||||
cargo run --release -p anicraft-cli -- commands # the command registry as JSON
|
||||
cargo run --release -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft
|
||||
cargo run --release -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout
|
||||
cargo test # all crates
|
||||
```
|
||||
|
||||
## Headless / agents
|
||||
The interface typefaces (Inter and JetBrains Mono) come from [storytold/craft-fonts](https://github.com/storytold/craft-fonts),
|
||||
an optional build input: `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run --release` (an absolute path). Without it, AniCraft
|
||||
uses egui's built-in fonts. See [`docs/development.md`](docs/development.md).
|
||||
|
||||
AniCraft is headless first: every action in the UI is an engine command, accessible through the CLI or over JSON-lines.
|
||||
The `serve` protocol takes one JSON request per line, `{"id": 1, "cmd": "timeline.insert_keyframe", "params": {"frame": 10}}`,
|
||||
and answers with its status, `{"id": 1, "ok": true, "result": {}, "revision": 7, "frame": 0}`. Send `{"cmd": "quit"}` to exit.
|
||||
|
||||
### Use it from Claude Code and other agents
|
||||
|
||||
Register the MCP server with Claude Code:
|
||||
|
||||
```sh
|
||||
cargo run -p anicraft-cli -- info --sample
|
||||
cargo run -p anicraft-cli -- render --sample --frame 12 --out frame12.png
|
||||
cargo run -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5
|
||||
cargo run -p anicraft-cli -- gif --sample --out animation.gif --fps 24
|
||||
cargo run -p anicraft-cli -- commands # the registry as JSON
|
||||
cargo run -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft
|
||||
cargo run -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout
|
||||
cargo run -p anicraft-cli -- mcp --sample # MCP server for AI assistants (docs/mcp.md)
|
||||
claude mcp add anicraft -- /path/to/anicraft-cli mcp
|
||||
```
|
||||
|
||||
The `serve` protocol accepts one JSON request per line:
|
||||
```json
|
||||
{"id": 1, "cmd": "timeline.insert_keyframe", "params": {"frame": 10}}
|
||||
```
|
||||
And returns structured status:
|
||||
```json
|
||||
{"id": 1, "ok": true, "result": {}, "revision": 7, "frame": 0}
|
||||
```
|
||||
Send `{"cmd": "quit"}` to exit.
|
||||
The details, including the server entry for other MCP clients, are in [`docs/mcp.md`](docs/mcp.md).
|
||||
|
||||
## Architecture
|
||||
## Status
|
||||
|
||||
The codebase enforces strict downward-only layering:
|
||||
> [!IMPORTANT]
|
||||
> **Early alpha: not yet for production animation work.** The core document model, vector renderer,
|
||||
> egui shell, classic and shape tweens, and the first XFL and SVG imports work; much is still to come.
|
||||
|
||||
[**docs/roadmap.md**](docs/roadmap.md) has the honest status by dimension, milestones M0–M8 and what's next.
|
||||
|
||||
**What's missing:** motion tweens and the Motion Editor, shape hints, audio layers, ActionScript (frame scripts are counted
|
||||
on import but not kept yet, ADR 0013), motion tweens from XFL, a GPU renderer, and macOS and Linux CI runners
|
||||
(AniCraft is verified on Windows so far).
|
||||
|
||||
**Workspace:** strict downward-only layering, checked by `cargo test`:
|
||||
|
||||
```text
|
||||
crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing
|
||||
@@ -165,28 +209,19 @@ crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/s
|
||||
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
|
||||
```
|
||||
|
||||
No code below `src/` depends on egui, eframe, or windowing libraries.
|
||||
No code below `src/` depends on egui, eframe or windowing libraries.
|
||||
|
||||
### Documents
|
||||
* [`docs/requirements.md`](docs/requirements.md): Scope, functional requirements, and technology choices
|
||||
* [`docs/architecture.md`](docs/architecture.md): Philosophy, crate map, document model, renderer, and engine
|
||||
* [`docs/roadmap.md`](docs/roadmap.md): Milestones M0–M8 and current progress
|
||||
* [`docs/product-principles.md`](docs/product-principles.md): Design and user experience principles
|
||||
* [`docs/development.md`](docs/development.md): Development setup, testing, and build hygiene
|
||||
* [`AGENTS.md`](AGENTS.md): Guide for contributors and AI agents
|
||||
|
||||
## Status
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Status: Early Alpha (Not yet for public consumption).**
|
||||
> AniCraft is under active early development. The core document model, vector rendering oracle,
|
||||
> egui shell, classic and shape tweens, and initial XFL/SVG imports are functional, but it is not yet
|
||||
> ready for production animation work. See [`docs/roadmap.md`](docs/roadmap.md) for milestones M0–M8
|
||||
> and honest progress.
|
||||
Agent and contributor rules (clean room, the asset policy, no panics in shipped code) are in [`AGENTS.md`](AGENTS.md).
|
||||
[`docs/requirements.md`](docs/requirements.md) has the scope, [`docs/architecture.md`](docs/architecture.md) the design,
|
||||
[`docs/product-principles.md`](docs/product-principles.md) the design and user experience principles, and
|
||||
[`docs/development.md`](docs/development.md) the setup, testing and build hygiene. Every bundled asset is listed
|
||||
with its licence in [`ATTRIBUTION.md`](ATTRIBUTION.md).
|
||||
|
||||
## Downloads
|
||||
|
||||
On GitHub, the [latest release](https://github.com/storytold/anicraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/anicraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
**New to AniCraft?** Download it from the [AniCraft page on getartcraft.com](https://getartcraft.com/apps/anicraft). That's the easiest way to install it.
|
||||
|
||||
**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/anicraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/anicraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
|
||||
### Windows
|
||||
|
||||
@@ -244,8 +279,16 @@ stand on its own.
|
||||
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/cadcraft-64.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design and drafting | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
|
||||
| <img src="docs/brand/artcraft-mark.svg" alt="" width="32" height="32"> | **AniCraft** | **2D vector animation studio · you are here** | [GitHub](https://github.com/storytold/anicraft) | [Website](https://getartcraft.com/apps/anicraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
|
||||
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
|
||||
| <img src="assets/app-icon/hicolor/64x64/apps/ai.storyteller.anicraft.png" alt="" width="32" height="32"> | **AniCraft** | **2D vector animation · you are here** | [GitHub](https://github.com/storytold/anicraft) | [Website](https://getartcraft.com/apps/anicraft) |
|
||||
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
|
||||
|
||||
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
|
||||
|
||||
@@ -271,7 +314,9 @@ And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video stud
|
||||
<a href="https://getartcraft.com/apps/anicraft">AniCraft</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
## Star history
|
||||
|
||||
[](https://www.star-history.com/?repos=storytold%2Fanicraft&type=date&legend=top-left)
|
||||
|
||||
## License and credits
|
||||
|
||||
@@ -281,6 +326,9 @@ Copyright (c) 2026 ArtCraft Team and the AniCraft contributors. Required notices
|
||||
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
|
||||
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
|
||||
|
||||
The app icon (an engraved rabbit on AniCraft yellow, `#dac604`) is the owner's original artwork; its
|
||||
palette and files are in [`assets/app-icon/`](assets/app-icon/README.md).
|
||||
|
||||
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
|
||||
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
|
||||
part of this repository and AniCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
AniCraft app icon (anicraft.svg, anicraft-small.svg and every file derived from them in this
|
||||
directory: anicraft-1024.png, anicraft-padded-1024.png, anicraft-macos-512.png, anicraft.ico, hicolor/).
|
||||
|
||||
Original artwork made for this project by the project owner, drawn in ArtCraft and vectorised for
|
||||
AniCraft (no third-party material). Licensed like the rest of AniCraft, under either of
|
||||
|
||||
* Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
|
||||
* MIT license (https://opensource.org/licenses/MIT)
|
||||
|
||||
at your option.
|
||||
|
||||
Regenerate the derived files with scripts/icons.sh.
|
||||
@@ -0,0 +1,53 @@
|
||||
# AniCraft app icon
|
||||
|
||||
**Creature:** an engraved rabbit, AniCraft's mascot.
|
||||
|
||||
**Style:** an engraving-style portrait in the Crafting Apps template: a head-and-shoulders portrait on a
|
||||
full-bleed field, no frame or roundel, with the body running off the tile.
|
||||
|
||||
**Palette** (exactly three colours):
|
||||
|
||||
| Colour | Hex | Used for |
|
||||
|---|---|---|
|
||||
| Ink | `#0b0b0c` | line work and contour |
|
||||
| Paper | `#f2f1ee` | the figure (a neutral white, so the rabbit doesn't read as cream on the yellow) |
|
||||
| AniCraft colour | `#dac604` | the full-bleed field |
|
||||
|
||||
**Tile:** `viewBox="0 0 512 512"`, a rounded square with `rx=112`, the same tile as every Crafting App.
|
||||
The art is clipped 6 units inside it (a concentric rounded square, `x=y=6`, `500×500`, `rx=106`), so a
|
||||
band of field colour runs round every edge where the rabbit runs off, as on the other icons. The padded files add Apple's transparent margin (tile = 824/1024 of the canvas); Windows
|
||||
and Linux use the tile edge to edge.
|
||||
|
||||
**Provenance:** the owner's original ArtCraft drawing, vectorised with `trace.py`. `anicraft.svg` is the
|
||||
canonical artwork. Licence: see `LICENSE.txt`.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What | Used by |
|
||||
|---|---|---|
|
||||
| `anicraft.svg` | master vector (traced at 1600 px, about 275 KB) | source for everything below |
|
||||
| `anicraft-small.svg` | lighter vector (traced at 1000 px, about 170 KB) | `hicolor/scalable` |
|
||||
| `anicraft-1024.png` | full tile, 1024 px | docs, store listings |
|
||||
| `anicraft-padded-1024.png` | tile with Apple's margin, 1024 px | landing pages, store listings |
|
||||
| `anicraft-macos-512.png` | tile with Apple's margin, 512 px | runtime Dock icon on macOS (`src/main.rs`) |
|
||||
| `anicraft.ico` | Windows icon, 16 to 256 px | `build.rs` (embedded in `anicraft.exe`) |
|
||||
| `hicolor/<size>/apps/ai.storyteller.anicraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime icon on Windows and Linux, the 128 one the mark in Help › About (`src/app.rs`) | Linux packaging, the Crafting Apps tables |
|
||||
| `hicolor/scalable/apps/ai.storyteller.anicraft.svg` | Linux scalable icon | as above |
|
||||
| `trace.py` | traces the 2000 px source drawing into the master SVG | regenerating the vectors |
|
||||
|
||||
## How it reaches each OS
|
||||
|
||||
- **macOS:** the app sets the Dock / app-switcher icon at runtime (`ViewportBuilder::with_icon`).
|
||||
- **Windows:** `build.rs` embeds `anicraft.ico` with `winresource` (taskbar, Start menu, Explorer,
|
||||
Alt-Tab); the runtime icon covers the title bar.
|
||||
- **Linux:** the runtime icon covers the window; install `hicolor/` to `share/icons/` for launchers.
|
||||
|
||||
## Regenerate
|
||||
|
||||
```sh
|
||||
# From the 2000 px source drawing (needs numpy, Pillow, SciPy and vtracer; svgo 3.3.2 shrinks the paths):
|
||||
python trace.py rabbit.webp master.svg 1600 4 1960 && npx svgo@3.3.2 -p 1 master.svg -o anicraft.svg
|
||||
python trace.py rabbit.webp small.svg 1000 4 1960 && npx svgo@3.3.2 -p 1 small.svg -o anicraft-small.svg
|
||||
# Every render (needs resvg on PATH and Python with Pillow):
|
||||
scripts/icons.sh
|
||||
```
|
||||
|
After Width: | Height: | Size: 334 KiB |
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 270 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="a"><rect width="500" height="500" x="6" y="6" rx="106"/></clipPath></defs><rect width="512" height="512" fill="#dac604" rx="112"/><g fill-rule="evenodd" clip-path="url(#a)"><path fill="#f2f1ee" d="M161.3 19.5c3.4-.1 3.4-.1 5.1.5l1.2-.1c3 .2 5.2 3.3 7 5.4q1.7 2.4 3 4.9l1.3 1.8q1.8 2 2.7 4.2 1 1.5 2.2 2.7l.4 1.1q1.3 2.5 3.3 4.4c1 1.2 1 1.2 1.4 3 .6 2 1.7 3.3 3.3 4.9a20 20 0 0 1 5.4 7.6l1.2 1.2q2 2 3.4 4.4l1.3 1.3q3 3.1 3.9 7.4l-.6 1 1 .2c2 .6 2.7 2.3 3.7 4l1.5 4.2q2.1 6.1 5.7 11.7c1.2 2.1 1.6 4.3 2 6.6.5 1.5.5 1.5 1.3 2.8q1.2 2 1.5 4.6l1.8 7q2 6.8 2.4 13.8c.1 1.5.4 2.3 1.2 3.5v1.4c0 2.5.5 5.3 2.3 7.1l.7.7q1.2 1.8 2 3.7c1.3 2.9 1.3 2.9 2.8 3.7 1.4-.2 1.4-.2 2.7-1.2q1.8-2.3 2.8-5 .6-1.9 2-3.2l3.1-1-.1-1.2c.1-2.7 1.2-5 2.1-7.5 1.4-3.5 2.1-7 2.9-10.5.5-2.8 1.2-5.3 3.3-7.4l.4-1.8c.6-1.8.9-2.1 2.1-3.4l1.1-2 .5-1 1-2.4q1-2.4 2.6-4.3c0-.2 0-.2.7-1.2l2.7-4 1.4-2.3 2-2.7c1.4-1.6 2-3.3 2.9-5.2 2.1-3.3 2.1-3.3 3.6-4l1.5-2.6.8-.7c.8-.8.8-.8 1.4-2.2q1.4-2.7 3.4-4.8 2-2.2 3.7-4.7 1.3-1.9 3-3.3 2.3-1.8 3.6-4.3l2.5-2 2-1.8 3.8-3.1 4-3.8 2.7-2.6 1.5-1.3q4.8-3.9 10.4-6.8 2.4-1.4 4.7-3.3c1.2-1 2.3-1.3 3.7-1.9l2.3-1.4a36 36 0 0 1 16.9-5c1.8-.3 1.8-.3 2.3-.8 4.2-.4 8.4 1 12 3 4.8 4 4.8 4 5.3 6.6l.1 1.7.7 1c3 4 2 11.3 1.4 15.9l-.2 1.5q-.8 5.5-2.1 10.9l-.3 1.4-.4 1.4-.2 1.2c-.4 1-.4 1-1.4 2-.2 1.1-.2 1.1-.2 2.5-.8 9.2-.8 9.2-2.4 10.8l-.3 3.1c-.2 1-.2 1-1.2 2.6l-.4 2.7c-.8 4.9-2.8 9.2-4.9 13.6q-.9 2.3-1.4 4.7l-1.5 3.8-1.3 3.6a38 38 0 0 1-4.9 10l-1 2.5-1.2 3-.7 1.4c-.6 1.3-.6 1.3-2.2 2.3 0 .2 0 .2-.7 1.2-.8 1.3-.8 1.3-2 2.5a19 19 0 0 0-3.2 4.8q-1.4 2.1-3.3 3.8l-1.4 1.4-1.4 1.4-1.4 1.5q-1.9 1.7-4 2.8l-2 2.3-3.4 3.7q-2 2.1-3.7 4.5l-.6.8h-1l.3 1.2.2 1.4-.5.5-.1 1.6a7 7 0 0 1-1.7 3.7 10 10 0 0 0-2 5.4c-.3 1-.3 1-1.4 2.6l-.7 2.4c-1.6 5.6-1.6 5.6-3.4 7.3l-.4 1.7c-.6 1.9-.6 1.9-1.4 3.1q-2.5 4.7-1.7 10l1.5 3.1q.4 3.2-.5 6.2h1.2c1.3.5 1.3.5 2 1.4l.5 1.2c1 2 2 3 3.7 4.3 1.7 1.5 1.7 1.5 2 3l-.7 2.9 2-.3c1.5-.2 2-.2 3.6.3h2.3l1.1.1c1.2-.1 1.2-.1 2.2-.9 1.7-1.2 3.3-1 5.3-1 1.4-.3 1.4-.3 2.4-1 1.3-1 2-.8 3.6-.8l2.2-1.4c1.6-1.2 3-2 5-2.4 2.8-.8 4.8-2.2 7.1-3.9 1.6-1 1.6-1 3.5-1 2.5.1 4.1-.8 6.3-2s4.1-2.2 6.6-2.6q3-.7 5.7-1.9 3-1.3 6-.4c1.4.3 2 0 3.3-.4l1.2-.4 2.3-1c2.4-.9 4-1 6.6-1 1.4-.7 1.4-.7 2.6-1.6 2.7-1.6 2.7-1.6 4.2-1.4l.9.4q2.4.8 4.7.6h9.4c1.3 0 1.3 0 1.8-.6l5.3-.4h1.5l1.5-.1 1.3-.1c1.1 0 1.1 0 2.1 1.1l3.1.4 2.2.4c.9.2.9.2 2.2.2s1.3 0 2.3 1q2 .4 4.1.5 4.3.3 8.2 1.8 2.5.8 5 1l1.4.2 1.4.2c1.4.5 1.4.5 2.3 1.7 1.5 1.7 2.4 1.7 4.5 1.8h1.3c4.3.3 4.3.3 5.5 1.6l.6 1c2.3.8 4.5.3 7 .2 1.7.3 1.7.3 2.3 1l.6 1c1.5 2.4 3.5 2.8 6.2 3.5a16 16 0 0 1 8 4l3 1.6 2.8 1.7q3 1.9 6 3.4l1 1 1 .4c4 1.7 4 1.7 5.6 3.7q.8 3.8.5 8v77.3l-.1 29v46.4l-.1 15.8v7.3l-.1 6.6v2.4c0 4 0 7.3-1.7 11l-.4 1.6q-1.3 3.7-3 7l-1.3 3c-.5 1.2-.5 1.2-1.5 2.2l-.4 1.4q-.8 2.3-2.1 4.2l-.8 1.3a130 130 0 0 1-8 11.3c-1 1.2-1 1.2-1.8 2.6s-2 2.2-3.3 3.3l-4.5 5.4a65 65 0 0 1-16.5 13l-1.9 1.2c-6.2 4-13 6.7-19.8 9.5l-3 1.5c-2.5 1.2-5 1.2-7.8 1.2h-86.7c-2.5 0-2.5 0-3.6-1.1 0-1.4.3-2 1.4-2.9 4.2-2.6 9-2.4 13.8-2.6h1.9l1.8-.1h1.7c1.4 0 1.4 0 3 .5l-.6-4.1q-1.9-.7-3.8-.8c-2-.2-3.2-.7-4.9-1.8l-1.7-.5c-2-.6-3.3-1.3-5-2.6l-.9.5-2 1q-3.3 1.8-4.7 5.2a9 9 0 0 1-3.6 4q-1.4 2.3-2 4.7c-1 .9-2 .6-3.1.6h-61.9c-1.1-.1-1.1-.1-2.1-1.1v-2.5l.2-1.4c.3-1.2.3-1.2 1-2.3 1-1.2 1.1-2.3 1.4-3.9.3-2.6.3-2.6 1.5-3.7q.5-3.7.5-7.2l-.9-.2-5.3-1.4-1 2.1h-2.6v3.3l.1 1.8c0 1.6 0 1.6-1 2.6l-.3 2.2c-.1 1.7-.2 2.2-1.3 3.6-1.4 1.8-1.5 3.5-1.8 5.7-.3 1.3-.3 1.3-1.3 2.3l-4.3.2h-38.8c-2.9-.1-2.9-.1-4-1.2v-3.6l-1-1q.1-2 1-3.6c.7-1.5.4-2.6 0-4.1l-.5-.5q-.3-4.6.5-9.1c0-1.2 0-1.2-.3-2.2-.3-1.3.2-1.9.8-3l-.2-2.3c-.3-2-.1-3.5.7-5.4l-.9-.2c-1.7-.6-2.2-1.7-3.1-3.2q-1-2.5-1.3-5.1a9 9 0 0 0-1.4-3.2c-1-1.7-1.3-2.8-1.5-4.7l-1.7-.2c-1.8-.3-1.8-.3-2.9-1.4l-2-5.6h-1c-2.5.2-4.1.2-6.2-1.5q-1.5-1.8-2.8-3.8c-.8-1.3-.8-1.3-2.1-2.8a7 7 0 0 1-1.7-3.8l-.6-2-2.6-1c-1.6-.8-2.3-2.4-3.2-4-1.1-1.6-2.3-2.5-3.9-3.6l-1.1-.2c-1-.3-1-.3-1.9-2-.7-2.4-.7-2.4 0-4l.5-1.5-1.5-.5c-1.6-.5-1.6-.5-2.6-1.5q.1-2.1.5-4.1l-2-1v-7.7l-3.1.5c-1-1-1-1-1.1-2.9v-1.7l-1-.2c-1-.4-1-.4-1.5-.9l.5-3.6-.9.6c-1.5.6-2.2.4-3.7 0-.5-.6-.5-.6-.6-2v-3.3c0-1.4 0-1.4.6-2 .2-2.9-.3-5-1.2-7.8-.4-1.3-.4-2.2-.4-3.5 0-2.1-.4-2.7-1.5-4.5v-3.6l-.8-2c-.9-2-.7-3.7-.4-6 .2-1.2.2-1.2.2-3.2l-.8-1c-.8-1-.8-1-.6-2.2l.4-1v-1.5l-.6-.5v-5.2q.1-3.8-.5-7.6c-1-1-1-1-2.2-1.7-2.4-1.3-2.4-1.3-3.4-2.4l-1.2-.4c-1.7-.7-2.3-1.7-3.4-3.2l-1.1-.8-1-.7v-1H137q-2.6 0-5.1-1-.8 0-1.8-.4a9 9 0 0 1-3.5-2.7l-2.6-1.5-.5-1-1.2-.6c-1.7-1.2-2.1-2.3-3-4.2-.4-.9-.4-.9-1.4-2l-1-2.5-1-1-1.6-3.6-1-1v-3.6l-.6-.5-.3-3.4c-.2-1.2-.2-1.2-.7-2.4-1-3-.6-6.4-.5-9.6v-1c.2-5.8.2-5.8 1.3-7l.8-.7.4-1.3q1-2.8 2.7-5.3c.4-1 .4-1 0-2l-.6-1.1c-.3-3.2-.2-5.5 1.5-8.2l.5-2.5c.4-2.4 1.3-3.8 2.9-5.7q1.4-2.2 2.3-4.5 1.3-3 3.6-5.1c1.2-1.4 1.6-2.8 2.1-4.7.5-1.2 1-1.7 2-2.6l1-3.6.5-.5a8 8 0 0 0-1-4.8 16 16 0 0 1-.5-11l.2-1.4c.3-1.2.3-1.2 1.3-2.2l.5-1.6c.5-1.5.5-1.5 1.5-2.5v-1.6l-3-2c.9-4 2.4-7.2 5-10.4.6-.9.6-.9 1-2.5.8-2 2-2.5 3.6-3.7a16 16 0 0 0 3-3 14 14 0 0 1 4.8-4c1.5.1 1.5.1 2.5.5l.4-.8c1.3Line truncated
|
||||
|
After Width: | Height: | Size: 169 KiB |
|
After Width: | Height: | Size: 90 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="a"><rect width="500" height="500" x="6" y="6" rx="106"/></clipPath></defs><rect width="512" height="512" fill="#dac604" rx="112"/><g fill-rule="evenodd" clip-path="url(#a)"><path fill="#f2f1ee" d="m165.1 19.8 3.4.5c1.3.2 1.8.6 2.7 1.5l.3 1 1 .8a17 17 0 0 1 4.5 6q.6 1.4 2 2.2c1 .6 1 1 1.3 2.1q1 3 3 5.3l.8 1.3 1.5 1.9q1.1 1.2 1.6 2.7l.5.5q.6.7 1 1.7.8 2.5 2.7 4.2c.8.8 1 .9 1 2 .3 1.7 1.3 2.1 2.6 3q1.5 1.5 2.2 3.2 1 1.3 2.2 2.3 1.5 1 2.1 2.8c.4 1.1.4 1.1 1.3 1.7q.6.1 1 .4c1.3 1.2 1.6 2.4 2 4q.6 1.3 1.6 2.4v1.3q.3 0 .5.2 1.4 1 2.2 2.5l.4.6a13 13 0 0 1 1.7 4l.7 1.7 1.5 3.5q1 2.7 2.3 5.2a55 55 0 0 1 3.5 8.3c.9 2.7.9 2.7 1.9 3.7l.6 2 .3.3.3 2.5c0 .7 0 .7.4 1l.2 2c.1.5.1.5.7 1.2l.2 3.4c.2 1.2.3 1.3 1.1 2v2q.1 1.2 1 2.2.9 3.2.6 6.5v1.5c0 .8.4 1 1 1.6v1.9c0 1.4 0 2.2.6 3.5l.4 1.7.1.9.2.6.7.1c.9.2.9.2 1.2.6l.2 2.1q.1 1 .7 2l.7.1.6.2.7 1.6c.4 1.3.7 1.9 1.9 2.6l1.6.3.2-.6c.4-.7.4-.7 1.2-1 1.6-1.2 2.3-3.2 2.8-5.1.3-1 .3-1 .9-1.6l.3-.8c.3-.8.3-.8 1.3-1.2l1-.2.6-.7h1.3l-.2-.9c-.2-1.2 0-1.3.8-2.3q.3-1.5.3-3.1v-.7l.5-.4c.8-.9.9-2 1.1-3 .7-2.9.7-2.9 1.2-4q.7-1.8.9-3.6.6-3 1.8-5.7l.3-.8c.8-2 .8-2 1.5-2.6l.4-.4c0-.9 0-.9-.3-1.6l1-.8c2-1.7 2.7-4 3.6-6.4q1-2.3 2.3-4.4c.5-.6.5-.6.8-1.6.4-1.1 1-1.6 1.9-2.5l1-1.6.5-.6.7-1.4q.6-1.4 1.8-2.3l1-1.3c.6-1 1.3-1.3 2.4-1.7v-1.3c.1-1.1.5-1.5 1.2-2.3l.7-1q.6-1.3 1.6-2.2l.4-.9c.5-1 .5-1 1.1-1.6q1.1-1 1.6-2.3 1.1-2.1 2.7-3.8l2-2.4.8-.9 1.2-1.8 3-3.5.7-.6 4.7-4.9 2.5-2.5q2.7-2.8 5.8-5.2c1.5-1 1.5-1 2-2 1-1.4 2.4-2 3.8-2.8a8 8 0 0 0 3.2-3.5c1-.6 1-.6 2.2-.8 1.5-.4 2-1.2 2.8-2.4.7-1 1.3-1 2.4-1.3l1.4-.6q1.5-.7 3-1l.1-.5q.6-1.4 1.9-2.3l.6-.7c2 .2 2 .2 2.9.7l-.3-1.6a50 50 0 0 1 6.3-3.6q1.8-.9 3.7-1.1c1.3-.1 1.3-.3 2.1-1.1l2-.2q1.4 0 2.8-.4h1.7q2.8 0 5.4-.9l.6-.1.6.6 3.2.6A8 8 0 0 1 361 25l1.1.4c1 .5 1.5.7 2 1.5l.4 1 1.6.8q1.5 1 1.8 2.7l.2 1.2c.5 2.4.5 2.4 1.2 3.4s.7 1.3.6 2.4l-.2.7c-.2 1.5.3 3 .7 4.4q.2 1.3 0 2.6v1l-.5 2.2-.1.7c-.2.9-.2.9-.6 1.7q-.4 1.1-.2 2.4l.6.6c-.2 2.1-.2 2.1-1 2.9l-.2 1.3-.1.8-.1.8-.3 1.5v.8c-.2.6-.2.6-.9 1.2l-.4 3c-.2.9-.6 1.3-1.2 2.1l-.2 1.5v.7l.1 1.3q.2 1.4-.5 2.6c-.6 2-1 3.3-.9 5.4 0 .7 0 .7-.5 1.3q-.9 1.2-1 2.7-.5 2.2-1.4 4l-.4 3c-.2 2.4-.2 2.4-1 3.1q0 .7-.4 1.5-.5 2-1.4 3.7a33 33 0 0 0-2.7 8l-1 2.1q-1 1.8-1.5 4l-.3.6c-.3.6-.3.6-.3 1.6 0 1.2-.4 1.4-1.3 2.2l-.7 2.6-1 1.8c-2.1 3.4-2.1 3.4-2 5l-.1.8-1.6 1-.4 1.6c-1 2.7-3.2 5.2-5 7.4l-1.3 1.5-.6.7-1 2.2a6 6 0 0 1-2.7 2.8c-.9.4-.9.4-1.1 1.3-.5 1.3-1 1.7-2 2.5l-1.2 1.2q-1.1 1.4-2.4 2.1l-3.9 3.1c-.5.5-.5.5-1.5 1.1l-.2.8a5 5 0 0 1-2.4 2.5c-2 1.2-2.5 2.3-3.1 4.4-.6.8-.6.8-1.3 1.3h-1.3l.4.5c.4 1 .3 1.4 0 2.4l-.6.4c-.4.5-.4.5-.5 1.2v2.2l-.9 1-.3.8c-.3.8-.3.8-1.3 1.4l-.1 1.6q0 3-2.1 5.1l-.1 1q-.6 3-2.8 5.4l-.6.3.2 1c.1 1.6-.3 1.8-1.2 2.9l-.2 1.3c-.1 1.3-.2 1.4-1 2.2q-.9 1.6-.8 3.4c-.2 1.3-.5 2-1.5 3l-.7.3.4.5c.3.8.3.8.2 2v1.4q.1-.2.8.7c1.3 1.3 1.6 3 1.8 4.7 0 .7 0 .7-.3 1.3l-.3 1.2-.3 1h.9c1 0 1 0 1.8.6.5.7.5.7.4 1.5s0 .8 1 1.6l.7.8c0 .8-.3 1.2-.7 2l.7-.8c1-.6 1-.6 1.6-.6 1 .6 1 1.3 1.3 2.3l.5 3.5c.1 1 .1 1-.5 2a6 6 0 0 0 2.8.6l.6-.6c.7-.4.7-.4 1.6-.3l2 .6c2.2.6 3.5.3 5.6-.7 1.6-.9 2.5-1 4.3-.6 1.2 0 2.1-.9 3-1.5q1.6-.7 3.1-.1l1.3-1.3 1.5-1q1.2-.7 2.3-1.5c1.4-1 1.4-1 2.3-1h.7c1.2.3 1.2.3 1.8-.1l1.1-1q.9-.9 2.1-1.2l1.1-.8c1-.8 1-.8 2-.7l.8.2c.7.3.7.3 1.6.4l2-1.3q1.8-1.2 3.7-2l.7-.6 2.4-.1.8-.2.6-1.3c1-.7 2-.6 3.2-.6q1.2 0 2.3-.7l2.2-1 2.3-1q1-.4 2.2-.2l.6.7c.6.6.6.6 1.5.5q2.6-.6 5.1-1.7 2.2-1 4.6-1.3 4.3-.4 8-2.7c1-.6 1.4-.9 2.6-.6l1 1.3 1.2-.2 1.3-.2.3.4h2.9q1.3 0 2.5-.7 1.1.1 1.9.7c.9.4 1.4.2 2.4 0l1-.1 1-.2q4.6-1 9.4-1.1h2.2l.5.7c.5.7.5.7 1.2.8h3.5c2.4 0 2.4 0 3.3.8 1.4 1 3 .9 4.6.9 2.9 0 5.3 0 7.8 1.7l1.8.5 3 .8c1 .3 1 .3 1.7.1q1.3-.2 2.7.5h1.2c1 .3 1 .3 1.8 1.2 0 .2 0 .2.6 1 2.2 1.6 5.3 1.7 8 1.6 1.1 0 1.5 0 2.5.6.7.7.7.7 1.1 1.6 1.2 1 2.2 1 3.8 1 2 0 3.5 0 5.4.7.3 1.2.3 1.2 0 1.9h.7c1 0 1.3.3 2.1 1l2.3.6.6.3q1.1.5 2.4.6c2.3.4 3.6 1 5 3q1 .6 2.2 1c2.3.6 4.1 2.4 5.8 4l.7.2c.9.2.9.2 1.3.6q1 .9 2.2 1.2c1.5.6 1.5.6 2.2 1.3l1.2.4q1.4.3 2.3 1.3 1.4 1.1 2.9 1.8c.6.6.3 1.5.3 2.3v49.8q0 1.1-.3 2.3l.3.3v128l.1 5.3v9.6q.1 1.6-.7 3l-.3 1.8c-.3 1.5-.6 2-1.7 3v2.3q-.5 1.4-1.4 2.5-.7 1-.8 2.2a8 8 0 0 1-1.3 3.3l-.5 1c-.4.9-.4.9-1 1.5l-.3 1q-.6 1.8-1.9 3.4l-1 2c-.4 1.3-1 2-2 2.9l-1.5 2.2-.7 1.4q-.8 1.5-2 2.5l-.3.8q-.6 1.3-1.9 2l-.7 1-.6.7h-1v.6a7 7 0 0 1-2.2 3.2h-1l.2.7-.1.9-1.6 1q-.4 0-.7.3l-.2.7q-1 1.8-2.7 3.1l-.8 1c-.8.6-.8.6-1.4.8-.6.1-.6.1-1 .8-.9 1.4-2.2 3-3.8 3.4l-.6.1-2.1 2.1c-.5.5-.5.5-1.3.7-.8.4-.8.4-1.6 1.2s-1 .9-2 1.1l-.5.6c-.5.7-.5.7-1.6 1-1.3.4-1.7.9-2.6 1.8q-1 .9-2.4.8l-.4.6c-.8.9-1.4 1-2.5 1.3-1.8.5-1.8.5-2.4 1.1-.7.8-1.6.9-2.6 1.2-2 .5-2 .5-2.7 1.2l-3.5 1.4-4.8 1.8c-1 .3-1 .3-2 1h-1.8q-.4 0-.7.3h-83.3l-3.4.1h-6.7c-.7-.1-.7-.1-1.3-.7 0-.8 0-.8.3-1.6q1.2-.9 2.5-1.4c.7-.2.7-.2 1.4-.9l1.4-.5c1-.2 1.5-.5 2.4-1 .6-.2.6-.2 1.3-.2h1.8l.8-.1 5.5-.1 7.9-.3-.3-4.5c-2.5 0-2.5 0-3.4.3q-1.7 0-3-1-1.9-.9-4-1.2a6 6 0 0 1-3.7-2l-1.6-.6-.7-.2-.6-.1-.6.6h-1.3l-.3.6c-.4.7-.4.7-1 1l-.4 1.1-.6 1.2-1.1.5-1.1.4c-.4 1.1-.4 1.1-.6 2.3-.6 1-.6 1-1.3 1.6h-1.3l-.1.6c-.2.7-.2.7-Line truncated
|
||||
|
After Width: | Height: | Size: 274 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 757 B |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 144 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="a"><rect width="500" height="500" x="6" y="6" rx="106"/></clipPath></defs><rect width="512" height="512" fill="#dac604" rx="112"/><g fill-rule="evenodd" clip-path="url(#a)"><path fill="#f2f1ee" d="M161.3 19.5c3.4-.1 3.4-.1 5.1.5l1.2-.1c3 .2 5.2 3.3 7 5.4q1.7 2.4 3 4.9l1.3 1.8q1.8 2 2.7 4.2 1 1.5 2.2 2.7l.4 1.1q1.3 2.5 3.3 4.4c1 1.2 1 1.2 1.4 3 .6 2 1.7 3.3 3.3 4.9a20 20 0 0 1 5.4 7.6l1.2 1.2q2 2 3.4 4.4l1.3 1.3q3 3.1 3.9 7.4l-.6 1 1 .2c2 .6 2.7 2.3 3.7 4l1.5 4.2q2.1 6.1 5.7 11.7c1.2 2.1 1.6 4.3 2 6.6.5 1.5.5 1.5 1.3 2.8q1.2 2 1.5 4.6l1.8 7q2 6.8 2.4 13.8c.1 1.5.4 2.3 1.2 3.5v1.4c0 2.5.5 5.3 2.3 7.1l.7.7q1.2 1.8 2 3.7c1.3 2.9 1.3 2.9 2.8 3.7 1.4-.2 1.4-.2 2.7-1.2q1.8-2.3 2.8-5 .6-1.9 2-3.2l3.1-1-.1-1.2c.1-2.7 1.2-5 2.1-7.5 1.4-3.5 2.1-7 2.9-10.5.5-2.8 1.2-5.3 3.3-7.4l.4-1.8c.6-1.8.9-2.1 2.1-3.4l1.1-2 .5-1 1-2.4q1-2.4 2.6-4.3c0-.2 0-.2.7-1.2l2.7-4 1.4-2.3 2-2.7c1.4-1.6 2-3.3 2.9-5.2 2.1-3.3 2.1-3.3 3.6-4l1.5-2.6.8-.7c.8-.8.8-.8 1.4-2.2q1.4-2.7 3.4-4.8 2-2.2 3.7-4.7 1.3-1.9 3-3.3 2.3-1.8 3.6-4.3l2.5-2 2-1.8 3.8-3.1 4-3.8 2.7-2.6 1.5-1.3q4.8-3.9 10.4-6.8 2.4-1.4 4.7-3.3c1.2-1 2.3-1.3 3.7-1.9l2.3-1.4a36 36 0 0 1 16.9-5c1.8-.3 1.8-.3 2.3-.8 4.2-.4 8.4 1 12 3 4.8 4 4.8 4 5.3 6.6l.1 1.7.7 1c3 4 2 11.3 1.4 15.9l-.2 1.5q-.8 5.5-2.1 10.9l-.3 1.4-.4 1.4-.2 1.2c-.4 1-.4 1-1.4 2-.2 1.1-.2 1.1-.2 2.5-.8 9.2-.8 9.2-2.4 10.8l-.3 3.1c-.2 1-.2 1-1.2 2.6l-.4 2.7c-.8 4.9-2.8 9.2-4.9 13.6q-.9 2.3-1.4 4.7l-1.5 3.8-1.3 3.6a38 38 0 0 1-4.9 10l-1 2.5-1.2 3-.7 1.4c-.6 1.3-.6 1.3-2.2 2.3 0 .2 0 .2-.7 1.2-.8 1.3-.8 1.3-2 2.5a19 19 0 0 0-3.2 4.8q-1.4 2.1-3.3 3.8l-1.4 1.4-1.4 1.4-1.4 1.5q-1.9 1.7-4 2.8l-2 2.3-3.4 3.7q-2 2.1-3.7 4.5l-.6.8h-1l.3 1.2.2 1.4-.5.5-.1 1.6a7 7 0 0 1-1.7 3.7 10 10 0 0 0-2 5.4c-.3 1-.3 1-1.4 2.6l-.7 2.4c-1.6 5.6-1.6 5.6-3.4 7.3l-.4 1.7c-.6 1.9-.6 1.9-1.4 3.1q-2.5 4.7-1.7 10l1.5 3.1q.4 3.2-.5 6.2h1.2c1.3.5 1.3.5 2 1.4l.5 1.2c1 2 2 3 3.7 4.3 1.7 1.5 1.7 1.5 2 3l-.7 2.9 2-.3c1.5-.2 2-.2 3.6.3h2.3l1.1.1c1.2-.1 1.2-.1 2.2-.9 1.7-1.2 3.3-1 5.3-1 1.4-.3 1.4-.3 2.4-1 1.3-1 2-.8 3.6-.8l2.2-1.4c1.6-1.2 3-2 5-2.4 2.8-.8 4.8-2.2 7.1-3.9 1.6-1 1.6-1 3.5-1 2.5.1 4.1-.8 6.3-2s4.1-2.2 6.6-2.6q3-.7 5.7-1.9 3-1.3 6-.4c1.4.3 2 0 3.3-.4l1.2-.4 2.3-1c2.4-.9 4-1 6.6-1 1.4-.7 1.4-.7 2.6-1.6 2.7-1.6 2.7-1.6 4.2-1.4l.9.4q2.4.8 4.7.6h9.4c1.3 0 1.3 0 1.8-.6l5.3-.4h1.5l1.5-.1 1.3-.1c1.1 0 1.1 0 2.1 1.1l3.1.4 2.2.4c.9.2.9.2 2.2.2s1.3 0 2.3 1q2 .4 4.1.5 4.3.3 8.2 1.8 2.5.8 5 1l1.4.2 1.4.2c1.4.5 1.4.5 2.3 1.7 1.5 1.7 2.4 1.7 4.5 1.8h1.3c4.3.3 4.3.3 5.5 1.6l.6 1c2.3.8 4.5.3 7 .2 1.7.3 1.7.3 2.3 1l.6 1c1.5 2.4 3.5 2.8 6.2 3.5a16 16 0 0 1 8 4l3 1.6 2.8 1.7q3 1.9 6 3.4l1 1 1 .4c4 1.7 4 1.7 5.6 3.7q.8 3.8.5 8v77.3l-.1 29v46.4l-.1 15.8v7.3l-.1 6.6v2.4c0 4 0 7.3-1.7 11l-.4 1.6q-1.3 3.7-3 7l-1.3 3c-.5 1.2-.5 1.2-1.5 2.2l-.4 1.4q-.8 2.3-2.1 4.2l-.8 1.3a130 130 0 0 1-8 11.3c-1 1.2-1 1.2-1.8 2.6s-2 2.2-3.3 3.3l-4.5 5.4a65 65 0 0 1-16.5 13l-1.9 1.2c-6.2 4-13 6.7-19.8 9.5l-3 1.5c-2.5 1.2-5 1.2-7.8 1.2h-86.7c-2.5 0-2.5 0-3.6-1.1 0-1.4.3-2 1.4-2.9 4.2-2.6 9-2.4 13.8-2.6h1.9l1.8-.1h1.7c1.4 0 1.4 0 3 .5l-.6-4.1q-1.9-.7-3.8-.8c-2-.2-3.2-.7-4.9-1.8l-1.7-.5c-2-.6-3.3-1.3-5-2.6l-.9.5-2 1q-3.3 1.8-4.7 5.2a9 9 0 0 1-3.6 4q-1.4 2.3-2 4.7c-1 .9-2 .6-3.1.6h-61.9c-1.1-.1-1.1-.1-2.1-1.1v-2.5l.2-1.4c.3-1.2.3-1.2 1-2.3 1-1.2 1.1-2.3 1.4-3.9.3-2.6.3-2.6 1.5-3.7q.5-3.7.5-7.2l-.9-.2-5.3-1.4-1 2.1h-2.6v3.3l.1 1.8c0 1.6 0 1.6-1 2.6l-.3 2.2c-.1 1.7-.2 2.2-1.3 3.6-1.4 1.8-1.5 3.5-1.8 5.7-.3 1.3-.3 1.3-1.3 2.3l-4.3.2h-38.8c-2.9-.1-2.9-.1-4-1.2v-3.6l-1-1q.1-2 1-3.6c.7-1.5.4-2.6 0-4.1l-.5-.5q-.3-4.6.5-9.1c0-1.2 0-1.2-.3-2.2-.3-1.3.2-1.9.8-3l-.2-2.3c-.3-2-.1-3.5.7-5.4l-.9-.2c-1.7-.6-2.2-1.7-3.1-3.2q-1-2.5-1.3-5.1a9 9 0 0 0-1.4-3.2c-1-1.7-1.3-2.8-1.5-4.7l-1.7-.2c-1.8-.3-1.8-.3-2.9-1.4l-2-5.6h-1c-2.5.2-4.1.2-6.2-1.5q-1.5-1.8-2.8-3.8c-.8-1.3-.8-1.3-2.1-2.8a7 7 0 0 1-1.7-3.8l-.6-2-2.6-1c-1.6-.8-2.3-2.4-3.2-4-1.1-1.6-2.3-2.5-3.9-3.6l-1.1-.2c-1-.3-1-.3-1.9-2-.7-2.4-.7-2.4 0-4l.5-1.5-1.5-.5c-1.6-.5-1.6-.5-2.6-1.5q.1-2.1.5-4.1l-2-1v-7.7l-3.1.5c-1-1-1-1-1.1-2.9v-1.7l-1-.2c-1-.4-1-.4-1.5-.9l.5-3.6-.9.6c-1.5.6-2.2.4-3.7 0-.5-.6-.5-.6-.6-2v-3.3c0-1.4 0-1.4.6-2 .2-2.9-.3-5-1.2-7.8-.4-1.3-.4-2.2-.4-3.5 0-2.1-.4-2.7-1.5-4.5v-3.6l-.8-2c-.9-2-.7-3.7-.4-6 .2-1.2.2-1.2.2-3.2l-.8-1c-.8-1-.8-1-.6-2.2l.4-1v-1.5l-.6-.5v-5.2q.1-3.8-.5-7.6c-1-1-1-1-2.2-1.7-2.4-1.3-2.4-1.3-3.4-2.4l-1.2-.4c-1.7-.7-2.3-1.7-3.4-3.2l-1.1-.8-1-.7v-1H137q-2.6 0-5.1-1-.8 0-1.8-.4a9 9 0 0 1-3.5-2.7l-2.6-1.5-.5-1-1.2-.6c-1.7-1.2-2.1-2.3-3-4.2-.4-.9-.4-.9-1.4-2l-1-2.5-1-1-1.6-3.6-1-1v-3.6l-.6-.5-.3-3.4c-.2-1.2-.2-1.2-.7-2.4-1-3-.6-6.4-.5-9.6v-1c.2-5.8.2-5.8 1.3-7l.8-.7.4-1.3q1-2.8 2.7-5.3c.4-1 .4-1 0-2l-.6-1.1c-.3-3.2-.2-5.5 1.5-8.2l.5-2.5c.4-2.4 1.3-3.8 2.9-5.7q1.4-2.2 2.3-4.5 1.3-3 3.6-5.1c1.2-1.4 1.6-2.8 2.1-4.7.5-1.2 1-1.7 2-2.6l1-3.6.5-.5a8 8 0 0 0-1-4.8 16 16 0 0 1-.5-11l.2-1.4c.3-1.2.3-1.2 1.3-2.2l.5-1.6c.5-1.5.5-1.5 1.5-2.5v-1.6l-3-2c.9-4 2.4-7.2 5-10.4.6-.9.6-.9 1-2.5.8-2 2-2.5 3.6-3.7a16 16 0 0 0 3-3 14 14 0 0 1 4.8-4c1.5.1 1.5.1 2.5.5l.4-.8c1.3Line truncated
|
||||
|
After Width: | Height: | Size: 169 KiB |
@@ -0,0 +1,73 @@
|
||||
"""Trace the rabbit artwork into the app icon's master SVG.
|
||||
|
||||
Needs numpy, Pillow, SciPy and vtracer (`pip install vtracer`); see README.md for the exact run.
|
||||
usage: python trace.py SOURCE OUT_SVG WORK_PX SPECKLE CROP_PX
|
||||
|
||||
CROP_PX keeps the top-left CROP_PX square of the source: the drawing stops short of its right and
|
||||
bottom edges, so the crop lets the body run off the tile like the other Crafting Apps icons.
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import vtracer
|
||||
from PIL import Image, ImageFilter
|
||||
from scipy import ndimage
|
||||
|
||||
# Ink and paper are the Crafting Apps' shared engraving colours; the paper is a neutral white so
|
||||
# the rabbit doesn't read as cream against the yellow.
|
||||
INK, PAPER, FIELD = "#0b0b0c", "#f2f1ee", "#dac604"
|
||||
|
||||
|
||||
def trace(mask: np.ndarray, speckle: int, d: Path) -> str:
|
||||
"""One colour layer: vtracer's binary trace of `mask`, as path elements."""
|
||||
png, svg = d / "mask.png", d / "mask.svg"
|
||||
Image.fromarray(np.where(mask, 0, 255).astype(np.uint8)).filter(ImageFilter.MedianFilter(3)).save(png)
|
||||
vtracer.convert_image_to_svg_py(
|
||||
str(png), str(svg), colormode="binary", mode="spline", filter_speckle=speckle,
|
||||
corner_threshold=60, length_threshold=4.0, splice_threshold=45, path_precision=1,
|
||||
)
|
||||
found = re.findall(r'<path d="([^"]+)"[^>]*transform="translate\(([-\d.]+),([-\d.]+)\)"', svg.read_text())
|
||||
return "".join(f'<path transform="translate({x} {y})" d="{p.strip()}"/>' for p, x, y in found)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
src, out, n, speckle, crop = sys.argv[1], Path(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])
|
||||
im = Image.open(src).convert("RGB").crop((0, 0, crop, crop)).resize((n, n), Image.LANCZOS)
|
||||
a = np.asarray(im).astype(np.int32)
|
||||
r, g, b = a[..., 0], a[..., 1], a[..., 2]
|
||||
# The field is saturated yellow: blue far below red and green (ink over it stays yellowish).
|
||||
yellow = (np.minimum(r, g) - b) > 0.55 * np.maximum(r, 1)
|
||||
dark = 0.299 * r + 0.587 * g + 0.114 * b < 120
|
||||
|
||||
# The tile's rounding is done by SVG clips, so the art runs past it here. Only the source's own
|
||||
# dark olive margin goes: the dark regions joined to an image corner.
|
||||
olive, _ = ndimage.label(dark & (b < 0.25 * np.maximum(r, 1)))
|
||||
margin = np.isin(olive, [c for c in {olive[0, 0], olive[0, -1], olive[-1, 0], olive[-1, -1]} if c])
|
||||
inside = ~ndimage.binary_dilation(margin, iterations=2)
|
||||
|
||||
# Paper is the rabbit's silhouette: everything not yellow, opened so whiskers and stray fur
|
||||
# strokes over the field stay ink on yellow (no white halo), holes filled.
|
||||
disk = np.hypot(*np.mgrid[-3:4, -3:4]) <= 3.2
|
||||
silhouette = ndimage.binary_fill_holes(ndimage.binary_opening(inside & ~yellow, structure=disk, iterations=max(1, n // 1000)))
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
paper = trace(silhouette & inside, speckle, Path(d))
|
||||
ink = trace(inside & dark, speckle, Path(d))
|
||||
# The Crafting Apps tile (rx 112 of 512) filled with the field, and the art clipped 6 units inside
|
||||
# it (a concentric rx 106), so a band of field colour runs round every edge as on the other icons.
|
||||
out.write_text(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">'
|
||||
'<defs><clipPath id="a"><rect x="6" y="6" width="500" height="500" rx="106"/></clipPath></defs>'
|
||||
f'<rect width="512" height="512" rx="112" fill="{FIELD}"/>'
|
||||
f'<g clip-path="url(#a)"><g transform="scale({512 / n:g})" fill-rule="evenodd">'
|
||||
f'<g fill="{PAPER}">{paper}</g><g fill="{INK}">{ink}</g></g></g></svg>\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Optional font build input (the Craft family convention, as in PhotoCraft).
|
||||
//! Optional font build input (the Craft family convention, as in PhotoCraft), and the app icon
|
||||
//! embedded in the Windows executable.
|
||||
//!
|
||||
//! `CRAFT_FONTS_DIR=<craft-fonts checkout> cargo build` embeds the UI typefaces chosen in
|
||||
//! ADR 0005: Inter (prose) and JetBrains Mono (data), both SIL OFL 1.1. Font files are never
|
||||
@@ -49,7 +50,22 @@ fn discover() -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Windows only: embed the app icon into `anicraft.exe` (taskbar, Start menu, Explorer, Alt-Tab).
|
||||
/// A missing resource compiler is a warning, so a cross-compile still links.
|
||||
fn windows_icon() {
|
||||
println!("cargo:rerun-if-changed=assets/app-icon/anicraft.ico");
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("assets/app-icon/anicraft.ico").set("ProductName", "AniCraft").set("FileDescription", "AniCraft 2D vector animation studio");
|
||||
if let Err(e) = res.compile() {
|
||||
println!("cargo:warning=anicraft.exe built without its icon: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
windows_icon();
|
||||
println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
let dir = discover();
|
||||
|
||||
@@ -30,6 +30,10 @@ USAGE:
|
||||
anicraft-cli mcp [file|--sample] Model Context Protocol server on stdin/stdout,
|
||||
for AI assistants (see docs/mcp.md)
|
||||
|
||||
--plugins <folder> loads the WebAssembly plug-ins in a folder first (also the
|
||||
ANICRAFT_PLUGINS environment variable); see docs/plugins.md.
|
||||
Without it, headless runs use no plug-ins, so they are repeatable.
|
||||
|
||||
Frames on the command line are 1-based, as in the timeline.";
|
||||
|
||||
/// Parsed flags: positional args plus `--key value` pairs.
|
||||
@@ -77,6 +81,19 @@ pub fn open_session(src: Option<&str>) -> Result<Session, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`open_session`], with the plug-ins of `--plugins <folder>` (or `ANICRAFT_PLUGINS`) loaded.
|
||||
pub fn session(a: &Args, src: Option<&str>) -> Result<Session, String> {
|
||||
let mut s = open_session(src)?;
|
||||
let folder = a.flag("plugins").map(str::to_string).or_else(|| std::env::var("ANICRAFT_PLUGINS").ok().filter(|v| !v.trim().is_empty()));
|
||||
if let Some(folder) = folder {
|
||||
let r = exec(&mut s, "plugin.reload", &json!({"folder": folder}))?;
|
||||
for f in r["failed"].as_array().into_iter().flatten() {
|
||||
eprintln!("plug-in {} not loaded: {}", f["file"].as_str().unwrap_or(""), f["error"].as_str().unwrap_or(""));
|
||||
}
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, id: &str, params: &Value) -> Result<Value, String> {
|
||||
s.execute(id, params).map_err(|e| format!("{id}: {e}"))
|
||||
}
|
||||
@@ -101,11 +118,11 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
serde_json::to_string_pretty(&list).map_err(|e| e.to_string())
|
||||
}
|
||||
"info" => {
|
||||
let s = open_session(Some(src.ok_or("info needs a file or --sample")?))?;
|
||||
let s = session(&a, Some(src.ok_or("info needs a file or --sample")?))?;
|
||||
serde_json::to_string_pretty(&s.info()).map_err(|e| e.to_string())
|
||||
}
|
||||
"render" => {
|
||||
let mut s = open_session(Some(src.ok_or("render needs a file or --sample")?))?;
|
||||
let mut s = session(&a, Some(src.ok_or("render needs a file or --sample")?))?;
|
||||
let out = a.flag("out").ok_or("render needs --out <file.png>")?;
|
||||
let mut p = json!({"path": out, "frame": one_based(&a, "frame")?.unwrap_or(0)});
|
||||
if let Some(sc) = a.num::<f32>("scale")? {
|
||||
@@ -114,7 +131,7 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
exec(&mut s, "file.export_png", &p).map(|v| v.to_string())
|
||||
}
|
||||
"render-seq" => {
|
||||
let mut s = open_session(Some(src.ok_or("render-seq needs a file or --sample")?))?;
|
||||
let mut s = session(&a, Some(src.ok_or("render-seq needs a file or --sample")?))?;
|
||||
let dir = a.flag("out-dir").ok_or("render-seq needs --out-dir <dir>")?;
|
||||
let mut p = json!({"dir": dir});
|
||||
if let Some(f) = one_based(&a, "from")? {
|
||||
@@ -129,7 +146,7 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string())
|
||||
}
|
||||
"gif" => {
|
||||
let mut s = open_session(Some(src.ok_or("gif needs a file or --sample")?))?;
|
||||
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 <anim.gif>")?;
|
||||
let mut p = json!({"path": out});
|
||||
if let Some(f) = one_based(&a, "from")? {
|
||||
@@ -162,7 +179,7 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
exec(&mut s, "file.save", &json!({"path": out})).map(|v| v.to_string())
|
||||
}
|
||||
"exec" => {
|
||||
let mut s = open_session(Some(src.ok_or("exec needs a file or --sample")?))?;
|
||||
let mut s = session(&a, Some(src.ok_or("exec needs a file or --sample")?))?;
|
||||
let id = a.positional.get(1).ok_or("exec needs a command id")?;
|
||||
let params: Value = match a.positional.get(2) {
|
||||
Some(t) => serde_json::from_str(t).map_err(|e| format!("params are not JSON: {e}"))?,
|
||||
@@ -175,7 +192,7 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
Ok(v.to_string())
|
||||
}
|
||||
"run" => {
|
||||
let mut s = open_session(Some(src.ok_or("run needs a file or --sample")?))?;
|
||||
let mut s = session(&a, Some(src.ok_or("run needs a file or --sample")?))?;
|
||||
let script = a.positional.get(1).ok_or("run needs a script.json")?;
|
||||
let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?;
|
||||
// Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it.
|
||||
@@ -193,14 +210,14 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
}
|
||||
"bench" => bench(&a),
|
||||
"serve" => {
|
||||
let mut s = open_session(src)?;
|
||||
let mut s = session(&a, src)?;
|
||||
let stdin = std::io::stdin();
|
||||
let mut stdout = std::io::stdout();
|
||||
serve(&mut s, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?;
|
||||
Ok(String::new())
|
||||
}
|
||||
"mcp" => {
|
||||
let mut s = open_session(src)?;
|
||||
let mut s = session(&a, src)?;
|
||||
let stdin = std::io::stdin();
|
||||
let mut stdout = std::io::stdout();
|
||||
mcp::serve(&mut s, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?;
|
||||
@@ -236,8 +253,42 @@ pub const TIME_BUDGETS: &[(&str, &str, f64)] = &[
|
||||
("hit_test_us", "hit test (µs)", 200.0),
|
||||
("file.save_ms", "save the 65 MB file (ms)", 500.0),
|
||||
("file.load_ms", "load the 65 MB file (ms)", 500.0),
|
||||
("autosave.ui_us", "autosave: time on the editing thread (µs)", 1000.0),
|
||||
("autosave.background_ms", "autosave the 65 MB file in the background (ms)", 2000.0),
|
||||
];
|
||||
|
||||
/// One crash-recovery autosave of `doc` as the app does it: an `Autosaver` in a scratch
|
||||
/// recovery folder, timing what the editing thread pays (the hand-off) apart from the
|
||||
/// background serialize + atomic write (temp file, flush to disk, rename).
|
||||
fn bench_autosave(doc: &anicraft_doc::Document) -> Value {
|
||||
use anicraft_engine::recovery::{Autosaver, Outcome, SessionLock};
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-bench-recovery-{}", std::process::id()));
|
||||
let Ok(mut saver) = SessionLock::acquire(&dir).and_then(Autosaver::start) else { return json!({"error": "no scratch folder"}) };
|
||||
let t = Instant::now();
|
||||
saver.write(doc.clone(), None);
|
||||
let ui_us = t.elapsed().as_secs_f64() * 1e6;
|
||||
let mut out = json!({"error": "timed out"});
|
||||
while t.elapsed().as_secs() < 120 {
|
||||
if let Some(o) = saver.poll().into_iter().next() {
|
||||
let background_ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
out = match o {
|
||||
Outcome::Written { stats, .. } => json!({
|
||||
"ui_us": round(ui_us), "background_ms": round(background_ms),
|
||||
"serialize_ms": round(stats.serialize_ms), "write_ms": round(stats.write_ms),
|
||||
"mb": round(stats.bytes as f64 / 1048576.0),
|
||||
}),
|
||||
Outcome::Failed { error, .. } => json!({"error": error}),
|
||||
Outcome::Cleared { .. } => out,
|
||||
};
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
saver.finish(None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
out
|
||||
}
|
||||
|
||||
/// Compares bench output with [`TIME_BUDGETS`]: one row per budget, and the ones missed.
|
||||
pub fn check_budgets(out: &Value) -> (Vec<Value>, Vec<String>) {
|
||||
let mut rows = Vec::new();
|
||||
@@ -287,6 +338,8 @@ pub fn bench(a: &Args) -> Result<String, String> {
|
||||
let _ = format::from_json(&json_text);
|
||||
});
|
||||
|
||||
let autosave = bench_autosave(&doc);
|
||||
|
||||
let eval_ms = avg_ms(48, |i| {
|
||||
let _ = evaluate(&doc, (i * 5) % frames.max(1));
|
||||
});
|
||||
@@ -332,6 +385,7 @@ pub fn bench(a: &Args) -> Result<String, String> {
|
||||
"document": {"layers": layers, "shapes_per_layer": shapes, "frames": frames, "element_instances": instances,
|
||||
"estimated_mb": round(document_bytes(&s.doc) as f64 / 1048576.0), "build_ms": round(build_ms)},
|
||||
"file": {"json_mb": round(json_text.len() as f64 / 1048576.0), "save_ms": round(save_ms), "load_ms": round(load_ms)},
|
||||
"autosave": autosave,
|
||||
"evaluate_ms_per_frame": round(eval_ms),
|
||||
"render_1080p_ms_per_frame": round(render_ms), "render_shapes_drawn": drawn,
|
||||
"render_zoom400_ms_per_frame": round(zoom_ms), "render_zoom400_culled": culled,
|
||||
@@ -472,7 +526,7 @@ mod tests {
|
||||
#[test]
|
||||
fn budget_check_reads_bench_output() {
|
||||
let mut out = json!({"edit_command_ms": 0.01, "undo_ms": 0.01, "snapshot_clone_us": 0.4, "evaluate_ms_per_frame": 1.5,
|
||||
"render_1080p_ms_per_frame": 20.0, "render_zoom400_ms_per_frame": 10.0, "hit_test_us": 50.0, "file": {"save_ms": 100.0}});
|
||||
"render_1080p_ms_per_frame": 20.0, "render_zoom400_ms_per_frame": 10.0, "hit_test_us": 50.0, "file": {"save_ms": 100.0}, "autosave": {"ui_us": 5.0, "background_ms": 300.0}});
|
||||
let (rows, missed) = check_budgets(&out);
|
||||
assert_eq!(rows.len(), TIME_BUDGETS.len());
|
||||
assert_eq!(missed, ["render 1080p (ms): 20 (budget 16.7)", "load the 65 MB file (ms): not measured"]);
|
||||
@@ -485,6 +539,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_folder_flag() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-cli-plugins-{}", std::process::id()));
|
||||
let argv: Vec<String> = ["--sample", "--plugins", dir.to_str().unwrap()].iter().map(|s| s.to_string()).collect();
|
||||
let a = Args::parse(&argv).unwrap();
|
||||
let s = session(&a, Some("--sample")).unwrap();
|
||||
// A folder that doesn't exist yet is the plug-ins folder, with nothing in it.
|
||||
assert_eq!(s.plugins.folder(), Some(dir.as_path()));
|
||||
assert!(s.plugins.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_and_errors() {
|
||||
assert!(run(&[]).unwrap().contains("USAGE"));
|
||||
|
||||
@@ -42,6 +42,30 @@ impl Easing {
|
||||
}
|
||||
}
|
||||
|
||||
/// The cubic Bézier `(x1, y1, x2, y2)` that draws this ease, as the Motion Editor's handles:
|
||||
/// exact for linear, the quad and cubic in/out eases and the classic slider; the two in-out
|
||||
/// polynomials (two curves joined at the middle) get their usual one-curve approximations.
|
||||
pub fn as_bezier(&self) -> (f32, f32, f32, f32) {
|
||||
const THIRD: f32 = 1.0 / 3.0;
|
||||
match *self {
|
||||
Easing::Linear => (THIRD, THIRD, 2.0 * THIRD, 2.0 * THIRD),
|
||||
// t² and t³ and their mirrors, with x(s) = s.
|
||||
Easing::QuadIn => (THIRD, 0.0, 2.0 * THIRD, THIRD),
|
||||
Easing::QuadOut => (THIRD, 2.0 * THIRD, 2.0 * THIRD, 1.0),
|
||||
Easing::CubicIn => (THIRD, 0.0, 2.0 * THIRD, 0.0),
|
||||
Easing::CubicOut => (THIRD, 1.0, 2.0 * THIRD, 1.0),
|
||||
Easing::QuadInOut => (0.45, 0.0, 0.55, 1.0),
|
||||
Easing::CubicInOut => (0.65, 0.0, 0.35, 1.0),
|
||||
Easing::Classic(strength) => {
|
||||
// The quadratic 2(1 − t)t·c + t², raised to a cubic.
|
||||
let s = if strength.is_finite() { strength.clamp(-100.0, 100.0) / 100.0 } else { 0.0 };
|
||||
let c = 0.5 + 0.5 * s;
|
||||
(THIRD, 2.0 * c * THIRD, 2.0 * THIRD, (2.0 * c + 1.0) * THIRD)
|
||||
}
|
||||
Easing::CubicBezier(a, b, c, d) => (a, b, c, d),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply(&self, t: f32) -> f32 {
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
match *self {
|
||||
@@ -168,6 +192,24 @@ mod tests {
|
||||
assert!(Easing::Classic(f32::INFINITY).apply(0.5).is_finite());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bezier_forms_draw_the_same_curves() {
|
||||
// Exact for everything but the two in-out polynomials.
|
||||
for e in [Easing::Linear, Easing::QuadIn, Easing::QuadOut, Easing::CubicIn, Easing::CubicOut, Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.2, 1.4, 0.6, -0.3)] {
|
||||
let (a, b, c, d) = e.as_bezier();
|
||||
let bez = Easing::CubicBezier(a, b, c, d);
|
||||
for i in 0..=20 {
|
||||
let t = i as f32 / 20.0;
|
||||
assert!((e.apply(t) - bez.apply(t)).abs() < 1e-3, "{e:?} at {t}");
|
||||
}
|
||||
}
|
||||
for e in [Easing::QuadInOut, Easing::CubicInOut] {
|
||||
let (a, b, c, d) = e.as_bezier();
|
||||
let bez = Easing::CubicBezier(a, b, c, d);
|
||||
assert!((0..=20).all(|i| (e.apply(i as f32 / 20.0) - bez.apply(i as f32 / 20.0)).abs() < 0.08), "{e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ease_in_is_slow_at_start() {
|
||||
assert!(Easing::QuadIn.apply(0.25) < 0.25);
|
||||
|
||||
@@ -136,6 +136,15 @@ pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_
|
||||
pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
|
||||
let idx = layer.keyframe_index_at(frame)?;
|
||||
let kf = layer.keyframes.get(idx)?;
|
||||
// A motion tween: its target follows the property curves; anything else on the key holds.
|
||||
if let Some(m) = &kf.motion {
|
||||
let Some(i) = m.target_index(&kf.elements).filter(|_| !m.tracks.is_empty()) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
let mut els = kf.elements.clone();
|
||||
if let Some(slot) = els.get_mut(i) {
|
||||
*slot = Arc::new(m.apply(slot, (frame - kf.start) as f32));
|
||||
}
|
||||
return Some((kf.start, Cow::Owned(els)));
|
||||
}
|
||||
let Some(tween) = kf.tween else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
let Some(next) = layer.keyframes.get(idx + 1) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
if next.start != kf.end() || frame == kf.start {
|
||||
|
||||
@@ -326,3 +326,70 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() {
|
||||
layer0(&mut d).keyframes[1] = Arc::new(k1b);
|
||||
assert_eq!(x(&d, 7), 1020.0);
|
||||
}
|
||||
|
||||
/// A 24-frame motion tween on one shape: X keyed at 0, 12 (ease in) and 23; alpha keyed at 23.
|
||||
fn motion_doc() -> Document {
|
||||
use crate::{MotionTween, Property};
|
||||
let mut d = Document::default();
|
||||
let mut k = Keyframe::new(0, 24);
|
||||
k.elements.push(Arc::new(shape_el(10, 0.0)));
|
||||
let mut m = MotionTween::new(ElementId(10));
|
||||
m.set_key(Property::X, 12, 120.0, 0.0);
|
||||
m.set_key(Property::X, 23, 120.0, 0.0);
|
||||
if let Some(t) = m.track_mut(Property::X) {
|
||||
t.keys[0].ease = Easing::QuadIn;
|
||||
}
|
||||
m.set_key(Property::Alpha, 23, 0.0, 100.0);
|
||||
k.motion = Some(m);
|
||||
// A classic tween on the same span is ignored: the motion tween wins.
|
||||
k.tween = Some(Tween::default());
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k)];
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
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)
|
||||
};
|
||||
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.
|
||||
let (x6, a6) = at(6);
|
||||
assert!((x6 - 30.0).abs() < 1e-3, "{x6}");
|
||||
assert!((a6 - (1.0 - 6.0 / 23.0)).abs() < 1e-5, "{a6}");
|
||||
// X holds on 12..23 while alpha keeps fading.
|
||||
let (x18, a18) = at(18);
|
||||
assert!((x18 - 120.0).abs() < 1e-3 && a18 < a6);
|
||||
assert_eq!(at(23).1, 0.0);
|
||||
// Y, scale and rotation were never keyed: they stay the element's own.
|
||||
let item = &evaluate(&d, 18).items[0];
|
||||
let dc = item.transform.decompose();
|
||||
assert!(dc.ty.abs() < 1e-4 && (dc.sx - 1.0).abs() < 1e-5 && dc.rotation.abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn motion_tweens_survive_a_file_round_trip_and_old_files_have_none() {
|
||||
let d = motion_doc();
|
||||
let json = serde_json::to_string(&d).unwrap();
|
||||
let back: Document = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, d);
|
||||
assert!(back.timeline(0).layers[0].keyframes[0].motion.is_some());
|
||||
// A keyframe written before motion tweens existed loads with none.
|
||||
let old: Keyframe = serde_json::from_str(r#"{"start": 0, "duration": 3}"#).unwrap();
|
||||
assert!(old.motion.is_none());
|
||||
// Loading repairs a hostile tween and drops a classic tween beside it.
|
||||
let mut d2 = d.clone();
|
||||
let k = layer0(&mut d2).keyframe_mut(0).unwrap();
|
||||
if let Some(m) = k.motion.as_mut() {
|
||||
m.tracks[0].keys.reverse();
|
||||
m.tracks[0].keys[0].value = f32::INFINITY;
|
||||
}
|
||||
d2.sanitize();
|
||||
let k = &d2.timeline(0).layers[0].keyframes[0];
|
||||
assert!(k.tween.is_none() && k.motion.as_ref().is_some_and(crate::MotionTween::is_sane));
|
||||
for f in 0..30 {
|
||||
assert!(evaluate(&d2, f).items.iter().all(|i| i.transform.is_finite()));
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,14 @@ mod bitmap;
|
||||
mod filter;
|
||||
mod easing;
|
||||
mod eval;
|
||||
pub mod motion;
|
||||
pub mod path_table;
|
||||
pub mod sample;
|
||||
|
||||
pub use filter::{Filter, MAX_BLUR, MAX_QUALITY};
|
||||
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png};
|
||||
pub use easing::Easing;
|
||||
pub use motion::{MotionTween, Property, PropertyKey, Props, Track};
|
||||
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_scene};
|
||||
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
|
||||
@@ -491,19 +493,23 @@ pub struct Keyframe {
|
||||
pub elements: Vec<Arc<Element>>,
|
||||
#[serde(default)]
|
||||
pub tween: Option<Tween>,
|
||||
/// A motion tween over this span (ADR 0016). A span has a classic or shape tween (`tween`)
|
||||
/// or a motion tween, never both; commands keep it so, and a motion tween wins.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub motion: Option<MotionTween>,
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
impl PartialEq for Keyframe {
|
||||
fn eq(&self, o: &Keyframe) -> bool {
|
||||
self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.label == o.label && arcs_eq(&self.elements, &o.elements)
|
||||
self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.label == o.label && arcs_eq(&self.elements, &o.elements)
|
||||
}
|
||||
}
|
||||
|
||||
impl Keyframe {
|
||||
pub fn new(start: u32, duration: u32) -> Self {
|
||||
Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, label: String::new() }
|
||||
Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, label: String::new() }
|
||||
}
|
||||
/// Mutable access to the elements whose ids satisfy `pick`, cloning only those.
|
||||
pub fn elements_mut_where(&mut self, mut pick: impl FnMut(ElementId) -> bool) -> Vec<&mut Element> {
|
||||
@@ -618,6 +624,16 @@ impl Layer {
|
||||
/// Restores invariants after edits: sorted, durations ≥ 1, no overlaps. Touches (and so
|
||||
/// un-shares) only keyframes whose duration actually changes.
|
||||
pub fn normalize(&mut self) {
|
||||
// A loaded motion tween is repaired, and it replaces a classic tween on the same span.
|
||||
for i in 0..self.keyframes.len() {
|
||||
let bad = self.keyframes.get(i).is_some_and(|k| k.motion.as_ref().is_some_and(|m| !m.is_sane() || k.tween.is_some()));
|
||||
if bad && let Some(k) = self.keyframe_mut(i) {
|
||||
k.tween = None;
|
||||
if let Some(m) = k.motion.as_mut() {
|
||||
m.sanitize();
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self.keyframes.is_sorted_by_key(|k| k.start) {
|
||||
self.keyframes.sort_by_key(|k| k.start);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
//! Motion tweens (ADR 0016): one object's properties, each on its own curve.
|
||||
//!
|
||||
//! 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
|
||||
//! 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
|
||||
//! element and a frame offset to the element as it looks then.
|
||||
|
||||
use crate::{Element, ElementId, Easing};
|
||||
use anicraft_geom::{Affine, Decomposed};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Most keys one track keeps (files and commands alike).
|
||||
pub const MAX_KEYS: usize = 10_000;
|
||||
|
||||
/// A property a motion tween animates. Values are in the units the Motion Editor shows:
|
||||
/// pixels, percent and degrees.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Property {
|
||||
/// Registration point, stage pixels.
|
||||
X,
|
||||
Y,
|
||||
/// Percent (100 = natural size; negative flips).
|
||||
ScaleX,
|
||||
ScaleY,
|
||||
/// Degrees, clockwise on screen; not wrapped, so 0 → 720 turns twice.
|
||||
Rotation,
|
||||
/// Degrees of horizontal skew, within ±89.
|
||||
Skew,
|
||||
/// Colour effect: opacity and tint amount, percent.
|
||||
Alpha,
|
||||
Tint,
|
||||
}
|
||||
|
||||
impl Property {
|
||||
pub const ALL: [Property; 8] = [Property::X, Property::Y, Property::ScaleX, Property::ScaleY, Property::Rotation, Property::Skew, Property::Alpha, Property::Tint];
|
||||
|
||||
/// The name used in files and commands (`x`, `scale_x`, `alpha`…).
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Property::X => "x",
|
||||
Property::Y => "y",
|
||||
Property::ScaleX => "scale_x",
|
||||
Property::ScaleY => "scale_y",
|
||||
Property::Rotation => "rotation",
|
||||
Property::Skew => "skew",
|
||||
Property::Alpha => "alpha",
|
||||
Property::Tint => "tint",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Property::X => "X",
|
||||
Property::Y => "Y",
|
||||
Property::ScaleX => "Scale X",
|
||||
Property::ScaleY => "Scale Y",
|
||||
Property::Rotation => "Rotation",
|
||||
Property::Skew => "Skew",
|
||||
Property::Alpha => "Alpha",
|
||||
Property::Tint => "Tint",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unit(self) -> &'static str {
|
||||
match self {
|
||||
Property::X | Property::Y => "px",
|
||||
Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Tint => "%",
|
||||
Property::Rotation | Property::Skew => "°",
|
||||
}
|
||||
}
|
||||
|
||||
/// The Motion Editor's groups: Position, Transform, Colour effect.
|
||||
pub fn group(self) -> &'static str {
|
||||
match self {
|
||||
Property::X | Property::Y => "Position",
|
||||
Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => "Transform",
|
||||
Property::Alpha | Property::Tint => "Colour effect",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(s: &str) -> Option<Property> {
|
||||
let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_");
|
||||
let s = match s.as_str() {
|
||||
"scalex" => "scale_x",
|
||||
"scaley" => "scale_y",
|
||||
"rotate" => "rotation",
|
||||
"opacity" => "alpha",
|
||||
other => other,
|
||||
};
|
||||
Property::ALL.into_iter().find(|p| p.key() == s)
|
||||
}
|
||||
|
||||
/// Values a key may hold (commands reject others; files are clamped into it).
|
||||
pub fn range(self) -> std::ops::RangeInclusive<f32> {
|
||||
match self {
|
||||
Property::X | Property::Y => -1_000_000.0..=1_000_000.0,
|
||||
Property::ScaleX | Property::ScaleY => -1_000_000.0..=1_000_000.0,
|
||||
Property::Rotation => -100_000.0..=100_000.0,
|
||||
Property::Skew => -89.0..=89.0,
|
||||
Property::Alpha | Property::Tint => 0.0..=100.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
Property::ALL.iter().position(|p| *p == self).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn is_transform(self) -> bool {
|
||||
!matches!(self, Property::Alpha | Property::Tint)
|
||||
}
|
||||
|
||||
fn clamp(self, v: f32) -> f32 {
|
||||
let r = self.range();
|
||||
if v.is_finite() { v.clamp(*r.start(), *r.end()) } else { 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Every property's value, indexed like [`Property::ALL`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Props(pub [f32; 8]);
|
||||
|
||||
impl Props {
|
||||
/// An element's own values.
|
||||
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])
|
||||
}
|
||||
pub fn get(&self, p: Property) -> f32 {
|
||||
self.0.get(p.index()).copied().unwrap_or(0.0)
|
||||
}
|
||||
pub fn set(&mut self, p: Property, v: f32) {
|
||||
if let Some(x) = self.0.get_mut(p.index()) {
|
||||
*x = v;
|
||||
}
|
||||
}
|
||||
/// The transform these values describe.
|
||||
pub fn transform(&self) -> Affine {
|
||||
// Scale never reaches zero (that would collapse the artwork and lose its rotation).
|
||||
let scale = |pct: f32| {
|
||||
let s = Property::ScaleX.clamp(pct) / 100.0;
|
||||
if s.abs() < 1e-4 { 1e-4f32.copysign(s) } else { s }
|
||||
};
|
||||
Decomposed {
|
||||
tx: Property::X.clamp(self.get(Property::X)),
|
||||
ty: Property::Y.clamp(self.get(Property::Y)),
|
||||
sx: scale(self.get(Property::ScaleX)),
|
||||
sy: scale(self.get(Property::ScaleY)),
|
||||
rotation: Property::Rotation.clamp(self.get(Property::Rotation)).to_radians(),
|
||||
skew: Property::Skew.clamp(self.get(Property::Skew)).to_radians().tan(),
|
||||
}
|
||||
.compose()
|
||||
}
|
||||
}
|
||||
|
||||
/// A property keyframe.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PropertyKey {
|
||||
/// Frames from the span's first frame.
|
||||
pub frame: u32,
|
||||
pub value: f32,
|
||||
/// How the value travels from this key to the next one.
|
||||
#[serde(default, skip_serializing_if = "is_linear")]
|
||||
pub ease: Easing,
|
||||
}
|
||||
|
||||
fn is_linear(e: &Easing) -> bool {
|
||||
*e == Easing::Linear
|
||||
}
|
||||
|
||||
/// One property's keys, sorted by frame, one per frame.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Track {
|
||||
pub property: Property,
|
||||
#[serde(default)]
|
||||
pub keys: Vec<PropertyKey>,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
/// The value at `frame` (fractional frames sample the curve between frames): the first
|
||||
/// key's value before it, the last key's after it, the segment's ease in between.
|
||||
pub fn value_at(&self, frame: f32) -> Option<f32> {
|
||||
let first = self.keys.first()?;
|
||||
let last = self.keys.last()?;
|
||||
if !frame.is_finite() || frame <= first.frame as f32 {
|
||||
return Some(first.value);
|
||||
}
|
||||
if frame >= last.frame as f32 {
|
||||
return Some(last.value);
|
||||
}
|
||||
// The segment [a, b) holding `frame`: binary search on the key frames.
|
||||
let i = self.keys.partition_point(|k| k.frame as f32 <= frame);
|
||||
let (a, b) = (self.keys.get(i.checked_sub(1)?)?, self.keys.get(i)?);
|
||||
let span = (b.frame - a.frame).max(1) as f32;
|
||||
let t = a.ease.apply((frame - a.frame as f32) / span);
|
||||
Some(a.value + (b.value - a.value) * t)
|
||||
}
|
||||
|
||||
/// Index of the key at exactly `frame`.
|
||||
pub fn key_at(&self, frame: u32) -> Option<usize> {
|
||||
self.keys.binary_search_by_key(&frame, |k| k.frame).ok()
|
||||
}
|
||||
|
||||
/// Index of the key starting the segment that holds `frame` (`None` at or after the last
|
||||
/// key, where no segment follows).
|
||||
pub fn segment_at(&self, frame: u32) -> Option<usize> {
|
||||
let i = self.keys.partition_point(|k| k.frame <= frame).checked_sub(1)?;
|
||||
(i + 1 < self.keys.len()).then_some(i)
|
||||
}
|
||||
|
||||
/// Sets the key at `frame` (keeping its ease), or adds one that eases like the segment it
|
||||
/// splits.
|
||||
pub fn set(&mut self, frame: u32, value: f32) {
|
||||
let value = self.property.clamp(value);
|
||||
match self.keys.binary_search_by_key(&frame, |k| k.frame) {
|
||||
Ok(i) => {
|
||||
if let Some(k) = self.keys.get_mut(i) {
|
||||
k.value = value;
|
||||
}
|
||||
}
|
||||
Err(i) => {
|
||||
let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or(Easing::Linear, |k| k.ease);
|
||||
if self.keys.len() < MAX_KEYS {
|
||||
self.keys.insert(i, PropertyKey { frame, value, ease });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize(&mut self) {
|
||||
self.keys.retain(|k| k.value.is_finite());
|
||||
for k in &mut self.keys {
|
||||
k.value = self.property.clamp(k.value);
|
||||
}
|
||||
if !self.keys.is_sorted_by_key(|k| k.frame) {
|
||||
self.keys.sort_by_key(|k| k.frame);
|
||||
}
|
||||
self.keys.dedup_by_key(|k| k.frame);
|
||||
self.keys.truncate(MAX_KEYS);
|
||||
}
|
||||
|
||||
fn is_sane(&self) -> bool {
|
||||
self.keys.len() <= MAX_KEYS && self.keys.windows(2).all(|w| matches!(w, [a, b] if a.frame < b.frame)) && self.keys.iter().all(|k| self.property.range().contains(&k.value))
|
||||
}
|
||||
}
|
||||
|
||||
/// A motion tween on a keyframe span (see the module docs).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MotionTween {
|
||||
/// The object it animates. When no element has this id but the keyframe holds exactly one
|
||||
/// element, that one is the target (so edits that replace the object keep its motion).
|
||||
pub target: ElementId,
|
||||
/// At most one per property, in [`Property::ALL`] order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub tracks: Vec<Track>,
|
||||
}
|
||||
|
||||
impl MotionTween {
|
||||
pub fn new(target: ElementId) -> MotionTween {
|
||||
MotionTween { target, tracks: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn track(&self, p: Property) -> Option<&Track> {
|
||||
self.tracks.iter().find(|t| t.property == p)
|
||||
}
|
||||
|
||||
pub fn track_mut(&mut self, p: Property) -> Option<&mut Track> {
|
||||
self.tracks.iter_mut().find(|t| t.property == p)
|
||||
}
|
||||
|
||||
/// Index of the target among a keyframe's elements.
|
||||
pub fn target_index(&self, elements: &[Arc<Element>]) -> Option<usize> {
|
||||
elements.iter().position(|e| e.id == self.target).or((elements.len() == 1).then_some(0))
|
||||
}
|
||||
|
||||
/// Every property's value at `frame` frames into the span, for an object whose own values
|
||||
/// are `base`.
|
||||
pub fn props_at(&self, base: &Props, frame: f32) -> Props {
|
||||
let mut out = *base;
|
||||
for t in &self.tracks {
|
||||
if let Some(v) = t.value_at(frame) {
|
||||
out.set(t.property, v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The target as it looks `frame` frames into the span. Untracked properties keep the
|
||||
/// base's exact transform and colour effect.
|
||||
pub fn apply(&self, base: &Element, frame: f32) -> Element {
|
||||
let mut el = base.clone();
|
||||
if self.tracks.is_empty() {
|
||||
return el;
|
||||
}
|
||||
let props = self.props_at(&Props::of(base), frame);
|
||||
if self.tracks.iter().any(|t| t.property.is_transform()) {
|
||||
let m = props.transform();
|
||||
if m.is_finite() {
|
||||
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);
|
||||
}
|
||||
el
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
if self.track(p).is_none() {
|
||||
let mut keys = Vec::new();
|
||||
if frame > 0 {
|
||||
keys.push(PropertyKey { frame: 0, value: p.clamp(base), ease: Easing::Linear });
|
||||
}
|
||||
let at = Property::ALL.iter().position(|x| *x == p).unwrap_or(0);
|
||||
let pos = self.tracks.partition_point(|t| Property::ALL.iter().position(|x| *x == t.property).unwrap_or(0) < at);
|
||||
self.tracks.insert(pos, Track { property: p, keys });
|
||||
}
|
||||
if let Some(t) = self.track_mut(p) {
|
||||
t.set(frame, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes property `p`'s key at `frame`; a track left with no keys goes. Whether a key was
|
||||
/// there.
|
||||
pub fn remove_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);
|
||||
self.tracks.retain(|t| !t.keys.is_empty());
|
||||
true
|
||||
}
|
||||
|
||||
/// Frames (from the span's start) that hold a key of any property, sorted.
|
||||
pub fn key_frames(&self) -> Vec<u32> {
|
||||
let mut v: Vec<u32> = self.tracks.iter().flat_map(|t| t.keys.iter().map(|k| k.frame)).collect();
|
||||
v.sort_unstable();
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
/// The part of this tween from `frame` on, re-based to start there (splitting a span in
|
||||
/// two keeps the motion: each track gets a key at the cut with the value it had there).
|
||||
pub fn split_at(&self, frame: u32) -> MotionTween {
|
||||
let tracks = self
|
||||
.tracks
|
||||
.iter()
|
||||
.filter_map(|t| {
|
||||
let v = t.value_at(frame as f32)?;
|
||||
let ease = t.segment_at(frame).and_then(|i| t.keys.get(i)).map_or(Easing::Linear, |k| k.ease);
|
||||
let mut keys = vec![PropertyKey { frame: 0, value: v, ease }];
|
||||
keys.extend(t.keys.iter().filter(|k| k.frame > frame).map(|k| PropertyKey { frame: k.frame - frame, ..*k }));
|
||||
Some(Track { property: t.property, keys })
|
||||
})
|
||||
.collect();
|
||||
MotionTween { target: self.target, tracks }
|
||||
}
|
||||
|
||||
/// Whether loading must repair it (unsorted or duplicate keys, values out of range,
|
||||
/// duplicate or empty tracks).
|
||||
pub fn is_sane(&self) -> bool {
|
||||
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()))
|
||||
}
|
||||
|
||||
/// Repairs a loaded tween.
|
||||
pub fn sanitize(&mut self) {
|
||||
for t in &mut self.tracks {
|
||||
t.sanitize();
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{ColorEffect, ElementKind, Shape};
|
||||
use anicraft_geom::Path;
|
||||
|
||||
fn el(id: u64, x: f32, y: f32) -> Element {
|
||||
Element {
|
||||
id: ElementId(id),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(x, y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), crate::Paint::Solid(crate::Rgba::BLACK))),
|
||||
}
|
||||
}
|
||||
|
||||
fn track(p: Property, keys: &[(u32, f32, Easing)]) -> Track {
|
||||
Track { property: p, keys: keys.iter().map(|&(frame, value, ease)| PropertyKey { frame, value, ease }).collect() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_track_holds_before_and_after_and_eases_between() {
|
||||
let t = track(Property::X, &[(4, 100.0, Easing::Linear), (8, 200.0, Easing::QuadIn), (12, 0.0, Easing::Linear)]);
|
||||
assert_eq!(t.value_at(0.0), Some(100.0));
|
||||
assert_eq!(t.value_at(4.0), Some(100.0));
|
||||
assert_eq!(t.value_at(6.0), Some(150.0), "linear midpoint");
|
||||
// QuadIn on 8..12: a quarter of the way there at half time.
|
||||
assert_eq!(t.value_at(10.0), Some(200.0 - 200.0 * 0.25));
|
||||
assert_eq!(t.value_at(12.0), Some(0.0));
|
||||
assert_eq!(t.value_at(99.0), Some(0.0));
|
||||
assert_eq!(t.value_at(f32::NAN), Some(100.0));
|
||||
assert_eq!(track(Property::X, &[]).value_at(3.0), None);
|
||||
assert_eq!(t.segment_at(3), None);
|
||||
assert_eq!(t.segment_at(4), Some(0));
|
||||
assert_eq!(t.segment_at(11), Some(1));
|
||||
assert_eq!(t.segment_at(12), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_bezier_ease_matches_its_analytic_curve() {
|
||||
// Control points (0, 0) (0, 1) (1, 0) (1, 1): x(s) = 3s² − 2s³, y(s) = 3s(1 − s)² + s³;
|
||||
// the value at frame 10·x(s) must be 100·y(s).
|
||||
let e = Easing::CubicBezier(0.0, 1.0, 1.0, 0.0);
|
||||
let t = track(Property::Y, &[(0, 0.0, e), (10, 100.0, Easing::Linear)]);
|
||||
for s in [0.1f32, 0.3, 0.5, 0.8] {
|
||||
let bez = |p1: f32, p2: f32| 3.0 * (1.0 - s) * (1.0 - s) * s * p1 + 3.0 * (1.0 - s) * s * s * p2 + s * s * s;
|
||||
let (x, y) = (bez(0.0, 1.0), bez(1.0, 0.0));
|
||||
let v = t.value_at(x * 10.0).unwrap_or(f32::NAN);
|
||||
assert!((v - y * 100.0).abs() < 0.05, "s {s}: {v} vs {}", y * 100.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untracked_properties_keep_the_base_exactly() {
|
||||
let base = Element { transform: Affine::translate(5.0, 6.0).mul(&Affine::rotate(0.3)).mul(&Affine::scale(2.0, 0.5)), ..el(1, 0.0, 0.0) };
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
assert_eq!(m.apply(&base, 3.0), base, "no tracks: the base itself");
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_key_of_a_property_pins_the_span_start_to_the_base() {
|
||||
let base = el(1, 50.0, 20.0);
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
m.set_key(Property::X, 10, 150.0, 50.0);
|
||||
assert_eq!(m.track(Property::X).map(|t| t.keys.len()), Some(2));
|
||||
let x = |f: f32| m.apply(&base, f).transform.translation().x;
|
||||
assert!((x(0.0) - 50.0).abs() < 1e-3 && (x(5.0) - 100.0).abs() < 1e-3 && (x(10.0) - 150.0).abs() < 1e-3);
|
||||
// Y untouched, and a key added later in a segment eases like the segment it splits.
|
||||
assert!((m.apply(&base, 5.0).transform.translation().y - 20.0).abs() < 1e-3);
|
||||
if let Some(t) = m.track_mut(Property::X) {
|
||||
t.keys[0].ease = Easing::CubicOut;
|
||||
}
|
||||
m.set_key(Property::X, 4, 70.0, 50.0);
|
||||
assert_eq!(m.track(Property::X).map(|t| t.keys[1].ease), Some(Easing::CubicOut));
|
||||
assert!(m.remove_key(Property::X, 4) && !m.remove_key(Property::X, 4));
|
||||
assert!(m.remove_key(Property::X, 0) && m.remove_key(Property::X, 10));
|
||||
assert!(m.tracks.is_empty(), "an emptied track goes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_and_scale_compose_like_the_element_transform() {
|
||||
let base = el(1, 10.0, 10.0);
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
m.set_key(Property::Rotation, 8, 360.0, 0.0);
|
||||
m.set_key(Property::ScaleX, 8, 300.0, 100.0);
|
||||
let d = m.apply(&base, 4.0).transform.decompose();
|
||||
assert!((d.rotation.to_degrees() - 180.0).abs() < 1e-2 || (d.rotation.to_degrees() + 180.0).abs() < 1e-2, "half of a whole turn");
|
||||
assert!((d.sx - 2.0).abs() < 1e-4 && (d.sy - 1.0).abs() < 1e-4);
|
||||
assert!((d.tx - 10.0).abs() < 1e-4);
|
||||
// Scale through zero never collapses the artwork.
|
||||
m.set_key(Property::ScaleY, 8, -100.0, 100.0);
|
||||
assert!(m.apply(&base, 4.0).transform.determinant().abs() > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splitting_keeps_the_motion() {
|
||||
let base = el(1, 0.0, 0.0);
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
m.set_key(Property::X, 10, 100.0, 0.0);
|
||||
m.set_key(Property::Y, 6, 60.0, 0.0);
|
||||
let tail = m.split_at(4);
|
||||
let tail_base = m.apply(&base, 4.0);
|
||||
for f in 4..=12u32 {
|
||||
let a = m.apply(&base, f as f32).transform.translation();
|
||||
let b = tail.apply(&tail_base, (f - 4) as f32).transform.translation();
|
||||
assert!((a.x - b.x).abs() < 1e-3 && (a.y - b.y).abs() < 1e-3, "frame {f}: {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_target_falls_back_to_a_sole_element() {
|
||||
let m = MotionTween::new(ElementId(9));
|
||||
assert_eq!(m.target_index(&[Arc::new(el(1, 0.0, 0.0))]), Some(0));
|
||||
assert_eq!(m.target_index(&[Arc::new(el(1, 0.0, 0.0)), Arc::new(el(9, 0.0, 0.0))]), Some(1));
|
||||
assert_eq!(m.target_index(&[Arc::new(el(1, 0.0, 0.0)), Arc::new(el(2, 0.0, 0.0))]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_repairs_a_hostile_tween() {
|
||||
let mut m = MotionTween {
|
||||
target: ElementId(1),
|
||||
tracks: vec![
|
||||
track(Property::Alpha, &[(5, 500.0, Easing::Linear), (1, f32::NAN, Easing::Linear), (2, 10.0, Easing::Linear), (2, 20.0, Easing::Linear)]),
|
||||
track(Property::X, &[(0, 1.0, Easing::Linear)]),
|
||||
track(Property::X, &[(0, 2.0, Easing::Linear)]),
|
||||
track(Property::Y, &[]),
|
||||
],
|
||||
};
|
||||
assert!(!m.is_sane());
|
||||
m.sanitize();
|
||||
assert!(m.is_sane());
|
||||
assert_eq!(m.tracks.iter().map(|t| t.property).collect::<Vec<_>>(), vec![Property::X, Property::Alpha]);
|
||||
assert_eq!(m.track(Property::Alpha).map(|t| t.keys.iter().map(|k| (k.frame, k.value)).collect::<Vec<_>>()), Some(vec![(2, 10.0), (5, 100.0)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
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_eq!(Property::from_key("Scale X"), Some(Property::ScaleX));
|
||||
assert_eq!(Property::from_key("nope"), None);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ anicraft-render.workspace = true
|
||||
anicraft-xfl.workspace = true
|
||||
anicraft-svg.workspace = true
|
||||
anicraft-text.workspace = true
|
||||
anicraft-plugins.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
@@ -23,6 +24,8 @@ gif.workspace = true
|
||||
[dev-dependencies]
|
||||
# Decodes exported sheets in tests (already in the tree through the renderer).
|
||||
png.workspace = true
|
||||
# Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception).
|
||||
wat = "1.228"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -521,7 +521,7 @@ fn arrange_step(s: &mut Session, forward: bool) -> Result<Value> {
|
||||
|
||||
// ----- symbols ----------------------------------------------------------------------------
|
||||
|
||||
fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("select something to convert".into()));
|
||||
|
||||
@@ -145,6 +145,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
info["imported"] = json!(path.display().to_string());
|
||||
info["report"] = json!(report.summary());
|
||||
info["skipped"] = json!(report.skipped);
|
||||
info["missing_fonts"] = json!(report.missing_fonts);
|
||||
return Ok(info);
|
||||
}
|
||||
let doc = format::load(&path)?;
|
||||
|
||||
@@ -142,6 +142,9 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let new = *remap.entry(old).or_insert_with(|| ElementId(s.doc.alloc_id()));
|
||||
Arc::make_mut(e).id = new;
|
||||
}
|
||||
if let Some(m) = k.motion.as_mut() {
|
||||
m.target = *remap.entry(m.target).or_insert_with(|| ElementId(s.doc.alloc_id()));
|
||||
}
|
||||
keys.push(Arc::new(k));
|
||||
}
|
||||
let Some(layer) = s.doc.timeline_mut(s.scene).layers.get_mut(row).map(Arc::make_mut) else { continue };
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Motion tweens (ADR 0016): creating one on a span, property keyframes, per-segment eases,
|
||||
//! and auto-keying edits made to the tweened object.
|
||||
//!
|
||||
//! Auto-key works for every command without the commands knowing: when a command asks for the
|
||||
//! keyframe to edit ([`Session::editable_keyframe`]) and the playhead is inside a motion tween,
|
||||
//! [`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).
|
||||
|
||||
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 serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("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", false, info),
|
||||
]
|
||||
}
|
||||
|
||||
/// A command editing a motion tween's target (see the module docs).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct MotionEdit {
|
||||
layer: LayerId,
|
||||
/// The span's first frame and the playhead's offset into it.
|
||||
start: u32,
|
||||
offset: u32,
|
||||
target: ElementId,
|
||||
/// The target as the command found it (at the playhead), and its base.
|
||||
before: Element,
|
||||
base: Element,
|
||||
}
|
||||
|
||||
/// Starts an edit of the motion tween on `kf` at `frame`: the target is replaced by how it
|
||||
/// looks there. `None` when `kf` has no motion tween (or no target).
|
||||
pub(crate) fn begin_edit(layer: LayerId, kf: &mut Keyframe, frame: u32) -> Option<MotionEdit> {
|
||||
let m = kf.motion.as_ref()?;
|
||||
let i = m.target_index(&kf.elements)?;
|
||||
let offset = frame.checked_sub(kf.start)?;
|
||||
let base = (**kf.elements.get(i)?).clone();
|
||||
let before = m.apply(&base, offset as f32);
|
||||
if before != base
|
||||
&& let Some(slot) = kf.elements.get_mut(i)
|
||||
{
|
||||
*slot = Arc::new(before.clone());
|
||||
}
|
||||
Some(MotionEdit { layer, start: kf.start, offset, target: base.id, before, base })
|
||||
}
|
||||
|
||||
/// Turns what a command changed on the target into property keys at the playhead, and puts
|
||||
/// 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(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 };
|
||||
let Some(m) = kf.motion.as_mut() else { return };
|
||||
m.target = e.target;
|
||||
let (now_dec, was_dec) = (Props::of(&after), Props::of(&e.before));
|
||||
let base_props = Props::of(&e.base);
|
||||
// The values the curves give here (rotation unwrapped: a key may hold 540°).
|
||||
let was = m.props_at(&base_props, e.offset as f32);
|
||||
let mut new_base = base_props;
|
||||
let (mut base_xf, mut base_color) = (false, false);
|
||||
for p in Property::ALL {
|
||||
let mut d = now_dec.get(p) - was_dec.get(p);
|
||||
if p == Property::Rotation {
|
||||
// The turn the edit made, the short way round.
|
||||
d = (d + 180.0).rem_euclid(360.0) - 180.0;
|
||||
}
|
||||
if !d.is_finite() || d.abs() <= 1e-4 {
|
||||
continue;
|
||||
}
|
||||
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) {
|
||||
base_color = true;
|
||||
} else {
|
||||
base_xf = true;
|
||||
}
|
||||
} else {
|
||||
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 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) {
|
||||
(true, true) => base.transform,
|
||||
(true, false) => new_base.transform(),
|
||||
(false, _) => e.base.transform,
|
||||
};
|
||||
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 },
|
||||
};
|
||||
if let Some(slot) = kf.elements.get_mut(idx) {
|
||||
*slot = Arc::new(base);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let Some(i) = layer.keyframe_index_at(frame) else { return false };
|
||||
let Some(kf) = layer.keyframe_mut(i) else { return false };
|
||||
if frame <= kf.start {
|
||||
return kf.motion.is_some();
|
||||
}
|
||||
let offset = frame - kf.start;
|
||||
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);
|
||||
for p in Property::ALL {
|
||||
m.set_key(p, offset, now.get(p), base.get(p));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The base as it looks on the span's first frame: what a span keeps when its motion tween is
|
||||
/// removed or replaced by another kind of tween.
|
||||
pub(crate) fn bake_first_frame(kf: &mut Keyframe) {
|
||||
let Some(m) = kf.motion.take() else { return };
|
||||
if let Some(i) = m.target_index(&kf.elements)
|
||||
&& let Some(slot) = kf.elements.get_mut(i)
|
||||
{
|
||||
let first = m.apply(slot, 0.0);
|
||||
if first != **slot {
|
||||
*slot = Arc::new(first);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create Motion Tween: the span at the frame tweens its object property by property. Several
|
||||
/// objects become one graphic symbol first (as Animate offers), a one-frame span grows to a
|
||||
/// second, and a classic or shape tween on the span is replaced.
|
||||
pub(crate) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let lid = lid.unwrap_or(s.layer);
|
||||
let (start, ids) = {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
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()));
|
||||
}
|
||||
let k = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
if let Some(m) = &k.motion {
|
||||
return Ok(json!({"motion": k.start, "target": m.target.0, "frames": k.duration, "converted": false}));
|
||||
}
|
||||
if k.elements.is_empty() {
|
||||
return Err(EngineError::State("there is nothing on this keyframe to tween: draw or place something first".into()));
|
||||
}
|
||||
(k.start, k.elements.iter().map(|e| e.id).collect::<Vec<_>>())
|
||||
};
|
||||
let converted = ids.len() > 1;
|
||||
if converted {
|
||||
// A motion tween moves one object: the key's artwork becomes one instance.
|
||||
let (layer, frame, sel) = (s.layer, s.frame, s.selection.clone());
|
||||
let name = format!("Tween {}", s.doc.library.len() + 1);
|
||||
s.layer = lid;
|
||||
s.frame = start;
|
||||
s.selection = ids;
|
||||
let r = crate::cmds_draw::convert_to_symbol(s, &json!({"name": name}));
|
||||
s.frame = frame;
|
||||
if layer != lid {
|
||||
s.layer = layer;
|
||||
s.selection = sel;
|
||||
}
|
||||
r?;
|
||||
}
|
||||
let seconds = (s.doc.stage.fps.round() as u32).clamp(2, 240);
|
||||
let layer = s.layer_mut(Some(lid))?;
|
||||
let i = layer.keyframe_starting_at(start).ok_or_else(|| EngineError::State("the keyframe went away".into()))?;
|
||||
let k = layer.keyframe_mut(i).ok_or_else(|| EngineError::State("the keyframe went away".into()))?;
|
||||
let target = k.elements.first().map(|e| e.id).ok_or_else(|| EngineError::State("there is nothing on this keyframe to tween".into()))?;
|
||||
k.tween = None;
|
||||
k.motion = Some(MotionTween::new(target));
|
||||
// A single frame has no room to move in: it becomes a one-second span.
|
||||
if k.duration == 1 {
|
||||
for _ in 1..seconds {
|
||||
if crate::cmds_timeline::insert_frame_at(layer, start).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let frames = layer.keyframe_starting_at(start).and_then(|i| layer.keyframes.get(i)).map_or(1, |k| k.duration);
|
||||
Ok(json!({"motion": start, "target": target.0, "frames": frames, "converted": converted}))
|
||||
}
|
||||
|
||||
/// The motion tween covering the target frame, its keyframe and the frame's offset into it.
|
||||
fn motion_span<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Keyframe, u32)> {
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let layer = s.layer_mut(lid)?;
|
||||
let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
let kf = layer.keyframe_mut(i).ok_or_else(|| EngineError::State("keyframe vanished".into()))?;
|
||||
if kf.motion.is_none() {
|
||||
return Err(EngineError::State(format!("frame {} is not in a motion tween; select the span and use Insert › Create Motion Tween", frame + 1)));
|
||||
}
|
||||
let offset = frame - kf.start;
|
||||
Ok((kf, offset))
|
||||
}
|
||||
|
||||
fn property(p: &Value) -> Result<Option<Property>> {
|
||||
match opt_str(p, "property")? {
|
||||
None => Ok(None),
|
||||
Some(k) => Property::from_key(k).map(Some).ok_or_else(|| {
|
||||
let all: Vec<&str> = Property::ALL.iter().map(|p| p.key()).collect();
|
||||
EngineError::Param(format!("unknown property '{k}' ({})", all.join(", ")))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let prop = property(p)?.ok_or_else(|| EngineError::Param("param 'property' is required".into()))?;
|
||||
let value = f32_req(p, "value")?;
|
||||
let r = prop.range();
|
||||
if !r.contains(&value) {
|
||||
return Err(EngineError::Param(format!("{} must be between {} and {} {}", prop.label(), r.start(), r.end(), prop.unit())));
|
||||
}
|
||||
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 m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
m.set_key(prop, offset, value, base.get(prop));
|
||||
Ok(json!({"property": prop.key(), "frame": start + offset, "value": value}))
|
||||
}
|
||||
|
||||
fn remove_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let only = property(p)?;
|
||||
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();
|
||||
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}))
|
||||
}
|
||||
|
||||
fn set_ease(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let easing = opt_easing(p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
|
||||
let only = property(p)?;
|
||||
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 mut set = Vec::new();
|
||||
for t in m.tracks.iter_mut().filter(|t| only.is_none_or(|o| o == t.property)) {
|
||||
if let Some(k) = t.segment_at(offset).and_then(|i| t.keys.get_mut(i)) {
|
||||
k.ease = easing;
|
||||
set.push(t.property.key());
|
||||
}
|
||||
}
|
||||
if set.is_empty() {
|
||||
return Err(EngineError::State(format!("frame {} is not between two property keyframes{}", start + offset + 1, only.map_or_else(String::new, |o| format!(" of {}", o.label())))));
|
||||
}
|
||||
Ok(json!({"easing": easing.label(), "properties": set}))
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 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));
|
||||
let now = base.map(|b| m.props_at(&b, (frame - kf.start) as f32));
|
||||
let tracks: Vec<Value> = m
|
||||
.tracks
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let keys: Vec<Value> = t.keys.iter().map(|k| json!({"frame": kf.start + k.frame, "value": k.value, "ease": k.ease.label(), "bezier": k.ease.as_bezier()})).collect();
|
||||
json!({"property": t.property.key(), "label": t.property.label(), "unit": t.property.unit(), "keys": keys})
|
||||
})
|
||||
.collect();
|
||||
let values: serde_json::Map<String, Value> = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().to_string(), json!(n.get(*p))))).collect();
|
||||
Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values}))
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! WebAssembly plug-ins (ADR 0017, `docs/plugins.md`): `plugin.install / list / run / remove /
|
||||
//! reload`, and the host side of the ABI, which lets a running plug-in read the document and
|
||||
//! run registry commands. A run is atomic and one undo step: the commands it makes run nested
|
||||
//! (no history of their own) inside `plugin.run`, and any failure restores the document.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ElementId, ElementKind, Paint};
|
||||
use anicraft_geom::Rect;
|
||||
use anicraft_plugins::{Host, Manifest, ParamKind, Plugin, SelectionNeed};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("plugin.install", "Install Plug-in…", "Commands", None, "{path: a .wasm plug-in, confirm? (when it replaces an installed plug-in's file)} validates and installs it; with a plug-ins folder it is copied there", false, install as crate::RunFn),
|
||||
c("plugin.list", "Manage Plug-ins…", "Commands", None, "{} lists the installed plug-ins (the app shows them in a window)", false, list),
|
||||
c("plugin.run", "Run Plug-in", "", None, "{id, params?: {…} (see plugin.list; missing ones take their defaults)} one undo step", true, run),
|
||||
c("plugin.remove", "Remove Plug-in", "", None, "{id, confirm? (when it deletes the plug-in's file from the plug-ins folder)}", false, remove),
|
||||
c("plugin.reload", "Reload Plug-ins", "Commands", None, "{folder? (makes it the plug-ins folder first)} re-reads every .wasm in the plug-ins folder", false, reload),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most elements the `elements` request lists.
|
||||
const MAX_ELEMENTS: usize = 10_000;
|
||||
|
||||
/// Whether a running plug-in may call command `id`, and if not, why. Plug-ins edit the
|
||||
/// document; they never touch files, the clipboard, history or other plug-ins. A command in
|
||||
/// 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"];
|
||||
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" => {
|
||||
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"),
|
||||
"plugin" => Err("plug-ins can't install, run or remove plug-ins"),
|
||||
ns if DOCUMENT.contains(&ns) => Ok(()),
|
||||
_ => Err("plug-ins can't call this command"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The session as a plug-in sees it.
|
||||
pub(crate) struct SessionHost<'a> {
|
||||
pub s: &'a mut Session,
|
||||
}
|
||||
|
||||
impl Host for SessionHost<'_> {
|
||||
fn request(&mut self, op: &str, req: &Value) -> std::result::Result<Value, String> {
|
||||
match op {
|
||||
"command" => {
|
||||
let id = req.get("id").and_then(Value::as_str).ok_or("a command request needs an \"id\", e.g. {\"op\":\"command\",\"id\":\"draw.rect\",\"params\":{…}}")?;
|
||||
if crate::find_command(id).is_none() {
|
||||
return Err(format!("unknown command '{id}'"));
|
||||
}
|
||||
plugin_may_call(id).map_err(|why| format!("'{id}': {why}"))?;
|
||||
let params = req.get("params").cloned().unwrap_or_else(|| json!({}));
|
||||
self.s.execute_nested(id, ¶ms).map_err(|e| e.to_string())
|
||||
}
|
||||
"document" => Ok(document_view(self.s)),
|
||||
"elements" => elements_view(self.s, req),
|
||||
_ => Err(format!("unknown op '{op}' (ABI v1 has command, document, elements and log)")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The compact document view (`{"op":"document"}`).
|
||||
fn document_view(s: &Session) -> Value {
|
||||
let st = &s.doc.stage;
|
||||
let layers: Vec<Value> = s
|
||||
.doc
|
||||
.timeline(s.scene)
|
||||
.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)}))
|
||||
.collect();
|
||||
json!({
|
||||
"abi": anicraft_plugins::ABI_VERSION,
|
||||
"stage": {"width": st.width, "height": st.height, "fps": st.fps, "background": st.background.to_hex()},
|
||||
"scene": s.scene,
|
||||
"scenes": s.doc.scenes.len(),
|
||||
"frame": s.frame,
|
||||
"frames": s.frame_count(),
|
||||
"layer": s.layer.0,
|
||||
"layers": layers,
|
||||
"selection": s.selection.iter().map(|e| e.0).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
fn paint_json(p: &Paint) -> Value {
|
||||
match p {
|
||||
Paint::Solid(c) => json!(c.to_hex()),
|
||||
Paint::Linear { .. } => json!("linear-gradient"),
|
||||
Paint::Radial { .. } => json!("radial-gradient"),
|
||||
Paint::Bitmap { .. } => json!("bitmap"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The elements on the active layer at the playhead (`{"op":"elements", "selected"?, "paths"?}`).
|
||||
fn elements_view(s: &Session, req: &Value) -> std::result::Result<Value, String> {
|
||||
let only_selected = req.get("selected").and_then(Value::as_bool).unwrap_or(false);
|
||||
let paths = req.get("paths").and_then(Value::as_bool).unwrap_or(false);
|
||||
// Stage bounds of every top-level element in one pass over the display list.
|
||||
let mut bounds: HashMap<ElementId, Rect> = HashMap::new();
|
||||
for item in s.display_list().items.iter().filter(|i| i.layer == s.layer) {
|
||||
let pad = item.stroke.map_or(0.0, |st| st.width * 0.5);
|
||||
let r = item.path.bounds().inflate(pad).transformed(&item.transform);
|
||||
let e = bounds.entry(item.element).or_insert(Rect::EMPTY);
|
||||
*e = e.union(&r);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for e in s.visible_elements().iter().filter(|e| !only_selected || s.selection.contains(&e.id)) {
|
||||
if out.len() >= MAX_ELEMENTS {
|
||||
break;
|
||||
}
|
||||
let b = bounds.get(&e.id).copied().unwrap_or(Rect::EMPTY);
|
||||
let mut v = json!({
|
||||
"id": e.id.0,
|
||||
"name": e.name,
|
||||
"selected": s.selection.contains(&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,
|
||||
});
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => {
|
||||
v["kind"] = json!("shape");
|
||||
v["fill"] = sh.fill.as_ref().map_or(Value::Null, paint_json);
|
||||
v["stroke"] = sh.stroke.map_or(Value::Null, |st| json!({"color": st.color.to_hex(), "width": st.width}));
|
||||
if paths {
|
||||
v["path"] = json!(sh.path.to_svg());
|
||||
}
|
||||
}
|
||||
ElementKind::Symbol { symbol, .. } => {
|
||||
v["kind"] = json!("symbol");
|
||||
v["symbol"] = json!(symbol.0);
|
||||
}
|
||||
ElementKind::Text(t) => {
|
||||
v["kind"] = json!("text");
|
||||
v["text"] = json!(t.text);
|
||||
}
|
||||
}
|
||||
out.push(v);
|
||||
}
|
||||
Ok(json!({"layer": s.layer.0, "frame": s.frame, "elements": out}))
|
||||
}
|
||||
|
||||
fn param_json(name: &str, p: &anicraft_plugins::ParamSpec) -> Value {
|
||||
let mut v = match &p.kind {
|
||||
ParamKind::Number { min, max, default } => json!({"type": "number", "min": min, "max": max, "default": default}),
|
||||
ParamKind::Int { min, max, default } => json!({"type": "int", "min": min, "max": max, "default": default}),
|
||||
ParamKind::Bool { default } => json!({"type": "bool", "default": default}),
|
||||
ParamKind::Choice { options, default } => json!({"type": "choice", "options": options, "default": default}),
|
||||
ParamKind::Color { default } => json!({"type": "color", "default": default}),
|
||||
};
|
||||
v["name"] = json!(name);
|
||||
v["label"] = json!(p.label);
|
||||
v
|
||||
}
|
||||
|
||||
/// A plug-in as `plugin.list` describes it.
|
||||
pub fn describe(s: &Session, p: &Plugin) -> Value {
|
||||
let m: &Manifest = p.manifest();
|
||||
json!({
|
||||
"id": m.id,
|
||||
"name": m.name,
|
||||
"version": m.version,
|
||||
"author": m.author,
|
||||
"description": m.description,
|
||||
"kind": "command",
|
||||
"selection": if m.selection == SelectionNeed::Required { "required" } else { "optional" },
|
||||
"params": m.params.iter().map(|(k, spec)| param_json(k, spec)).collect::<Vec<_>>(),
|
||||
"notation": m.params_notation(),
|
||||
"size": p.size(),
|
||||
"source": p.source().map(|s| s.display().to_string()),
|
||||
"in_folder": s.plugins.owns_file(p),
|
||||
})
|
||||
}
|
||||
|
||||
fn plugin_err(e: anicraft_plugins::Error) -> EngineError {
|
||||
match e {
|
||||
anicraft_plugins::Error::Params(m) => EngineError::Param(m),
|
||||
e => EngineError::State(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
let inst = s.plugins.install_file(&path).map_err(plugin_err)?;
|
||||
Ok(json!({
|
||||
"installed": describe(s, &inst.plugin),
|
||||
"replaced": inst.replaced.map(|o| o.manifest().version.clone()),
|
||||
"copied_to": inst.copied_to.map(|d| d.display().to_string()),
|
||||
}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let plugins: Vec<Value> = s.plugins.list().map(|p| describe(s, p)).collect();
|
||||
Ok(json!({"plugins": plugins, "folder": s.plugins.folder().map(|f| f.display().to_string()), "abi": anicraft_plugins::ABI_VERSION}))
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_req(p, "id")?;
|
||||
let plugin = s.plugins.get(id).ok_or_else(|| EngineError::State(format!("no plug-in “{id}” is installed (see plugin.list)")))?;
|
||||
let m = plugin.manifest();
|
||||
if m.selection == SelectionNeed::Required && s.selection.is_empty() {
|
||||
return Err(EngineError::State(format!("{} works on the selection: select some artwork first", m.name)));
|
||||
}
|
||||
let params = m.resolve_params(p.get("params").unwrap_or(&Value::Null)).map_err(plugin_err)?;
|
||||
let report = plugin.run(&mut SessionHost { s }, ¶ms).map_err(plugin_err)?;
|
||||
// The undo step is named after the plug-in ("Undo Star Field").
|
||||
s.step_label = Some(m.name.clone());
|
||||
Ok(json!({"plugin": m.id, "name": m.name, "params": params, "log": report.log, "log_dropped": report.log_dropped, "calls": report.calls, "fuel": report.fuel}))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_req(p, "id")?;
|
||||
let rm = s.plugins.remove(id).map_err(plugin_err)?;
|
||||
Ok(json!({"removed": rm.plugin.id(), "name": rm.plugin.manifest().name, "deleted": rm.deleted.map(|d| d.display().to_string())}))
|
||||
}
|
||||
|
||||
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(f) = opt_str(p, "folder")? {
|
||||
if f.trim().is_empty() {
|
||||
return Err(EngineError::Param("'folder' is empty".into()));
|
||||
}
|
||||
s.plugins.set_folder(Some(PathBuf::from(f)));
|
||||
}
|
||||
let rep = s.plugins.reload().map_err(plugin_err)?;
|
||||
Ok(json!({
|
||||
"folder": s.plugins.folder().map(|f| f.display().to_string()),
|
||||
"loaded": rep.loaded,
|
||||
"failed": rep.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(),
|
||||
"installed": s.plugins.len(),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Crash-recovery commands (ADR 0015): list, restore and discard the autosaved copies that a
|
||||
//! session which didn't close cleanly left in a recovery folder, and autosave on request.
|
||||
//! The desktop app autosaves in the background with [`crate::recovery::Autosaver`]; these
|
||||
//! commands are how it (and the CLI, scripts and agents) acts on what was left behind.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::recovery::{self, RecoveryMeta};
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec {
|
||||
id: "file.recovery_list",
|
||||
label: "Recover Autosaved Documents…",
|
||||
menu: "File",
|
||||
shortcut: None,
|
||||
params: "{dir (the recovery folder)}",
|
||||
mutates: false,
|
||||
run: list,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "file.recover",
|
||||
label: "Restore Autosaved Document",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{dir, session (an id from file.recovery_list), confirm? (needed over unsaved changes)}",
|
||||
mutates: false,
|
||||
run: recover,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "file.discard_recovery",
|
||||
label: "Discard Autosaved Document",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{dir, session, confirm (always: it cannot be undone)}",
|
||||
mutates: false,
|
||||
run: discard,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "file.autosave",
|
||||
label: "Autosave Now",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{dir, session? (default headless-<process id>)}",
|
||||
mutates: false,
|
||||
run: autosave,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn dir(p: &Value) -> Result<PathBuf> {
|
||||
let d = str_req(p, "dir")?;
|
||||
if d.trim().is_empty() {
|
||||
return Err(EngineError::Param("param 'dir' must name the recovery folder".into()));
|
||||
}
|
||||
Ok(PathBuf::from(d))
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = dir(p)?;
|
||||
let found = recovery::scan(&dir, None);
|
||||
Ok(json!({"dir": dir.display().to_string(), "documents": found.iter().map(recovery::Entry::to_json).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Opens an autosaved copy as the document: unsaved, with its original path remembered so Save
|
||||
/// goes back there, unless that file was saved after the copy was made (then Save asks for a
|
||||
/// name, so newer work on disk is never replaced by older recovered work).
|
||||
fn recover(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = dir(p)?;
|
||||
let id = str_req(p, "session")?;
|
||||
let entry = recovery::find(&dir, id)?;
|
||||
let newer = entry.original_is_newer();
|
||||
let (doc, meta) = recovery::load(&dir, id)?;
|
||||
let path = if newer { None } else { meta.original.clone() };
|
||||
s.replace_document(doc, path);
|
||||
s.mark_unsaved();
|
||||
let mut info = s.info();
|
||||
info["recovered"] = json!(id);
|
||||
info["name"] = json!(meta.name);
|
||||
info["original"] = json!(meta.original.as_ref().map(|o| o.display().to_string()));
|
||||
info["original_newer"] = json!(newer);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn discard(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = dir(p)?;
|
||||
let id = str_req(p, "session")?;
|
||||
let removed = recovery::discard(&dir, id)?;
|
||||
Ok(json!({"discarded": id, "files": removed}))
|
||||
}
|
||||
|
||||
fn autosave(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = dir(p)?;
|
||||
let id = match opt_str(p, "session")? {
|
||||
Some(id) => id.to_string(),
|
||||
None => format!("headless-{}", std::process::id()),
|
||||
};
|
||||
let meta = RecoveryMeta::describe(&id, &s.doc, s.path.as_deref());
|
||||
let st = recovery::write(&dir, &id, &s.doc, &meta)?;
|
||||
Ok(json!({
|
||||
"session": id,
|
||||
"written": recovery::document_path(&dir, &id).display().to_string(),
|
||||
"bytes": st.bytes,
|
||||
"serialize_ms": (st.serialize_ms * 100.0).round() / 100.0,
|
||||
"write_ms": (st.write_ms * 100.0).round() / 100.0,
|
||||
}))
|
||||
}
|
||||
@@ -106,6 +106,11 @@ fn reid(s: &mut Session, tl: &Timeline) -> Timeline {
|
||||
Arc::new(Element { id, ..(**e).clone() })
|
||||
})
|
||||
.collect();
|
||||
if let Some(m) = nk.motion.as_mut()
|
||||
&& let Some((_, n)) = emap.iter().find(|(o, _)| *o == m.target)
|
||||
{
|
||||
m.target = *n;
|
||||
}
|
||||
Arc::new(nk)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -15,9 +15,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("timeline.insert_blank_keyframe", "Blank Keyframe", "Insert/Timeline", Some("F7"), "{layer? | layers?: [..], frame?}", true, insert_blank_keyframe),
|
||||
c("timeline.clear_keyframe", "Clear Keyframe", "Insert/Timeline", Some("Shift+F6"), "{layer? | layers?: [..], frame?, count?}", true, clear_keyframe),
|
||||
c("timeline.move_keyframes", "Move Keyframes", "", None, "{layer? | layers?: [..], from, to?, by, layer_by? (rows down; negative = up)}", true, move_keyframes),
|
||||
c("timeline.create_motion_tween", "Create Motion Tween", "Insert", None, "{layer?, frame?} (several objects on the key become one graphic symbol; a one-frame span grows to a second)", true, crate::cmds_motion::create),
|
||||
c("timeline.create_tween", "Create Classic Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_tween),
|
||||
c("timeline.create_shape_tween", "Create Shape Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_shape_tween),
|
||||
c("timeline.remove_tween", "Remove Tween", "Insert", None, "{layer?, frame?}", true, remove_tween),
|
||||
c("timeline.remove_tween", "Remove Tween", "Insert", None, "{layer?, frame?} (a motion tween leaves its object as it is on the first frame)", true, remove_tween),
|
||||
c("timeline.set_easing", "Set Tween Easing", "", None, "{easing, layer?, frame?}", true, set_easing),
|
||||
c("timeline.set_orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}", true, set_orient),
|
||||
c("timeline.set_label", "Frame Label", "", None, "{label, layer?, frame?}", true, set_label),
|
||||
@@ -238,7 +239,7 @@ fn insert_frame(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"frames": frames}))
|
||||
}
|
||||
|
||||
fn insert_frame_at(layer: &mut Layer, frame: u32) -> Result<()> {
|
||||
pub(crate) fn insert_frame_at(layer: &mut Layer, frame: u32) -> Result<()> {
|
||||
if layer.end_frame() >= MAX_FRAME {
|
||||
return Err(EngineError::State("the timeline is at its maximum length".into()));
|
||||
}
|
||||
@@ -320,20 +321,31 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
if let Some(k) = layer.keyframe_starting_at(frame).and_then(|i| layer.keyframe_mut(i)) {
|
||||
k.elements.clear();
|
||||
k.tween = None;
|
||||
k.motion = None;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let elements = if copy { evaluate_layer_elements(layer, frame).map(|(_, e)| e.into_owned()) } else { None };
|
||||
// Past the end of a motion tween, a copy starts from how its object looks at the end.
|
||||
let last_state = match layer.keyframes.iter().rposition(|k| k.start < frame) {
|
||||
Some(i) if copy && layer.keyframe_index_at(frame).is_none() => {
|
||||
layer.keyframes.get(i).filter(|k| k.motion.is_some()).and_then(|k| evaluate_layer_elements(layer, k.end() - 1)).map(|(_, e)| e.into_owned())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match layer.keyframe_index_at(frame) {
|
||||
Some(i) => {
|
||||
let Some(k) = layer.keyframe_mut(i) else { return Ok(()) };
|
||||
let end = k.end();
|
||||
let tween = if copy { k.tween } else { None };
|
||||
// A motion tween split in two keeps moving the same way in both halves.
|
||||
let motion = if copy { k.motion.as_ref().map(|m| m.split_at(frame - k.start)) } else { None };
|
||||
k.duration = frame - k.start;
|
||||
let mut nk = Keyframe::new(frame, end - frame);
|
||||
nk.elements = elements.unwrap_or_default();
|
||||
nk.tween = tween;
|
||||
nk.motion = motion;
|
||||
layer.keyframes.insert(i + 1, Arc::new(nk));
|
||||
}
|
||||
None => {
|
||||
@@ -344,7 +356,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
let next_start = layer.keyframes.get(i + 1).map(|k| k.start);
|
||||
if let Some(k) = layer.keyframe_mut(i) {
|
||||
if copy {
|
||||
nk.elements = k.elements.clone();
|
||||
nk.elements = last_state.unwrap_or_else(|| k.elements.clone());
|
||||
}
|
||||
k.duration = frame - k.start;
|
||||
}
|
||||
@@ -363,7 +375,11 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
fn insert_keyframe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, frame) = target(s, p)?;
|
||||
for id in target_layers(s, p)? {
|
||||
insert_keyframe_at(s.layer_mut(Some(id))?, frame, true)?;
|
||||
let layer = s.layer_mut(Some(id))?;
|
||||
// Inside a motion tween F6 keys every property there; the span stays whole.
|
||||
if !crate::cmds_motion::key_all_at(layer, frame) {
|
||||
insert_keyframe_at(layer, frame, true)?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"keyframe": frame}))
|
||||
}
|
||||
@@ -524,6 +540,7 @@ fn clear_keyframe_at(layer: &mut Layer, frame: u32) -> Result<()> {
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.elements.clear();
|
||||
k.tween = None;
|
||||
k.motion = None;
|
||||
}
|
||||
} else {
|
||||
let removed = layer.keyframes.remove(i);
|
||||
@@ -559,6 +576,8 @@ fn tween_of_kind(s: &mut Session, p: &Value, kind: TweenKind) -> Result<Value> {
|
||||
None => k.tween.map(|t| t.easing).unwrap_or_default(),
|
||||
};
|
||||
let orient = k.tween.is_some_and(|t| t.orient);
|
||||
// It replaces a motion tween, keeping the object as it is on the first frame.
|
||||
crate::cmds_motion::bake_first_frame(k);
|
||||
k.tween = Some(Tween { easing, kind, orient });
|
||||
let kind = if kind == TweenKind::Shape { "shape" } else { "classic" };
|
||||
Ok(json!({"tween": k.start, "easing": easing.label(), "kind": kind}))
|
||||
@@ -567,6 +586,7 @@ fn tween_of_kind(s: &mut Session, p: &Value, kind: TweenKind) -> Result<Value> {
|
||||
fn remove_tween(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let k = keyframe_mut(s, p)?;
|
||||
k.tween = None;
|
||||
crate::cmds_motion::bake_first_frame(k);
|
||||
Ok(json!({"removed": k.start}))
|
||||
}
|
||||
|
||||
|
||||
@@ -76,7 +76,18 @@ fn overwrite(path: &Path, what: &str) -> Confirmation {
|
||||
/// The confirmation `id` with `p` needs right now, if any.
|
||||
pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
match id {
|
||||
"file.new" | "file.new_sample" | "file.open" if s.is_dirty() => Some(Confirmation {
|
||||
"file.discard_recovery" => {
|
||||
// Always: the autosaved work is the last copy there is.
|
||||
let dir = Path::new(p.get("dir").and_then(Value::as_str)?);
|
||||
let e = crate::recovery::find(dir, p.get("session").and_then(Value::as_str)?).ok()?;
|
||||
Some(Confirmation {
|
||||
title: "Discard autosaved document?".into(),
|
||||
message: format!("The autosaved copy of “{}” will be deleted, with the work it holds.", e.meta.name),
|
||||
action: "Discard".into(),
|
||||
irreversible: true,
|
||||
})
|
||||
}
|
||||
"file.new" | "file.new_sample" | "file.open" | "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(),
|
||||
@@ -180,6 +191,33 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"plugin.install" => {
|
||||
let path = Path::new(p.get("path").and_then(Value::as_str)?);
|
||||
let (m, dest) = s.plugins.install_overwrites(path)?;
|
||||
let old = s.plugins.get(&m.id).map(|o| o.manifest().version.clone()).filter(|v| !v.is_empty());
|
||||
Some(Confirmation {
|
||||
title: "Replace plug-in?".into(),
|
||||
message: format!(
|
||||
"“{}”{} is already installed. Installing {} replaces its file in the plug-ins folder ({}); this cannot be undone.",
|
||||
m.name,
|
||||
old.map_or_else(String::new, |v| format!(" {v}")),
|
||||
path.display(),
|
||||
dest.display()
|
||||
),
|
||||
action: "Replace Plug-in".into(),
|
||||
irreversible: true,
|
||||
})
|
||||
}
|
||||
"plugin.remove" => {
|
||||
let plugin = s.plugins.get(p.get("id").and_then(Value::as_str)?)?;
|
||||
let file = plugin.source().filter(|_| s.plugins.owns_file(&plugin))?;
|
||||
Some(Confirmation {
|
||||
title: "Remove plug-in?".into(),
|
||||
message: format!("“{}” is uninstalled and its file is deleted from the plug-ins folder ({}). This cannot be undone.", plugin.manifest().name, file.display()),
|
||||
action: "Remove Plug-in".into(),
|
||||
irreversible: true,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,18 @@ mod cmds_draw;
|
||||
mod cmds_file;
|
||||
mod cmds_frames;
|
||||
mod cmds_modify;
|
||||
mod cmds_motion;
|
||||
mod cmds_paint;
|
||||
mod cmds_path;
|
||||
mod cmds_recovery;
|
||||
pub mod cmds_plugin;
|
||||
mod cmds_scene;
|
||||
pub mod cmds_text;
|
||||
mod cmds_timeline;
|
||||
pub mod confirm;
|
||||
pub mod format;
|
||||
pub mod history;
|
||||
pub mod recovery;
|
||||
pub mod render_service;
|
||||
pub mod params;
|
||||
|
||||
@@ -29,6 +33,7 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use anicraft_doc as doc;
|
||||
pub use anicraft_plugins as plugins;
|
||||
pub use anicraft_text as text;
|
||||
pub use anicraft_geom as geom;
|
||||
pub use anicraft_render as render;
|
||||
@@ -82,7 +87,9 @@ impl CommandSpec {
|
||||
pub fn commands() -> Vec<CommandSpec> {
|
||||
let mut v = Vec::new();
|
||||
v.extend(cmds_file::specs());
|
||||
v.extend(cmds_recovery::specs());
|
||||
v.extend(cmds_timeline::specs());
|
||||
v.extend(cmds_motion::specs());
|
||||
v.extend(cmds_scene::specs());
|
||||
v.extend(cmds_frames::specs());
|
||||
v.extend(cmds_draw::specs());
|
||||
@@ -90,6 +97,7 @@ pub fn commands() -> Vec<CommandSpec> {
|
||||
v.extend(cmds_path::specs());
|
||||
v.extend(cmds_paint::specs());
|
||||
v.extend(cmds_text::specs());
|
||||
v.extend(cmds_plugin::specs());
|
||||
v
|
||||
}
|
||||
|
||||
@@ -159,6 +167,14 @@ pub struct Session {
|
||||
pub clipboard: cmds_modify::Clipboard,
|
||||
/// Copied frames (Copy Frames), separate from copied artwork as in Animate.
|
||||
pub frame_clipboard: cmds_frames::FrameClipboard,
|
||||
/// A command is editing a motion tween's target (auto-key, ADR 0016).
|
||||
motion_edit: Option<cmds_motion::MotionEdit>,
|
||||
/// Installed WebAssembly plug-ins (ADR 0017). They belong to the session, not the
|
||||
/// document: they survive New and Open.
|
||||
pub plugins: anicraft_plugins::Registry,
|
||||
/// A name for the undo step the running command records, set by the command
|
||||
/// (`plugin.run` names its step after the plug-in).
|
||||
pub(crate) step_label: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Session {
|
||||
@@ -196,6 +212,9 @@ impl Session {
|
||||
dl_cache: RefCell::new(None),
|
||||
clipboard: cmds_modify::Clipboard::default(),
|
||||
frame_clipboard: cmds_frames::FrameClipboard::default(),
|
||||
motion_edit: None,
|
||||
plugins: anicraft_plugins::Registry::default(),
|
||||
step_label: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,6 +229,12 @@ impl Session {
|
||||
self.saved_state = Some(self.state);
|
||||
}
|
||||
|
||||
/// Marks the document as not saved anywhere yet (a restored autosave), so the close guard
|
||||
/// and the title treat it as unsaved work.
|
||||
pub fn mark_unsaved(&mut self) {
|
||||
self.saved_state = None;
|
||||
}
|
||||
|
||||
/// The confirmation running `id` with `params` needs right now (ADR 0004).
|
||||
pub fn confirmation(&self, id: &str, params: &Value) -> Option<confirm::Confirmation> {
|
||||
confirm::confirmation(self, id, params)
|
||||
@@ -251,9 +276,11 @@ impl Session {
|
||||
let rev = self.revision;
|
||||
let budget = self.history.budget_bytes;
|
||||
let clipboard = std::mem::take(&mut self.clipboard);
|
||||
let plugins = std::mem::take(&mut self.plugins);
|
||||
*self = Session::new(doc);
|
||||
// The clipboard survives New/Open, so artwork can move between documents.
|
||||
self.clipboard = clipboard;
|
||||
self.plugins = plugins;
|
||||
self.style = style;
|
||||
self.revision = rev + 1;
|
||||
self.path = path;
|
||||
@@ -273,11 +300,22 @@ impl Session {
|
||||
if !spec.mutates {
|
||||
return (spec.run)(self, params);
|
||||
}
|
||||
let before = self.snapshot(spec.label);
|
||||
let mut before = self.snapshot(spec.label);
|
||||
// A command must never observe a display list of the state it is changing.
|
||||
self.dl_cache.replace(None);
|
||||
self.motion_edit = None;
|
||||
self.step_label = None;
|
||||
let result = (spec.run)(self, params);
|
||||
// Edits to a motion tween's target become property keys (auto-key).
|
||||
if let Some(edit) = self.motion_edit.take()
|
||||
&& result.is_ok()
|
||||
{
|
||||
cmds_motion::finish_edit(self, edit);
|
||||
}
|
||||
self.dl_cache.replace(None);
|
||||
if let Some(label) = self.step_label.take() {
|
||||
before.label = label;
|
||||
}
|
||||
match result {
|
||||
Ok(v) => {
|
||||
// O(changed): unchanged subtrees compare by pointer.
|
||||
@@ -298,6 +336,52 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a command inside another one (a plug-in's requests during `plugin.run`): checked
|
||||
/// and atomic like [`Session::execute`], but it records no undo step of its own, so the
|
||||
/// outer command stays one step.
|
||||
pub(crate) fn execute_nested(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
if let Some(c) = self.confirmation(id, params)
|
||||
&& c.irreversible
|
||||
{
|
||||
return Err(EngineError::NeedsConfirmation(format!("{} {}", c.title, c.message)));
|
||||
}
|
||||
if !spec.mutates {
|
||||
return (spec.run)(self, params);
|
||||
}
|
||||
let before = self.snapshot("");
|
||||
self.dl_cache.replace(None);
|
||||
let result = (spec.run)(self, params);
|
||||
self.dl_cache.replace(None);
|
||||
match result {
|
||||
Ok(v) => {
|
||||
// Later requests must see this change (display list, hit tests): new state.
|
||||
if self.doc != before.doc {
|
||||
self.state = history::fresh_state();
|
||||
}
|
||||
self.fix_selection();
|
||||
Ok(v)
|
||||
}
|
||||
Err(e) => {
|
||||
self.restore(before);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the document back where the open gesture started, keeping the gesture open. A
|
||||
/// live preview re-runs from the same start on every change, and Cancel leaves no step.
|
||||
pub fn revert_gesture(&mut self) {
|
||||
let Some(g) = &self.gesture else { return };
|
||||
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 };
|
||||
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 }
|
||||
}
|
||||
@@ -475,13 +559,16 @@ impl Session {
|
||||
return Err(EngineError::State(format!("layer '{}' is in a locked folder", l.name)));
|
||||
}
|
||||
}
|
||||
let layer = self.layer_mut(None)?;
|
||||
// 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)))?;
|
||||
if layer.locked {
|
||||
return Err(EngineError::State(format!("layer '{}' is locked", layer.name)));
|
||||
}
|
||||
// Inside a motion tween edits key properties, never the timeline.
|
||||
let needs_key = match layer.keyframe_at(frame) {
|
||||
None => true,
|
||||
Some(k) => k.tween.is_some() && k.start != frame,
|
||||
Some(k) => k.motion.is_none() && k.tween.is_some() && k.start != frame,
|
||||
};
|
||||
if needs_key {
|
||||
// Inside a tween: capture the tweened state. On an empty frame: start blank.
|
||||
@@ -489,7 +576,16 @@ impl Session {
|
||||
cmds_timeline::insert_keyframe_at(layer, frame, copy)?;
|
||||
}
|
||||
let idx = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State("no keyframe at the playhead".into()))?;
|
||||
layer.keyframe_mut(idx).ok_or_else(|| EngineError::State("no keyframe at the playhead".into()))
|
||||
let lid = layer.id;
|
||||
let kf = layer.keyframe_mut(idx).ok_or_else(|| EngineError::State("no keyframe at the playhead".into()))?;
|
||||
// In a motion tween the command edits the target as it looks at the playhead; the
|
||||
// session turns what changed into property keys when the command is done.
|
||||
if self.motion_edit.is_none()
|
||||
&& let Some(edit) = cmds_motion::begin_edit(lid, kf, frame)
|
||||
{
|
||||
self.motion_edit = Some(edit);
|
||||
}
|
||||
Ok(kf)
|
||||
}
|
||||
|
||||
/// Selected elements in the editable keyframe (copy-on-write: only these are cloned).
|
||||
@@ -512,7 +608,7 @@ impl Session {
|
||||
.map(|l| {
|
||||
json!({
|
||||
"id": l.id.0, "name": l.name, "visible": l.visible, "locked": l.locked,
|
||||
"keyframes": l.keyframes.iter().map(|k| json!({"start": k.start, "duration": k.duration, "elements": k.elements.len(), "tween": k.tween.map(|t| t.easing.label())})).collect::<Vec<_>>()
|
||||
"keyframes": l.keyframes.iter().map(|k| json!({"start": k.start, "duration": k.duration, "elements": k.elements.len(), "tween": k.tween.map(|t| t.easing.label()), "motion": k.motion.as_ref().map(|m| m.tracks.iter().map(|t| t.property.key()).collect::<Vec<_>>())})).collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -551,3 +647,8 @@ pub fn element_label(doc: &Document, e: &Element) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod motion_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_tests;
|
||||
@@ -0,0 +1,263 @@
|
||||
//! Motion tweens through the command registry (ADR 0016): creation, auto-key, property keys and
|
||||
//! eases, F6 inside a span, removal, conversion, frames clipboard and the file round trip.
|
||||
|
||||
use super::*;
|
||||
use anicraft_doc::{Easing, Property};
|
||||
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 10 × 10 square centred on (5, 5), selected, with a motion tween over a one-second span.
|
||||
fn tweened() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
let v = run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
assert_eq!(v["frames"], 24, "a one-frame span grows to a second at 24 fps");
|
||||
assert_eq!(v["converted"], false);
|
||||
s
|
||||
}
|
||||
|
||||
fn pos(s: &mut Session, frame: u32) -> (f32, f32) {
|
||||
s.set_frame(frame);
|
||||
let t = s.visible_elements().first().map(|e| e.transform.translation()).unwrap_or_default();
|
||||
(t.x, t.y)
|
||||
}
|
||||
|
||||
fn layer(s: &Session) -> &Layer {
|
||||
s.active_layer().expect("active layer")
|
||||
}
|
||||
|
||||
fn motion(s: &Session) -> &anicraft_doc::MotionTween {
|
||||
layer(s).keyframes[0].motion.as_ref().expect("motion tween")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_object_inside_a_motion_tween_adds_property_keys_not_keyframes() {
|
||||
let mut s = tweened();
|
||||
let steps = s.history_len();
|
||||
s.set_frame(12);
|
||||
run(&mut s, "element.translate", json!({"dx": 100, "dy": 0}));
|
||||
// One keyframe on the timeline still, one undo step, an X track keyed at 0 and 12.
|
||||
assert_eq!(layer(&s).keyframes.len(), 1);
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
let x = motion(&s).track(Property::X).expect("x track");
|
||||
assert_eq!(x.keys.iter().map(|k| (k.frame, k.value)).collect::<Vec<_>>(), vec![(0, 5.0), (12, 105.0)]);
|
||||
assert!(motion(&s).track(Property::Y).is_none(), "Y did not change, so it has no track");
|
||||
assert_eq!(pos(&mut s, 0), (5.0, 5.0));
|
||||
assert_eq!(pos(&mut s, 6), (55.0, 5.0));
|
||||
assert_eq!(pos(&mut s, 20), (105.0, 5.0), "holds after the last key");
|
||||
// Moving again at the same frame updates that key; moving elsewhere adds another.
|
||||
s.set_frame(12);
|
||||
run(&mut s, "element.translate", json!({"dx": -5, "dy": 0}));
|
||||
s.set_frame(23);
|
||||
run(&mut s, "element.translate", json!({"dx": 0, "dy": 50}));
|
||||
// Y's first key pins frame 0, so it runs over the whole span; X kept its own keys.
|
||||
let (x12, y12) = pos(&mut s, 12);
|
||||
assert!(x12 == 100.0 && (y12 - (5.0 + 50.0 * 12.0 / 23.0)).abs() < 1e-3, "{x12} {y12}");
|
||||
assert_eq!(pos(&mut s, 23), (100.0, 55.0));
|
||||
assert_eq!(motion(&s).track(Property::Y).map(|t| t.keys.len()), Some(2));
|
||||
// The stored object is still its first-frame self.
|
||||
assert_eq!(layer(&s).keyframes[0].elements[0].transform.translation(), anicraft_geom::Vec2::new(5.0, 5.0));
|
||||
// Undo takes the keys back one edit at a time.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(motion(&s).track(Property::Y).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_the_first_frame_an_unkeyed_property_moves_the_object_itself() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "element.translate", json!({"dx": 10, "dy": 0}));
|
||||
assert!(motion(&s).tracks.is_empty(), "no keys: the base moved");
|
||||
assert_eq!(pos(&mut s, 0), (15.0, 5.0));
|
||||
// Once X is keyed, the first frame keys it too, and the rest of the curve stays.
|
||||
s.set_frame(10);
|
||||
run(&mut s, "element.translate", json!({"dx": 100, "dy": 0}));
|
||||
s.set_frame(0);
|
||||
run(&mut s, "element.translate", json!({"dx": -15, "dy": 0}));
|
||||
let x = motion(&s).track(Property::X).expect("x track");
|
||||
assert_eq!(x.keys.iter().map(|k| (k.frame, k.value)).collect::<Vec<_>>(), vec![(0, 0.0), (10, 115.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforms_and_colour_edits_key_their_own_properties() {
|
||||
let mut s = tweened();
|
||||
s.set_frame(8);
|
||||
run(&mut s, "element.set_alpha", json!({"alpha": 0.25}));
|
||||
run(&mut s, "element.set_transform", json!({"sx": 2.0}));
|
||||
let m = motion(&s);
|
||||
assert_eq!(m.track(Property::Alpha).map(|t| t.keys.iter().map(|k| k.value).collect::<Vec<_>>()), Some(vec![100.0, 25.0]));
|
||||
assert!(m.track(Property::ScaleX).is_some_and(|t| (t.keys[1].value - 200.0).abs() < 1e-3));
|
||||
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);
|
||||
// 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"}));
|
||||
s.set_frame(0);
|
||||
let fill = match &s.visible_elements()[0].kind {
|
||||
ElementKind::Shape(sh) => sh.fill.clone(),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(fill, Some(anicraft_doc::Paint::Solid(anicraft_doc::Rgba::hex(0xff0000))));
|
||||
assert_eq!(layer(&s).keyframes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotating_past_half_a_turn_keeps_turning_the_same_way() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "motion.set_key", json!({"property": "rotation", "frame": 10, "value": 170}));
|
||||
s.set_frame(10);
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
// 20° more about the centre: 190°, not −170° (which would spin back the long way).
|
||||
let (c, r) = (5.0f32, 20f32.to_radians());
|
||||
let m = anicraft_geom::Affine::translate(c, c).mul(&anicraft_geom::Affine::rotate(r)).mul(&anicraft_geom::Affine::translate(-c, -c));
|
||||
let [a, b, cc, d, e, f] = m.m;
|
||||
run(&mut s, "modify.transform", json!({"a": a, "b": b, "c": cc, "d": d, "e": e, "f": f}));
|
||||
let rot = motion(&s).track(Property::Rotation).and_then(|t| t.keys.last()).map(|k| k.value).unwrap_or(0.0);
|
||||
assert!((rot - 190.0).abs() < 1e-2, "{rot}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_key_commands_and_segment_eases() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "motion.set_key", json!({"property": "x", "frame": 20, "value": 205}));
|
||||
run(&mut s, "motion.set_key", json!({"property": "Y", "frame": 20, "value": 105}));
|
||||
run(&mut s, "motion.set_ease", json!({"property": "x", "frame": 3, "easing": {"bezier": [0.4, 0.0, 0.2, 1.0]}}));
|
||||
let info = run(&mut s, "motion.info", json!({"frame": 10}));
|
||||
assert_eq!(info["start"], 0);
|
||||
assert_eq!(info["frames"], 24);
|
||||
assert_eq!(info["tracks"][0]["property"], "x");
|
||||
assert_eq!(info["tracks"][0]["keys"][0]["bezier"], json!([0.4f32, 0.0, 0.2f32, 1.0]));
|
||||
// X follows its Bézier; Y stays linear.
|
||||
let ease = Easing::CubicBezier(0.4, 0.0, 0.2, 1.0).apply(0.5);
|
||||
let (x, y) = pos(&mut s, 10);
|
||||
assert!((x - (5.0 + 200.0 * ease)).abs() < 1e-3 && (y - 55.0).abs() < 1e-3, "{x} {y}");
|
||||
assert!((info["values"]["x"].as_f64().unwrap_or(0.0) as f32 - x).abs() < 1e-3);
|
||||
// Every property's segment at once.
|
||||
let v = run(&mut s, "motion.set_ease", json!({"frame": 5, "easing": "CubicOut"}));
|
||||
assert_eq!(v["properties"], json!(["x", "y"]));
|
||||
// Remove one property's key, then the rest at that frame.
|
||||
run(&mut s, "motion.remove_key", json!({"property": "y", "frame": 20}));
|
||||
assert_eq!(motion(&s).track(Property::Y).map(|t| t.keys.len()), Some(1));
|
||||
let v = run(&mut s, "motion.remove_key", json!({"frame": 0}));
|
||||
assert_eq!(v["removed"], json!(["x", "y"]));
|
||||
// Errors say what to do.
|
||||
for (id, p) in [
|
||||
("motion.set_key", json!({"property": "alpha", "value": 140})),
|
||||
("motion.set_key", json!({"property": "size", "value": 1})),
|
||||
("motion.set_key", json!({"property": "x"})),
|
||||
("motion.remove_key", json!({"frame": 7})),
|
||||
("motion.set_ease", json!({"frame": 22, "easing": "Linear"})),
|
||||
("motion.set_key", json!({"property": "x", "value": 1, "frame": 40})),
|
||||
] {
|
||||
assert!(s.execute(id, &p).is_err(), "{id} {p}");
|
||||
}
|
||||
run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": 30}));
|
||||
let e = s.execute("motion.set_key", &json!({"property": "x", "value": 1, "frame": 30})).unwrap_err().to_string();
|
||||
assert!(e.contains("Create Motion Tween"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f6_inside_a_motion_tween_keys_every_property_without_splitting_the_span() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "motion.set_key", json!({"property": "x", "frame": 20, "value": 105}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({"frame": 10}));
|
||||
assert_eq!(layer(&s).keyframes.len(), 1);
|
||||
let m = motion(&s);
|
||||
assert_eq!(m.tracks.len(), Property::ALL.len());
|
||||
assert!(m.tracks.iter().all(|t| t.key_at(10).is_some()));
|
||||
assert!((m.track(Property::X).and_then(|t| t.keys.get(1)).map_or(0.0, |k| k.value) - 55.0).abs() < 1e-3);
|
||||
// The motion is unchanged by the new keys.
|
||||
assert!((pos(&mut s, 15).0 - 80.0).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_or_replacing_a_motion_tween_keeps_the_first_frame() {
|
||||
let mut s = tweened();
|
||||
s.set_frame(0);
|
||||
run(&mut s, "motion.set_key", json!({"property": "x", "frame": 0, "value": 50}));
|
||||
run(&mut s, "motion.set_key", json!({"property": "x", "frame": 20, "value": 150}));
|
||||
run(&mut s, "timeline.remove_tween", json!({}));
|
||||
assert!(layer(&s).keyframes[0].motion.is_none());
|
||||
assert_eq!(pos(&mut s, 0).0, 50.0);
|
||||
assert_eq!(pos(&mut s, 20).0, 50.0);
|
||||
// A classic tween replaces a motion tween the same way, and back.
|
||||
run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
run(&mut s, "timeline.create_tween", json!({}));
|
||||
let k = &layer(&s).keyframes[0];
|
||||
assert!(k.motion.is_none() && k.tween.is_some());
|
||||
run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
let k = &layer(&s).keyframes[0];
|
||||
assert!(k.motion.is_some() && k.tween.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_objects_become_one_symbol_to_tween() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
run(&mut s, "draw.ellipse", json!({"x": 20, "y": 0, "w": 10, "h": 10}));
|
||||
run(&mut s, "timeline.insert_frame", json!({"count": 9}));
|
||||
let v = run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
assert_eq!(v["converted"], true);
|
||||
assert_eq!(v["frames"], 10, "a longer span keeps its length");
|
||||
assert_eq!(s.doc.library.len(), 1);
|
||||
assert_eq!(layer(&s).keyframes[0].elements.len(), 1);
|
||||
// Empty keys have nothing to tween; folders have no frames.
|
||||
run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": 20}));
|
||||
assert!(s.execute("timeline.create_motion_tween", &json!({"frame": 20})).is_err());
|
||||
let f = run(&mut s, "layer.new_folder", json!({}));
|
||||
assert!(s.execute("timeline.create_motion_tween", &json!({"layer": f["layer"]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_and_split_spans_keep_their_motion() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "motion.set_key", json!({"property": "x", "frame": 23, "value": 235}));
|
||||
let want: Vec<(f32, f32)> = (0..24).map(|f| pos(&mut s, f)).collect();
|
||||
// Copy the span, paste it after itself: the pasted copy tweens its own (fresh) object.
|
||||
run(&mut s, "timeline.copy_frames", json!({"frame": 0, "count": 24}));
|
||||
run(&mut s, "timeline.paste_frames", json!({"frame": 24}));
|
||||
let k = &layer(&s).keyframes[1];
|
||||
let m = k.motion.as_ref().expect("pasted motion");
|
||||
assert_eq!(m.target, k.elements[0].id);
|
||||
assert_ne!(k.elements[0].id, layer(&s).keyframes[0].elements[0].id);
|
||||
for f in 0..24 {
|
||||
assert_eq!(pos(&mut s, 24 + f), want[f as usize], "pasted frame {f}");
|
||||
}
|
||||
// Splitting the span (a cut across it) keeps the motion on both sides.
|
||||
run(&mut s, "timeline.copy_frames", json!({"frame": 6, "count": 4}));
|
||||
let clip = s.frame_clipboard.layers[0].keys.clone();
|
||||
assert!(clip.first().is_some_and(|k| k.motion.is_some()));
|
||||
let mut l = layer(&s).clone();
|
||||
cmds_timeline::insert_keyframe_at(&mut l, 9, true).expect("split");
|
||||
for f in 0..24 {
|
||||
let e = evaluate_layer_elements(&l, f).map(|(_, e)| e[0].transform.translation()).unwrap_or_default();
|
||||
assert!((e.x - want[f as usize].0).abs() < 1e-3, "split frame {f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn motion_tweens_round_trip_through_the_file_format() {
|
||||
let mut s = tweened();
|
||||
s.set_frame(12);
|
||||
run(&mut s, "element.translate", json!({"dx": 40, "dy": 30}));
|
||||
run(&mut s, "motion.set_ease", json!({"frame": 4, "easing": {"bezier": [0.1, 0.9, 0.3, 1.2]}}));
|
||||
let text = format::to_json(&s.doc).expect("save");
|
||||
assert!(text.contains("\"motion\"") && text.contains("\"scale_x\"") == motion(&s).track(Property::ScaleX).is_some());
|
||||
let back = format::from_json(&text).expect("load");
|
||||
assert_eq!(back, s.doc);
|
||||
let mut t = Session::new(back);
|
||||
for f in 0..24 {
|
||||
assert_eq!(pos(&mut t, f), pos(&mut s, f));
|
||||
}
|
||||
// Duplicating a scene re-points the tween at the copied object.
|
||||
run(&mut s, "scene.duplicate", json!({}));
|
||||
let k = &s.doc.timeline(1).layers[0].keyframes[0];
|
||||
assert_eq!(k.motion.as_ref().map(|m| m.target), Some(k.elements[0].id));
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Plug-ins through the engine: install, run as one undo step, atomic failures, the command
|
||||
//! policy, and hostile requests through the host side of the ABI.
|
||||
|
||||
use crate::cmds_plugin::{SessionHost, plugin_may_call};
|
||||
use crate::{Session, commands};
|
||||
use anicraft_doc::sample;
|
||||
use anicraft_plugins::Host;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// WAT string literal contents for `s`.
|
||||
fn esc(s: &str) -> String {
|
||||
s.bytes().map(|b| if b == b'"' || b == b'\\' || !(0x20..0x7f).contains(&b) { format!("\\{b:02x}") } else { (b as char).to_string() }).collect()
|
||||
}
|
||||
|
||||
/// A plug-in that sends `requests` in order, then returns `code`. With `check`, it returns 1
|
||||
/// as soon as an answer isn't `{"ok":true…` (byte 6 is `t`).
|
||||
fn plugin(manifest: &str, requests: &[&str], check: bool, code: i32) -> Vec<u8> {
|
||||
plugin_then(manifest, requests, check, "", code)
|
||||
}
|
||||
|
||||
/// [`plugin`], running `tail` before it returns.
|
||||
fn plugin_then(manifest: &str, requests: &[&str], check: bool, tail: &str, code: i32) -> Vec<u8> {
|
||||
let mut data = format!("(data (i32.const 1024) \"{}\")\n", esc(manifest));
|
||||
let mut body = String::new();
|
||||
let mut at = 8192;
|
||||
for r in requests {
|
||||
data.push_str(&format!("(data (i32.const {at}) \"{}\")\n", esc(r)));
|
||||
body.push_str(&format!("(local.set $n (call $call (i32.const {at}) (i32.const {})))\n", r.len()));
|
||||
if check {
|
||||
body.push_str("(drop (call $response (i32.const 60000) (i32.const 16)))\n(if (i32.ne (i32.load8_u (i32.const 60006)) (i32.const 116)) (then (return (i32.const 1))))\n");
|
||||
}
|
||||
at += r.len() + 16;
|
||||
}
|
||||
let text = format!(
|
||||
r#"(module
|
||||
(import "anicraft" "call" (func $call (param i32 i32) (result i32)))
|
||||
(import "anicraft" "response" (func $response (param i32 i32) (result i32)))
|
||||
(memory (export "memory") 2)
|
||||
{data}
|
||||
(func (export "ac_abi_version") (result i32) i32.const 1)
|
||||
(func (export "ac_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 1024)))
|
||||
(func (export "ac_alloc") (param i32) (result i32) i32.const 70000)
|
||||
(func (export "ac_run") (param i32 i32) (result i32) (local $n i32)
|
||||
{body}
|
||||
{tail}
|
||||
i32.const {code}))"#,
|
||||
len = manifest.len()
|
||||
);
|
||||
wat::parse_str(&text).expect("test WAT")
|
||||
}
|
||||
|
||||
const STARS: &str = r#"{"id":"org.test.stars","name":"Test Stars","version":"1.0","kind":"command","params":{"count":{"type":"int","min":1,"max":5,"default":3}}}"#;
|
||||
const NUDGE: &str = r#"{"id":"org.test.nudge","name":"Nudge","kind":"command","selection":"required"}"#;
|
||||
|
||||
fn stars() -> Vec<u8> {
|
||||
let star = r##"{"op":"command","id":"draw.star","params":{"cx":100,"cy":80,"outer":20,"inner":8,"points":5,"fill":"#ffee88"}}"##;
|
||||
plugin(STARS, &[r#"{"op":"command","id":"layer.new","params":{"name":"Stars"}}"#, star, star, star], true, 0)
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("anicraft-engine-plugins-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).expect("temp dir");
|
||||
d
|
||||
}
|
||||
|
||||
fn install(s: &mut Session, dir: &std::path::Path, file: &str, bytes: &[u8]) -> Value {
|
||||
let path = dir.join(file);
|
||||
std::fs::write(&path, bytes).expect("write module");
|
||||
s.execute("plugin.install", &json!({"path": path.display().to_string()})).expect("installs")
|
||||
}
|
||||
|
||||
fn shapes(s: &Session) -> usize {
|
||||
s.doc.timeline(s.scene).layers.iter().flat_map(|l| l.keyframes.iter()).map(|k| k.elements.len()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_is_one_undo_step_named_after_the_plugin() {
|
||||
let dir = temp("run");
|
||||
let mut s = Session::new(sample::demo());
|
||||
let v = install(&mut s, &dir, "stars.wasm", &stars());
|
||||
assert_eq!(v["installed"]["name"], "Test Stars");
|
||||
assert_eq!(v["installed"]["params"][0]["name"], "count");
|
||||
let list = s.execute("plugin.list", &json!({})).unwrap();
|
||||
assert_eq!(list["plugins"].as_array().map(Vec::len), Some(1));
|
||||
let (doc, layers, steps, rev) = (s.doc.clone(), s.doc.timeline(0).layers.len(), s.history_len(), s.revision);
|
||||
let n = shapes(&s);
|
||||
let out = s.execute("plugin.run", &json!({"id": "org.test.stars", "params": {"count": 99}})).unwrap();
|
||||
assert_eq!(out["params"]["count"], 5, "clamped to the manifest's range");
|
||||
assert_eq!(out["calls"], 4);
|
||||
assert_eq!(s.doc.timeline(0).layers.len(), layers + 1);
|
||||
assert_eq!(shapes(&s), n + 3);
|
||||
assert!(s.revision > rev);
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
assert_eq!(s.undo_label(), Some("Test Stars"));
|
||||
// The new artwork renders.
|
||||
let dl = s.display_list();
|
||||
assert!(dl.items.len() >= 3);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc == doc, "undo restores the document exactly");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(shapes(&s), n + 3);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_run_leaves_the_document_untouched() {
|
||||
let dir = temp("fail");
|
||||
let mut s = Session::default();
|
||||
// Draws, then fails.
|
||||
let bad = plugin(r#"{"id":"org.test.bad","name":"Bad","kind":"command"}"#, &[r#"{"op":"command","id":"draw.rect","params":{"x":0,"y":0,"w":10,"h":10}}"#, r#"{"op":"log","message":"gave up"}"#], false, 5);
|
||||
install(&mut s, &dir, "bad.wasm", &bad);
|
||||
let (doc, steps, state) = (s.doc.clone(), s.history_len(), s.state);
|
||||
let e = s.execute("plugin.run", &json!({"id": "org.test.bad"})).unwrap_err().to_string();
|
||||
assert!(e.contains("code 5") && e.contains("gave up"), "{e}");
|
||||
assert!(s.doc == doc && s.history_len() == steps && s.state == state);
|
||||
// An endless loop: stopped by its budget, nothing changed, quickly.
|
||||
let spin = plugin_then(r#"{"id":"org.test.spin","name":"Spin","kind":"command"}"#, &[r#"{"op":"command","id":"draw.rect","params":{"x":0,"y":0,"w":5,"h":5}}"#], true, "(loop $l (br $l))", 0);
|
||||
s.plugins.set_limits(anicraft_plugins::Limits { fuel: 50_000_000, ..Default::default() });
|
||||
install(&mut s, &dir, "spin.wasm", &spin);
|
||||
install(&mut s, &dir, "spin.wasm", &spin);
|
||||
let t = std::time::Instant::now();
|
||||
let e = s.execute("plugin.run", &json!({"id": "org.test.spin"})).unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert!(s.doc == doc && s.history_len() == steps);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_cannot_reach_files_history_the_clipboard_or_other_plugins() {
|
||||
let dir = temp("policy");
|
||||
let target = dir.join("stolen.anicraft");
|
||||
let save = format!(r#"{{"op":"command","id":"file.save","params":{{"path":"{}","confirm":true}}}}"#, target.display().to_string().replace('\\', "/"));
|
||||
let forbidden = [
|
||||
save.as_str(),
|
||||
r#"{"op":"command","id":"file.export_png","params":{"path":"x.png"}}"#,
|
||||
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"}"#,
|
||||
r#"{"op":"command","id":"edit.copy"}"#,
|
||||
r#"{"op":"command","id":"no.such"}"#,
|
||||
r#"{"op":"command"}"#,
|
||||
r#"{"op":"read_file","path":"/etc/passwd"}"#,
|
||||
];
|
||||
let m = r#"{"id":"org.test.sneaky","name":"Sneaky","kind":"command"}"#;
|
||||
// Every forbidden request must be answered with ok:false: the plug-in returns 1 on an ok.
|
||||
for req in forbidden {
|
||||
let mut s = Session::default();
|
||||
let bytes = plugin(m, &[req], false, 0);
|
||||
install(&mut s, &dir, "sneaky.wasm", &bytes);
|
||||
let mut host = SessionHost { s: &mut s };
|
||||
let v: Value = serde_json::from_str(req).unwrap();
|
||||
let op = v["op"].as_str().unwrap_or("");
|
||||
assert!(host.request(op, &v).is_err(), "allowed: {req}");
|
||||
// And through the real ABI the run completes without the side effect.
|
||||
s.execute("plugin.run", &json!({"id": "org.test.sneaky"})).unwrap();
|
||||
assert_eq!(s.plugins.len(), 1);
|
||||
}
|
||||
assert!(!target.exists(), "a plug-in saved a file");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_namespace_has_a_plugin_policy() {
|
||||
// A new namespace must be classified in `plugin_may_call` before plug-ins can use it.
|
||||
for c in commands() {
|
||||
let ns = c.id.split('.').next().unwrap_or("");
|
||||
let verdict = plugin_may_call(c.id);
|
||||
match ns {
|
||||
"file" | "plugin" => 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),
|
||||
}
|
||||
}
|
||||
assert!(plugin_may_call("draw.rect").is_ok());
|
||||
assert!(plugin_may_call("future.thing").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_plugins_need_a_selection_and_see_it() {
|
||||
let dir = temp("sel");
|
||||
let mut s = Session::default();
|
||||
let nudge = plugin(NUDGE, &[r#"{"op":"elements","selected":true,"paths":true}"#, r#"{"op":"command","id":"element.translate","params":{"dx":5,"dy":0}}"#], true, 0);
|
||||
install(&mut s, &dir, "nudge.wasm", &nudge);
|
||||
let e = s.execute("plugin.run", &json!({"id": "org.test.nudge"})).unwrap_err().to_string();
|
||||
assert!(e.contains("select some artwork"), "{e}");
|
||||
let a = s.execute("draw.rect", &json!({"x": 10, "y": 10, "w": 20, "h": 20})).unwrap()["element"].as_u64().unwrap();
|
||||
s.execute("draw.rect", &json!({"x": 100, "y": 10, "w": 20, "h": 20})).unwrap();
|
||||
s.execute("element.select", &json!({"ids": [a]})).unwrap();
|
||||
// What the plug-in sees.
|
||||
let mut host = SessionHost { s: &mut s };
|
||||
let v = host.request("elements", &json!({"op": "elements", "selected": true, "paths": true})).unwrap();
|
||||
let els = v["elements"].as_array().unwrap();
|
||||
assert_eq!(els.len(), 1);
|
||||
assert_eq!(els[0]["id"], a);
|
||||
assert_eq!(els[0]["kind"], "shape");
|
||||
assert!(els[0]["path"].as_str().is_some_and(|d| d.starts_with('M')));
|
||||
let b = els[0]["bounds"].as_array().unwrap();
|
||||
assert!((b[0].as_f64().unwrap() - 10.0).abs() < 2.0 && (b[2].as_f64().unwrap() - 20.0).abs() < 3.0, "{b:?}");
|
||||
let all = host.request("elements", &json!({"op": "elements"})).unwrap();
|
||||
assert_eq!(all["elements"].as_array().map(Vec::len), Some(2));
|
||||
let d = host.request("document", &json!({"op": "document"})).unwrap();
|
||||
assert_eq!(d["selection"], json!([a]));
|
||||
assert_eq!(d["stage"]["width"], s.doc.stage.width);
|
||||
s.execute("plugin.run", &json!({"id": "org.test.nudge"})).unwrap();
|
||||
assert_eq!(s.undo_label(), Some("Nudge"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_survive_new_documents_and_removal_from_the_folder_asks_first() {
|
||||
let root = temp("folder");
|
||||
let folder = root.join("plugins");
|
||||
let mut s = Session::default();
|
||||
s.execute("plugin.reload", &json!({"folder": folder.display().to_string()})).unwrap();
|
||||
let v = install(&mut s, &root, "stars.wasm", &stars());
|
||||
assert!(v["copied_to"].as_str().is_some_and(|p| p.ends_with("org.test.stars.wasm")));
|
||||
s.execute("draw.rect", &json!({"x": 0, "y": 0, "w": 5, "h": 5})).unwrap();
|
||||
s.execute("file.new", &json!({"confirm": true})).unwrap();
|
||||
assert_eq!(s.plugins.len(), 1, "plug-ins belong to the session, not the document");
|
||||
// Reinstalling over the folder copy is irreversible: it asks.
|
||||
let again = json!({"path": root.join("stars.wasm").display().to_string()});
|
||||
assert!(s.confirmation("plugin.install", &again).is_some_and(|c| c.irreversible));
|
||||
assert!(s.execute("plugin.install", &again).is_err());
|
||||
let mut yes = again.clone();
|
||||
yes["confirm"] = json!(true);
|
||||
s.execute("plugin.install", &yes).unwrap();
|
||||
// Removing deletes the folder copy: it asks too.
|
||||
let rm = json!({"id": "org.test.stars"});
|
||||
assert!(s.confirmation("plugin.remove", &rm).is_some_and(|c| c.irreversible));
|
||||
assert!(s.execute("plugin.remove", &rm).is_err());
|
||||
let out = s.execute("plugin.remove", &json!({"id": "org.test.stars", "confirm": true})).unwrap();
|
||||
assert!(out["deleted"].as_str().is_some());
|
||||
assert!(!folder.join("org.test.stars.wasm").exists());
|
||||
// A broken module in the folder is reported by reload; the rest load.
|
||||
std::fs::write(folder.join("broken.wasm"), b"\0asm\x01\0\0\0nope").unwrap();
|
||||
std::fs::write(folder.join("stars.wasm"), stars()).unwrap();
|
||||
let r = s.execute("plugin.reload", &json!({})).unwrap();
|
||||
assert_eq!(r["loaded"], json!(["org.test.stars"]));
|
||||
assert_eq!(r["failed"].as_array().map(Vec::len), Some(1));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_preview_reverts_to_the_gesture_start() {
|
||||
let dir = temp("preview");
|
||||
let mut s = Session::new(sample::demo());
|
||||
install(&mut s, &dir, "stars.wasm", &stars());
|
||||
let (doc, steps) = (s.doc.clone(), s.history_len());
|
||||
s.begin_gesture("Test Stars");
|
||||
for count in 1..=3 {
|
||||
s.revert_gesture();
|
||||
s.execute("plugin.run", &json!({"id": "org.test.stars", "params": {"count": count}})).unwrap();
|
||||
}
|
||||
// Cancel: back to the start, no step.
|
||||
s.revert_gesture();
|
||||
s.end_gesture();
|
||||
assert!(s.doc == doc && s.history_len() == steps);
|
||||
// OK: one step for the last preview.
|
||||
s.begin_gesture("Test Stars");
|
||||
s.revert_gesture();
|
||||
s.execute("plugin.run", &json!({"id": "org.test.stars"})).unwrap();
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
assert_eq!(s.undo_label(), Some("Test Stars"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_requests_through_the_host_never_panic() {
|
||||
let hostile: Vec<Value> = vec![
|
||||
Value::Null,
|
||||
json!({}),
|
||||
json!([]),
|
||||
json!("x"),
|
||||
json!({"x": 1e300, "y": -1e300, "w": 1e7, "h": 1e7, "fill": "#zz"}),
|
||||
json!({"frame": u64::MAX, "layer": u64::MAX, "ids": [u64::MAX], "index": -1}),
|
||||
json!({"d": "M 0 0 C", "points": [[0, 0]], "name": "", "count": 1_000_000}),
|
||||
];
|
||||
for mut s in [Session::default(), Session::new(sample::demo())] {
|
||||
let mut host = SessionHost { s: &mut s };
|
||||
for c in commands() {
|
||||
for p in &hostile {
|
||||
let _ = host.request("command", &json!({"op": "command", "id": c.id, "params": p}));
|
||||
let _ = host.request("command", &json!({"op": "command", "id": c.id, "params": p.to_string()}));
|
||||
}
|
||||
}
|
||||
for op in ["document", "elements", "command", "", "log", "\u{202e}"] {
|
||||
for p in &hostile {
|
||||
let _ = host.request(op, p);
|
||||
let _ = host.request(op, &json!({"op": op, "selected": p, "paths": p, "id": p}));
|
||||
}
|
||||
}
|
||||
let _ = anicraft_render::render_frame(&s.doc, 0, 0.1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,671 @@
|
||||
//! Crash recovery (ADR 0015): autosaved copies of open documents in a recovery folder, so a
|
||||
//! crash, power cut or killed process loses at most the last autosave interval of work.
|
||||
//!
|
||||
//! One running editor is one *recovery session* with an id (`SessionLock`). Its files in the
|
||||
//! recovery folder are:
|
||||
//!
|
||||
//! * `<id>.anicraft`: the document, an ordinary `.anicraft` file (it opens like any other);
|
||||
//! * `<id>.json`: what it is ([`RecoveryMeta`]: original path, name, when, which version);
|
||||
//! * `<id>.lock`: held with an exclusive OS file lock while the session runs. The OS drops
|
||||
//! the lock when the process dies, however it dies, so "locked" means "alive" and an
|
||||
//! unlockable-free file means "left behind by a session that didn't close cleanly".
|
||||
//!
|
||||
//! Writes are atomic: each file goes to `<name>.tmp`, is flushed to disk and renamed over the
|
||||
//! old one, so a crash mid-write leaves the previous autosave intact. Recovery files only ever
|
||||
//! live in the recovery folder under a validated session id, and [`write`] refuses a target
|
||||
//! that is the user's own document, so autosave never writes over the user's file.
|
||||
//!
|
||||
//! [`Autosaver`] does the writing on a background thread: the caller hands it a snapshot of
|
||||
//! the persistent document (an `Arc` clone, O(1)) and never waits for serialization or disk.
|
||||
|
||||
use crate::{EngineError, Result, format};
|
||||
use anicraft_doc::Document;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Version of the `<id>.json` description.
|
||||
pub const META_VERSION: u32 = 1;
|
||||
/// Longest session id accepted (ids are generated; anything else is someone else's file).
|
||||
const MAX_ID: usize = 64;
|
||||
/// Most entries looked at in a recovery folder.
|
||||
const MAX_SCAN: usize = 4096;
|
||||
/// Largest description file read.
|
||||
const MAX_META_BYTES: u64 = 64 * 1024;
|
||||
|
||||
/// What a recovery file holds, written beside it as `<id>.json`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct RecoveryMeta {
|
||||
pub version: u32,
|
||||
/// The session that wrote it.
|
||||
pub session: String,
|
||||
/// Where the document was saved before (`None`: never saved, or imported).
|
||||
pub original: Option<PathBuf>,
|
||||
/// Display name: the original's file name, else "Untitled".
|
||||
pub name: String,
|
||||
/// Seconds since 1970 (UTC) when it was written.
|
||||
pub saved_at: u64,
|
||||
/// The AniCraft version that wrote it.
|
||||
pub app: String,
|
||||
/// Movie frames and scenes, for the restore list.
|
||||
pub frames: u32,
|
||||
pub scenes: usize,
|
||||
}
|
||||
|
||||
impl RecoveryMeta {
|
||||
/// Describes `doc`, last saved at `original`, for session `session`.
|
||||
pub fn describe(session: &str, doc: &Document, original: Option<&Path>) -> RecoveryMeta {
|
||||
RecoveryMeta {
|
||||
version: META_VERSION,
|
||||
session: session.to_string(),
|
||||
original: original.map(Path::to_path_buf),
|
||||
name: display_name(original),
|
||||
saved_at: now_secs(),
|
||||
app: env!("CARGO_PKG_VERSION").to_string(),
|
||||
frames: doc.frame_count(),
|
||||
scenes: doc.scenes.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// "walk.anicraft" for a saved document, "Untitled" otherwise.
|
||||
pub fn display_name(original: Option<&Path>) -> String {
|
||||
original.and_then(Path::file_name).map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
pub fn now_secs() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
|
||||
}
|
||||
|
||||
/// A recovery file left behind by a session that is no longer running.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Entry {
|
||||
pub session: String,
|
||||
/// The `.anicraft` copy.
|
||||
pub document: PathBuf,
|
||||
pub meta: RecoveryMeta,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// The original file changed after this copy was written (saved later, e.g. just before
|
||||
/// the crash): restoring must not put the older copy back over it.
|
||||
pub fn original_is_newer(&self) -> bool {
|
||||
let Some(o) = &self.meta.original else { return false };
|
||||
let modified = std::fs::metadata(o).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok());
|
||||
modified.is_some_and(|m| m.as_secs() > self.meta.saved_at)
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"session": self.session,
|
||||
"document": self.document.display().to_string(),
|
||||
"name": self.meta.name,
|
||||
"original": self.meta.original.as_ref().map(|p| p.display().to_string()),
|
||||
"saved_at": self.meta.saved_at,
|
||||
"frames": self.meta.frames,
|
||||
"scenes": self.meta.scenes,
|
||||
"app": self.meta.app,
|
||||
"bytes": self.bytes,
|
||||
"original_newer": self.original_is_newer(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Session ids are ours: ASCII letters, digits, `-` and `_`, so they can never name a path
|
||||
/// outside the recovery folder.
|
||||
pub fn valid_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= MAX_ID && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
fn check_id(id: &str) -> Result<()> {
|
||||
if valid_id(id) { Ok(()) } else { Err(EngineError::Param(format!("'{}' is not a recovery session id", id.chars().take(80).collect::<String>()))) }
|
||||
}
|
||||
|
||||
fn file(dir: &Path, id: &str, ext: &str) -> PathBuf {
|
||||
dir.join(format!("{id}.{ext}"))
|
||||
}
|
||||
|
||||
/// The recovery copy of session `id` in `dir`.
|
||||
pub fn document_path(dir: &Path, id: &str) -> PathBuf {
|
||||
file(dir, id, "anicraft")
|
||||
}
|
||||
|
||||
/// Writes `bytes` to `path` atomically: a temp file beside it, flushed to disk, renamed over it.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let mut tmp = path.as_os_str().to_owned();
|
||||
tmp.push(".tmp");
|
||||
let tmp = PathBuf::from(tmp);
|
||||
let result = (|| -> std::io::Result<()> {
|
||||
let mut f = File::create(&tmp)?;
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()?;
|
||||
drop(f);
|
||||
std::fs::rename(&tmp, path)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
Ok(result?)
|
||||
}
|
||||
|
||||
/// Same file, after resolving links and `..` where the file exists.
|
||||
fn same_file(a: &Path, b: &Path) -> bool {
|
||||
match (a.canonicalize(), b.canonicalize()) {
|
||||
(Ok(x), Ok(y)) => x == y,
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// Timings of one autosave, for the performance budget.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct WriteStats {
|
||||
pub bytes: u64,
|
||||
pub serialize_ms: f64,
|
||||
pub write_ms: f64,
|
||||
}
|
||||
|
||||
/// Writes the recovery copy of session `id`: the document, then its description, each atomic.
|
||||
pub fn write(dir: &Path, id: &str, doc: &Document, meta: &RecoveryMeta) -> Result<WriteStats> {
|
||||
check_id(id)?;
|
||||
let target = document_path(dir, id);
|
||||
if meta.original.as_deref().is_some_and(|o| same_file(o, &target)) {
|
||||
return Err(EngineError::State(format!("{} is the document itself; autosave never writes over it", target.display())));
|
||||
}
|
||||
// A file there that isn't a recovery copy (no lock or description beside it) is someone's.
|
||||
let ours = file(dir, id, "lock").is_file() || file(dir, id, "json").is_file();
|
||||
if target.exists() && !ours {
|
||||
return Err(EngineError::State(format!("{} is not an autosave; autosave never writes over it", target.display())));
|
||||
}
|
||||
let t = Instant::now();
|
||||
let json = format::to_json(doc)?;
|
||||
let serialize_ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
let t = Instant::now();
|
||||
std::fs::create_dir_all(dir)?;
|
||||
write_atomic(&target, json.as_bytes())?;
|
||||
let mut meta = meta.clone();
|
||||
meta.session = id.to_string();
|
||||
let text = serde_json::to_string_pretty(&meta).map_err(|e| EngineError::Format(e.to_string()))?;
|
||||
write_atomic(&file(dir, id, "json"), text.as_bytes())?;
|
||||
Ok(WriteStats { bytes: json.len() as u64, serialize_ms, write_ms: t.elapsed().as_secs_f64() * 1000.0 })
|
||||
}
|
||||
|
||||
/// Removes session `id`'s recovery copy and description (and leftover temp files), keeping its
|
||||
/// lock. Returns how many files went.
|
||||
pub fn clear(dir: &Path, id: &str) -> Result<usize> {
|
||||
check_id(id)?;
|
||||
let mut n = 0;
|
||||
for ext in ["anicraft", "json", "anicraft.tmp", "json.tmp"] {
|
||||
if std::fs::remove_file(file(dir, id, ext)).is_ok() {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Whether session `id` is running: its lock file is locked by a live process.
|
||||
pub fn is_live(dir: &Path, id: &str) -> bool {
|
||||
let Ok(f) = OpenOptions::new().read(true).write(true).open(file(dir, id, "lock")) else { return false };
|
||||
match f.try_lock() {
|
||||
Ok(()) => {
|
||||
let _ = f.unlock();
|
||||
false
|
||||
}
|
||||
Err(std::fs::TryLockError::WouldBlock) => true,
|
||||
// No locking on this file system: we can't tell, so offer it (restoring only reads).
|
||||
Err(std::fs::TryLockError::Error(_)) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_meta(dir: &Path, id: &str) -> RecoveryMeta {
|
||||
let path = file(dir, id, "json");
|
||||
let small = std::fs::metadata(&path).is_ok_and(|m| m.len() <= MAX_META_BYTES);
|
||||
let meta = if small { std::fs::read_to_string(&path).ok().and_then(|t| serde_json::from_str::<RecoveryMeta>(&t).ok()) } else { None };
|
||||
let mut meta = meta.unwrap_or_else(|| RecoveryMeta { name: "Untitled".into(), ..Default::default() });
|
||||
meta.session = id.to_string();
|
||||
if meta.name.trim().is_empty() {
|
||||
meta.name = display_name(meta.original.as_deref());
|
||||
}
|
||||
meta.name = meta.name.chars().take(256).collect();
|
||||
meta
|
||||
}
|
||||
|
||||
/// Recovery copies in `dir` left by sessions that are no longer running (not `own`), newest
|
||||
/// first. A missing or unreadable folder has none.
|
||||
pub fn scan(dir: &Path, own: Option<&str>) -> Vec<Entry> {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut out: Vec<Entry> = rd
|
||||
.take(MAX_SCAN)
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let name = e.file_name();
|
||||
let id = name.to_str()?.strip_suffix(".anicraft")?.to_string();
|
||||
// Ours only: a session's lock or description sits beside its copy (a document the
|
||||
// user saved into this folder has neither).
|
||||
let ours = file(dir, &id, "lock").is_file() || file(dir, &id, "json").is_file();
|
||||
if !valid_id(&id) || !ours || own == Some(id.as_str()) || is_live(dir, &id) {
|
||||
return None;
|
||||
}
|
||||
let bytes = e.metadata().ok().filter(|m| m.is_file())?.len();
|
||||
let meta = read_meta(dir, &id);
|
||||
Some(Entry { document: e.path(), session: id, meta, bytes })
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| b.meta.saved_at.cmp(&a.meta.saved_at).then_with(|| a.session.cmp(&b.session)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The entry for session `id`, if it was left behind.
|
||||
pub fn find(dir: &Path, id: &str) -> Result<Entry> {
|
||||
check_id(id)?;
|
||||
if is_live(dir, id) {
|
||||
return Err(EngineError::State("that document is open in another AniCraft window; it is still being autosaved there".into()));
|
||||
}
|
||||
let document = document_path(dir, id);
|
||||
let ours = file(dir, id, "lock").is_file() || file(dir, id, "json").is_file();
|
||||
let bytes = std::fs::metadata(&document).ok().filter(|m| ours && m.is_file()).ok_or_else(|| EngineError::State(format!("no autosaved document '{id}' in {}", dir.display())))?.len();
|
||||
Ok(Entry { session: id.to_string(), document, meta: read_meta(dir, id), bytes })
|
||||
}
|
||||
|
||||
/// Removes lock files of ended sessions that left no recovery copy (sessions that crashed
|
||||
/// with nothing unsaved). Returns how many went.
|
||||
pub fn prune(dir: &Path) -> usize {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else { return 0 };
|
||||
let stale: Vec<String> = rd
|
||||
.take(MAX_SCAN)
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().to_str()?.strip_suffix(".lock").map(str::to_string))
|
||||
.filter(|id| valid_id(id) && !document_path(dir, id).exists() && !is_live(dir, id))
|
||||
.collect();
|
||||
stale.iter().filter(|id| std::fs::remove_file(file(dir, id, "lock")).is_ok()).count()
|
||||
}
|
||||
|
||||
/// Loads a left-behind recovery copy.
|
||||
pub fn load(dir: &Path, id: &str) -> Result<(Document, RecoveryMeta)> {
|
||||
let e = find(dir, id)?;
|
||||
let doc = format::load(&e.document)?;
|
||||
Ok((doc, e.meta))
|
||||
}
|
||||
|
||||
/// Deletes a left-behind recovery copy and everything else of its session. Irreversible.
|
||||
pub fn discard(dir: &Path, id: &str) -> Result<usize> {
|
||||
find(dir, id)?;
|
||||
let n = clear(dir, id)?;
|
||||
let _ = std::fs::remove_file(file(dir, id, "lock"));
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
// ----- the running session ----------------------------------------------------------------------
|
||||
|
||||
/// A running session's identity, held as an exclusive lock on `<id>.lock` until it is
|
||||
/// [released](SessionLock::release) or the process ends.
|
||||
#[derive(Debug)]
|
||||
pub struct SessionLock {
|
||||
file: File,
|
||||
dir: PathBuf,
|
||||
id: String,
|
||||
}
|
||||
|
||||
impl SessionLock {
|
||||
/// Creates the folder if needed and takes a fresh session id.
|
||||
pub fn acquire(dir: &Path) -> Result<SessionLock> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let millis = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis());
|
||||
let base = format!("{millis:x}-{}", std::process::id());
|
||||
for n in 0..64u32 {
|
||||
let id = if n == 0 { base.clone() } else { format!("{base}-{n}") };
|
||||
let path = file(dir, &id, "lock");
|
||||
// `create_new`: two sessions never share a lock file, even when started together.
|
||||
let Ok(f) = OpenOptions::new().read(true).write(true).create_new(true).open(&path) else { continue };
|
||||
match f.try_lock() {
|
||||
Ok(()) => return Ok(SessionLock { file: f, dir: dir.to_path_buf(), id }),
|
||||
Err(std::fs::TryLockError::Error(e)) if e.kind() == std::io::ErrorKind::Unsupported => {
|
||||
// A file system without locks: run without liveness (see `is_live`).
|
||||
return Ok(SessionLock { file: f, dir: dir.to_path_buf(), id });
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
Err(EngineError::State(format!("could not start a recovery session in {}", dir.display())))
|
||||
}
|
||||
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
/// Ends the session cleanly: unlocks and removes the lock file. Call [`clear`] first unless
|
||||
/// the recovery copy should be offered next time.
|
||||
pub fn release(self) {
|
||||
let _ = self.file.unlock();
|
||||
drop(self.file);
|
||||
let _ = std::fs::remove_file(file(&self.dir, &self.id, "lock"));
|
||||
}
|
||||
}
|
||||
|
||||
// ----- background writer ------------------------------------------------------------------------
|
||||
|
||||
enum Job {
|
||||
Write { doc: Document, meta: Box<RecoveryMeta>, tag: u64 },
|
||||
Clear { tag: u64 },
|
||||
}
|
||||
|
||||
/// What the background writer finished.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Outcome {
|
||||
Written { tag: u64, stats: WriteStats },
|
||||
Cleared { tag: u64 },
|
||||
Failed { tag: u64, error: String },
|
||||
}
|
||||
|
||||
/// Writes recovery copies on its own thread. Jobs run in order; when several are waiting only
|
||||
/// the newest runs (each write replaces the last, and a clear removes it), so a slow disk never
|
||||
/// builds a queue. Dropping it stops the thread but leaves the files: only
|
||||
/// [`Autosaver::finish`] decides whether a session ended cleanly.
|
||||
pub struct Autosaver {
|
||||
lock: Option<SessionLock>,
|
||||
tx: Option<Sender<Job>>,
|
||||
done: Receiver<Outcome>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
next_tag: u64,
|
||||
}
|
||||
|
||||
impl Autosaver {
|
||||
pub fn start(lock: SessionLock) -> Result<Autosaver> {
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Job>();
|
||||
let (done_tx, done) = std::sync::mpsc::channel();
|
||||
let dir = lock.dir.clone();
|
||||
let id = lock.id.clone();
|
||||
let thread = std::thread::Builder::new().name("anicraft-autosave".into()).spawn(move || worker(&dir, &id, &rx, &done_tx))?;
|
||||
Ok(Autosaver { lock: Some(lock), tx: Some(tx), done, thread: Some(thread), next_tag: 0 })
|
||||
}
|
||||
|
||||
pub fn id(&self) -> &str {
|
||||
self.lock.as_ref().map_or("", |l| l.id.as_str())
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> Option<&Path> {
|
||||
self.lock.as_ref().map(|l| l.dir.as_path())
|
||||
}
|
||||
|
||||
fn send(&mut self, job: impl FnOnce(u64) -> Job) -> u64 {
|
||||
self.next_tag += 1;
|
||||
let tag = self.next_tag;
|
||||
if let Some(tx) = &self.tx {
|
||||
let _ = tx.send(job(tag));
|
||||
}
|
||||
tag
|
||||
}
|
||||
|
||||
/// Queues a write of `doc` (a cheap snapshot). Returns its tag.
|
||||
pub fn write(&mut self, doc: Document, original: Option<&Path>) -> u64 {
|
||||
let meta = RecoveryMeta::describe(self.id(), &doc, original);
|
||||
self.send(|tag| Job::Write { doc, meta: Box::new(meta), tag })
|
||||
}
|
||||
|
||||
/// Queues removal of this session's recovery copy (after a save, or when the work is gone).
|
||||
pub fn clear(&mut self) -> u64 {
|
||||
self.send(|tag| Job::Clear { tag })
|
||||
}
|
||||
|
||||
/// Finished jobs since the last call.
|
||||
pub fn poll(&self) -> Vec<Outcome> {
|
||||
let mut v = Vec::new();
|
||||
loop {
|
||||
match self.done.try_recv() {
|
||||
Ok(o) => v.push(o),
|
||||
Err(TryRecvError::Empty | TryRecvError::Disconnected) => return v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the session. `Some(doc)`: the work isn't safe yet, so write it one last time and
|
||||
/// keep it for the next start. `None`: a clean exit, so the recovery copy and the lock go.
|
||||
/// Waits for the writer (at most one write).
|
||||
pub fn finish(mut self, last: Option<(Document, Option<PathBuf>)>) -> Vec<Outcome> {
|
||||
let clean = last.is_none();
|
||||
match last {
|
||||
Some((doc, original)) => {
|
||||
self.write(doc, original.as_deref());
|
||||
}
|
||||
None => {
|
||||
self.clear();
|
||||
}
|
||||
}
|
||||
self.stop();
|
||||
let out = self.poll();
|
||||
if let Some(lock) = self.lock.take() {
|
||||
if clean {
|
||||
lock.release();
|
||||
} else {
|
||||
drop(lock); // unlocked by closing; the copy stays for the next start
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn stop(&mut self) {
|
||||
self.tx = None;
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Autosaver {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
fn worker(dir: &Path, id: &str, rx: &Receiver<Job>, done: &Sender<Outcome>) {
|
||||
while let Ok(mut job) = rx.recv() {
|
||||
// Only the newest waiting job matters.
|
||||
while let Ok(newer) = rx.try_recv() {
|
||||
job = newer;
|
||||
}
|
||||
let outcome = match job {
|
||||
Job::Write { doc, meta, tag } => match write(dir, id, &doc, &meta) {
|
||||
Ok(stats) => Outcome::Written { tag, stats },
|
||||
Err(e) => Outcome::Failed { tag, error: e.to_string() },
|
||||
},
|
||||
Job::Clear { tag } => match clear(dir, id) {
|
||||
Ok(_) => Outcome::Cleared { tag },
|
||||
Err(e) => Outcome::Failed { tag, error: e.to_string() },
|
||||
},
|
||||
};
|
||||
if done.send(outcome).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_doc::sample;
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("anicraft-recovery-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_cannot_escape_the_folder() {
|
||||
for bad in ["", "..", "../x", "a/b", "a\\b", "C:", "x.y", "é", &"a".repeat(65)] {
|
||||
assert!(!valid_id(bad), "{bad}");
|
||||
}
|
||||
assert!(valid_id("19a0b3c-1234-2"));
|
||||
let dir = tmp("ids");
|
||||
assert!(write(&dir, "../evil", &Document::default(), &RecoveryMeta::default()).is_err());
|
||||
assert!(load(&dir, "..\\evil").is_err());
|
||||
assert!(discard(&dir, "a/b").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_is_atomic_and_round_trips() {
|
||||
let dir = tmp("write");
|
||||
let doc = sample::demo();
|
||||
let meta = RecoveryMeta::describe("s1", &doc, Some(Path::new("/work/walk.anicraft")));
|
||||
let st = write(&dir, "s1", &doc, &meta).unwrap();
|
||||
assert!(st.bytes > 0);
|
||||
// No temp files survive a write.
|
||||
let names: Vec<String> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
assert!(names.iter().all(|n| !n.ends_with(".tmp")), "{names:?}");
|
||||
let (back, m) = load(&dir, "s1").unwrap();
|
||||
assert_eq!(back, doc);
|
||||
assert_eq!(m.name, "walk.anicraft");
|
||||
assert_eq!(m.original.as_deref(), Some(Path::new("/work/walk.anicraft")));
|
||||
// A crash mid-write (a temp file left half-written) keeps the previous copy intact.
|
||||
std::fs::write(dir.join("s1.anicraft.tmp"), b"{\"format\":\"anica").unwrap();
|
||||
assert_eq!(load(&dir, "s1").unwrap().0, doc);
|
||||
assert_eq!(scan(&dir, None).len(), 1, "temp files are not entries");
|
||||
// The next write replaces both.
|
||||
let mut d2 = doc.clone();
|
||||
d2.stage.width = 77;
|
||||
write(&dir, "s1", &d2, &meta).unwrap();
|
||||
assert_eq!(load(&dir, "s1").unwrap().0.stage.width, 77);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_writes_over_the_users_file() {
|
||||
let dir = tmp("own");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// A user who saved their document inside the recovery folder under a session-like name.
|
||||
let theirs = dir.join("mine.anicraft");
|
||||
std::fs::write(&theirs, b"precious").unwrap();
|
||||
let meta = RecoveryMeta::describe("mine", &Document::default(), Some(&theirs));
|
||||
assert!(write(&dir, "mine", &Document::default(), &meta).is_err());
|
||||
assert_eq!(std::fs::read(&theirs).unwrap(), b"precious");
|
||||
// Even when the copy doesn't claim to be it: a file that isn't an autosave stays.
|
||||
let meta = RecoveryMeta::describe("mine", &Document::default(), None);
|
||||
assert!(write(&dir, "mine", &Document::default(), &meta).is_err());
|
||||
assert_eq!(std::fs::read(&theirs).unwrap(), b"precious");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_sessions_are_not_offered_and_crashed_ones_are() {
|
||||
let dir = tmp("live");
|
||||
let lock = SessionLock::acquire(&dir).unwrap();
|
||||
let id = lock.id().to_string();
|
||||
write(&dir, &id, &sample::demo(), &RecoveryMeta::describe(&id, &sample::demo(), None)).unwrap();
|
||||
assert!(is_live(&dir, &id));
|
||||
assert!(scan(&dir, None).is_empty(), "a running session's copy is not offered");
|
||||
assert!(load(&dir, &id).is_err() && discard(&dir, &id).is_err());
|
||||
// The process "crashes": the OS drops the lock but the files stay.
|
||||
drop(lock);
|
||||
let found = scan(&dir, None);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].session, id);
|
||||
assert_eq!(found[0].meta.name, "Untitled");
|
||||
assert_eq!(scan(&dir, Some(&id)).len(), 0, "a session never offers its own copy");
|
||||
assert!(discard(&dir, &id).unwrap() >= 2);
|
||||
assert!(scan(&dir, None).is_empty());
|
||||
assert!(!file(&dir, &id, "lock").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_sessions_get_different_ids() {
|
||||
let dir = tmp("two");
|
||||
let a = SessionLock::acquire(&dir).unwrap();
|
||||
let b = SessionLock::acquire(&dir).unwrap();
|
||||
assert_ne!(a.id(), b.id());
|
||||
a.release();
|
||||
b.release();
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a clean release leaves nothing");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_in_the_folder_is_ignored_or_reported() {
|
||||
let dir = tmp("garbage");
|
||||
std::fs::create_dir_all(dir.join("folder.anicraft")).unwrap();
|
||||
std::fs::write(dir.join("bad id.anicraft"), b"x").unwrap();
|
||||
std::fs::write(dir.join("broken.anicraft"), b"not json").unwrap();
|
||||
std::fs::write(dir.join("broken.json"), b"{{{").unwrap();
|
||||
// A user's own document saved into the folder is not a recovery copy, and is never
|
||||
// discarded as one.
|
||||
std::fs::write(dir.join("mine.anicraft"), b"precious").unwrap();
|
||||
assert!(discard(&dir, "mine").is_err());
|
||||
assert_eq!(std::fs::read(dir.join("mine.anicraft")).unwrap(), b"precious");
|
||||
let found = scan(&dir, None);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].meta.name, "Untitled");
|
||||
assert!(load(&dir, "broken").is_err(), "a corrupt copy is an error, not a panic");
|
||||
assert!(scan(Path::new("/no/such/folder/anicraft"), None).is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosaver_writes_in_the_background_and_cleans_up_on_a_clean_exit() {
|
||||
let dir = tmp("saver");
|
||||
let mut a = Autosaver::start(SessionLock::acquire(&dir).unwrap()).unwrap();
|
||||
let id = a.id().to_string();
|
||||
let doc = sample::demo();
|
||||
for _ in 0..5 {
|
||||
a.write(doc.clone(), None);
|
||||
}
|
||||
let mut written = false;
|
||||
for _ in 0..500 {
|
||||
if a.poll().iter().any(|o| matches!(o, Outcome::Written { .. })) {
|
||||
written = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(written);
|
||||
assert!(document_path(&dir, &id).exists());
|
||||
a.finish(None);
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "clean exit removes the copy and the lock");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclean_finish_keeps_the_work_for_next_time() {
|
||||
let dir = tmp("unclean");
|
||||
let a = Autosaver::start(SessionLock::acquire(&dir).unwrap()).unwrap();
|
||||
let mut doc = sample::demo();
|
||||
doc.stage.width = 640;
|
||||
let out = a.finish(Some((doc.clone(), Some(PathBuf::from("/w/a.anicraft")))));
|
||||
assert!(out.iter().any(|o| matches!(o, Outcome::Written { .. })), "{out:?}");
|
||||
let found = scan(&dir, None);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].meta.name, "a.anicraft");
|
||||
assert_eq!(load(&dir, &found[0].session).unwrap().0.stage.width, 640);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_then_clear_leaves_no_copy() {
|
||||
let dir = tmp("clear");
|
||||
let mut a = Autosaver::start(SessionLock::acquire(&dir).unwrap()).unwrap();
|
||||
let id = a.id().to_string();
|
||||
a.write(sample::demo(), None);
|
||||
a.clear();
|
||||
// In order: the clear never races ahead of the write.
|
||||
for _ in 0..500 {
|
||||
if a.poll().iter().any(|o| matches!(o, Outcome::Cleared { .. })) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(!document_path(&dir, &id).exists());
|
||||
drop(a); // dropped without finish (a crash): the lock goes with the process
|
||||
assert!(scan(&dir, None).is_empty());
|
||||
assert_eq!(prune(&dir), 1, "the stale lock is tidied away");
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -577,6 +577,129 @@ fn file_commands_reject_bad_params() {
|
||||
assert!(s.execute("no.such.command", &json!({})).is_err());
|
||||
}
|
||||
|
||||
// ----- crash recovery (ADR 0015) -------------------------------------------------------------
|
||||
|
||||
/// A crash simulated end to end: a session autosaves unsaved work and dies without a clean
|
||||
/// exit; the next session finds the copy, restores it as unsaved work with its original path,
|
||||
/// and the copy can then be discarded (only with consent).
|
||||
#[test]
|
||||
fn crash_recovery_round_trip() {
|
||||
use crate::recovery::{Autosaver, Outcome, SessionLock};
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-crash-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("walk.anicraft");
|
||||
let d = dir.display().to_string();
|
||||
|
||||
// Session 1: saves, keeps working, autosaves in the background, then "crashes".
|
||||
let mut s1 = Session::new(sample::demo());
|
||||
run(&mut s1, "file.save", json!({"path": original.display().to_string()}));
|
||||
run(&mut s1, "draw.rect", json!({"x": 10, "y": 10, "w": 50, "h": 40}));
|
||||
assert!(s1.is_dirty());
|
||||
let mut saver = Autosaver::start(SessionLock::acquire(&dir).unwrap()).unwrap();
|
||||
saver.write(s1.doc.clone(), s1.path.as_deref());
|
||||
let mut done = false;
|
||||
for _ in 0..500 {
|
||||
if saver.poll().iter().any(|o| matches!(o, Outcome::Written { .. })) {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(done, "autosave finished");
|
||||
// While it runs, nobody else is offered its copy.
|
||||
let mut s2 = Session::default();
|
||||
assert_eq!(run(&mut s2, "file.recovery_list", json!({"dir": d}))["documents"].as_array().unwrap().len(), 0);
|
||||
drop(saver); // the crash: no clean finish, the OS drops the lock
|
||||
|
||||
// Session 2 (the next start) finds it.
|
||||
let list = run(&mut s2, "file.recovery_list", json!({"dir": d}));
|
||||
let docs = list["documents"].as_array().unwrap();
|
||||
assert_eq!(docs.len(), 1, "{list}");
|
||||
assert_eq!(docs[0]["name"], "walk.anicraft");
|
||||
assert_eq!(docs[0]["original_newer"], false);
|
||||
let id = docs[0]["session"].as_str().unwrap().to_string();
|
||||
|
||||
// Restoring over unsaved work asks first (irreversible), like Open.
|
||||
run(&mut s2, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5}));
|
||||
assert!(matches!(s2.execute("file.recover", &json!({"dir": d, "session": id})), Err(EngineError::NeedsConfirmation(_))));
|
||||
let v = run(&mut s2, "file.recover", json!({"dir": d, "session": id, "confirm": true}));
|
||||
assert_eq!(v["recovered"], json!(id));
|
||||
assert_eq!(s2.doc, s1.doc, "the work is back exactly");
|
||||
assert!(s2.is_dirty(), "restored work is unsaved");
|
||||
assert_eq!(s2.path.as_deref(), Some(original.as_path()), "Save goes back to the original");
|
||||
assert_eq!(s2.history_len(), 0);
|
||||
|
||||
// Discarding needs explicit consent, whoever asks.
|
||||
assert!(matches!(s2.execute("file.discard_recovery", &json!({"dir": d, "session": id})), Err(EngineError::NeedsConfirmation(_))));
|
||||
assert!(s2.confirmation("file.discard_recovery", &json!({"dir": d, "session": id})).is_some_and(|c| c.irreversible));
|
||||
run(&mut s2, "file.discard_recovery", json!({"dir": d, "session": id, "confirm": true}));
|
||||
assert_eq!(run(&mut s2, "file.recovery_list", json!({"dir": d}))["documents"].as_array().unwrap().len(), 0);
|
||||
assert!(original.exists(), "the user's own file is untouched");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The original was saved after the autosave (a save just before the crash): restoring must
|
||||
/// not point Save at it, or older work would replace newer work.
|
||||
#[test]
|
||||
fn recovery_never_replaces_a_newer_original() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-crash-newer-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("a.anicraft");
|
||||
let d = dir.display().to_string();
|
||||
let mut s = Session::new(sample::demo());
|
||||
s.path = Some(original.clone());
|
||||
let mut meta = crate::recovery::RecoveryMeta::describe("old", &s.doc, Some(&original));
|
||||
meta.saved_at = 1; // long ago
|
||||
crate::recovery::write(&dir, "old", &s.doc, &meta).unwrap();
|
||||
std::fs::write(&original, b"newer").unwrap();
|
||||
let mut s2 = Session::default();
|
||||
let v = run(&mut s2, "file.recover", json!({"dir": d, "session": "old"}));
|
||||
assert_eq!(v["original_newer"], true);
|
||||
assert!(s2.path.is_none(), "Save asks for a name instead");
|
||||
assert!(s2.is_dirty());
|
||||
assert_eq!(std::fs::read(&original).unwrap(), b"newer");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_commands_survive_hostile_params() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-crash-hostile-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let d = dir.display().to_string();
|
||||
let mut s = Session::new(sample::demo());
|
||||
let hostile = [
|
||||
Value::Null,
|
||||
json!({}),
|
||||
json!({"dir": 5}),
|
||||
json!({"dir": ""}),
|
||||
json!({"dir": " "}),
|
||||
json!({"dir": d, "session": "../../etc/passwd"}),
|
||||
json!({"dir": d, "session": "a\\..\\b"}),
|
||||
json!({"dir": d, "session": ""}),
|
||||
json!({"dir": d, "session": "x".repeat(10_000)}),
|
||||
json!({"dir": d, "session": 7, "confirm": "yes"}),
|
||||
json!({"dir": d, "session": "missing", "confirm": true}),
|
||||
json!({"dir": "/no/such/folder/at/all", "session": "abc", "confirm": true}),
|
||||
];
|
||||
for id in ["file.recovery_list", "file.recover", "file.discard_recovery", "file.autosave"] {
|
||||
for p in &hostile {
|
||||
let _ = s.execute(id, p);
|
||||
}
|
||||
}
|
||||
// Nothing escaped the folder, and the document is intact.
|
||||
assert!(!dir.join("..").join("etc").exists() || std::path::Path::new("/etc").exists());
|
||||
// Headless autosave writes a copy that lists (no lock: headless sessions are not "live").
|
||||
let v = run(&mut s, "file.autosave", json!({"dir": d}));
|
||||
assert!(v["bytes"].as_u64().unwrap() > 0);
|
||||
let list = run(&mut s, "file.recovery_list", json!({"dir": d}));
|
||||
let ids: Vec<&str> = list["documents"].as_array().unwrap().iter().filter_map(|e| e["session"].as_str()).collect();
|
||||
assert!(ids.contains(&format!("headless-{}", std::process::id()).as_str()), "{ids:?}");
|
||||
assert!(ids.iter().all(|i| crate::recovery::valid_id(i)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
// ----- paths: pen, pencil, point editing ---------------------------------------------------
|
||||
|
||||
@@ -959,7 +1082,8 @@ fn opening_an_xfl_folder_imports_it_untitled() {
|
||||
dir.join("DOMDocument.xml"),
|
||||
r##"<DOMDocument width="320" height="240" frameRate="12"><timelines><DOMTimeline name="Scene 1"><layers><DOMLayer name="Art"><frames><DOMFrame index="0" duration="6"><elements>
|
||||
<DOMShape><fills><FillStyle index="1"><SolidColor color="#FF8800"/></FillStyle></fills><edges><Edge fillStyle1="1" edges="!0 0|2000 0|2000 2000|0 2000|0 0"/></edges></DOMShape>
|
||||
<DOMStaticText/></elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>"##,
|
||||
<DOMDynamicText name="title" width="200"><matrix><Matrix tx="20" ty="30"/></matrix><textRuns><DOMTextRun><characters>Hello</characters><textAttrs><DOMTextAttrs face="NoSuchFamilyAtAll-Bold" size="20" fillColor="#0000FF"/></textAttrs></DOMTextRun></textRuns></DOMDynamicText>
|
||||
</elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>"##,
|
||||
)
|
||||
.unwrap();
|
||||
let mut s = Session::default();
|
||||
@@ -967,12 +1091,30 @@ 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 text fields"), "{v}");
|
||||
assert!(v["report"].as_str().unwrap().contains("1 dynamic and input text fields (imported as static text)"), "{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.
|
||||
let dl = s.display_list();
|
||||
assert!(dl.items.iter().any(|i| matches!(i.fill, Some(anicraft_doc::Paint::Solid(c)) if c == anicraft_doc::Rgba::hex(0xff8800))));
|
||||
// Text comes across as an editable text block when this computer has fonts (ADR 0015),
|
||||
// with the missing family named.
|
||||
if !anicraft_text::Fonts::get().families().is_empty() {
|
||||
assert!(v["report"].as_str().unwrap().contains("Fonts not on this computer"), "{v}");
|
||||
assert_eq!(v["missing_fonts"], json!(["No Such Family At All"]));
|
||||
let text = s.doc.timeline(s.scene).layers[0].keyframes[0].elements.iter().find(|e| matches!(e.kind, ElementKind::Text(_))).cloned().expect("a text element");
|
||||
assert_eq!(text.name, "title");
|
||||
assert!(dl.items.iter().any(|i| matches!(i.fill, Some(anicraft_doc::Paint::Solid(c)) if c == anicraft_doc::Rgba::hex(0x0000ff))), "the text renders");
|
||||
s.selection = vec![text.id];
|
||||
run(&mut s, "text.edit", json!({"text": "Hello again"}));
|
||||
// Saved and opened again, it is the same text.
|
||||
let file = dir.join("imported.anicraft");
|
||||
run(&mut s, "file.save", json!({"path": file.display().to_string()}));
|
||||
let mut back = Session::default();
|
||||
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));
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "anicraft-plugins"
|
||||
description = "AniCraft L0: sandboxed WebAssembly plug-ins, a resource-limited wasmi host for the AniCraft plug-in ABI"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
# Pure-Rust WebAssembly interpreter (MIT OR Apache-2.0), the Craft-family plug-in host. Without
|
||||
# `wat` (text parsing is test-only) and memory64; `validate` keeps full module validation on;
|
||||
# the portable dispatcher never overflows the host stack (see docs/plugins.md).
|
||||
wasmi = { version = "2.0.0", default-features = false, features = ["std", "validate", "stable", "portable-dispatch"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# WebAssembly text -> binary for the test fixtures, so no binary blobs are committed
|
||||
# (Apache-2.0 WITH LLVM-exception).
|
||||
wat = "1.228"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Sandboxed WebAssembly plug-ins for AniCraft (layer L0; ADR 0017, `docs/plugins.md`).
|
||||
//!
|
||||
//! A plug-in is a core WebAssembly module that implements the AniCraft plug-in ABI (v1). It
|
||||
//! runs in [`wasmi`], a pure-Rust interpreter, with:
|
||||
//!
|
||||
//! - **no host imports but the AniCraft ABI**: the module may import only `anicraft.call` and
|
||||
//! `anicraft.response`, a JSON request/response channel to its [`Host`]. No WASI, file
|
||||
//! system, network, clock or randomness; a module importing anything else is rejected;
|
||||
//! - an **instruction budget** (fuel), metered in slices so a wall-clock deadline is enforced
|
||||
//! too (native builds), so endless loops end with an error;
|
||||
//! - a **linear-memory cap**, a **call-depth cap** and wasmi's strict module limits;
|
||||
//! - **bounded traffic**: request, response, log and host-call counts are capped;
|
||||
//! - a **fresh instance per run**, so no state survives between runs.
|
||||
//!
|
||||
//! This crate knows nothing about documents: the engine implements [`Host`] over its command
|
||||
//! registry. Every failure (malformed module, trap, exhausted budget, bad output) is an
|
||||
//! [`Error`]; nothing a module does can panic or hang the host.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod manifest;
|
||||
pub mod registry;
|
||||
mod runtime;
|
||||
|
||||
pub use manifest::{Kind, Manifest, ParamKind, ParamSpec, SelectionNeed};
|
||||
pub use registry::{FolderReport, Registry};
|
||||
pub use runtime::{ABI_VERSION, IMPORT_MODULE, Limits, Plugin, RunReport};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// A plug-in error. Every way a module can misbehave ends here, never in a panic.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("not a valid plug-in module: {0}")]
|
||||
Module(String),
|
||||
#[error("plug-in ABI: {0}")]
|
||||
Abi(String),
|
||||
#[error("plug-in manifest: {0}")]
|
||||
Manifest(String),
|
||||
#[error("plug-in stopped with an error: {0}")]
|
||||
Trap(String),
|
||||
#[error("plug-in exceeded its {0}")]
|
||||
Limit(String),
|
||||
#[error("plug-in parameters: {0}")]
|
||||
Params(String),
|
||||
#[error("plug-in failed: {0}")]
|
||||
Failed(String),
|
||||
#[error("no plug-in “{0}” is installed")]
|
||||
NotFound(String),
|
||||
#[error("{0}")]
|
||||
Io(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// What a running plug-in talks to. The runtime parses each `anicraft.call` request, handles
|
||||
/// `log` itself and hands every other operation here; the answer goes back to the plug-in as
|
||||
/// `{"ok": true, "result": …}` or `{"ok": false, "error": "…"}`.
|
||||
pub trait Host {
|
||||
/// Handles one request: `op` is its `"op"` field, `request` the whole JSON object.
|
||||
fn request(&mut self, op: &str, request: &Value) -> std::result::Result<Value, String>;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
//! The plug-in manifest (`ac_manifest`) and its parameter schema.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
pub const MAX_MANIFEST_BYTES: usize = 64 * 1024;
|
||||
/// Most parameters a plug-in may declare.
|
||||
pub const MAX_PARAMS: usize = 32;
|
||||
|
||||
/// What a plug-in is. ABI v1 has command plug-ins only; exporters, easing presets and frame
|
||||
/// scripts are later kinds on the same host (ADR 0017).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Kind {
|
||||
/// Runs once on demand (a menu item, the palette, `plugin.run`) and edits the document
|
||||
/// through commands: generators and selection transforms.
|
||||
Command,
|
||||
}
|
||||
|
||||
/// Whether a command plug-in works on the selection.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SelectionNeed {
|
||||
/// Runs with or without a selection (a generator).
|
||||
#[default]
|
||||
Optional,
|
||||
/// Needs selected elements; menus disable it without them (a selection transform).
|
||||
Required,
|
||||
}
|
||||
|
||||
/// One declared parameter: its label in the dialog, and its type.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ParamSpec {
|
||||
pub label: String,
|
||||
pub kind: ParamKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ParamKind {
|
||||
/// A real number in `min..=max` (a slider in the dialog).
|
||||
Number { min: f64, max: f64, default: f64 },
|
||||
/// A whole number in `min..=max`.
|
||||
Int { min: i64, max: i64, default: i64 },
|
||||
/// A checkbox.
|
||||
Bool { default: bool },
|
||||
/// One of `options` (a dropdown).
|
||||
Choice { options: Vec<String>, default: String },
|
||||
/// A colour, `#rrggbb` or `#rrggbbaa` (a swatch).
|
||||
Color { default: String },
|
||||
}
|
||||
|
||||
/// The manifest a plug-in returns from `ac_manifest` (UTF-8 JSON).
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Manifest {
|
||||
/// Stable id, `[A-Za-z0-9._-]{1,64}` (reverse-DNS style is recommended: `org.example.stars`).
|
||||
pub id: String,
|
||||
/// Menu label.
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub version: String,
|
||||
pub kind: Kind,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub author: String,
|
||||
#[serde(default)]
|
||||
pub selection: SelectionNeed,
|
||||
/// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest.
|
||||
#[serde(default, deserialize_with = "ordered_params")]
|
||||
pub params: Vec<(String, ParamSpec)>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
/// Parses and validates manifest JSON.
|
||||
pub fn parse(bytes: &[u8]) -> Result<Manifest> {
|
||||
if bytes.len() > MAX_MANIFEST_BYTES {
|
||||
return Err(Error::Manifest(format!("it is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len())));
|
||||
}
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("it is not UTF-8".into()))?;
|
||||
let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(e.to_string()))?;
|
||||
man.validate()?;
|
||||
Ok(man)
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<()> {
|
||||
if !valid_id(&self.id) {
|
||||
return Err(Error::Manifest(format!("invalid id {:?}: use 1-64 characters from A-Z a-z 0-9 . _ -", self.id)));
|
||||
}
|
||||
if !printable(&self.name, 64) {
|
||||
return Err(Error::Manifest("`name` must be 1-64 printable characters".into()));
|
||||
}
|
||||
if self.version.chars().count() > 32 || self.description.chars().count() > 1024 || self.author.chars().count() > 128 {
|
||||
return Err(Error::Manifest("`version`, `description` or `author` is too long".into()));
|
||||
}
|
||||
if [&self.version, &self.description, &self.author].iter().any(|s| s.chars().any(|c| (c.is_control() && c != '\n') || hidden_format(c))) {
|
||||
return Err(Error::Manifest("`version`, `description` and `author` must be printable text".into()));
|
||||
}
|
||||
for (i, (k, _)) in self.params.iter().enumerate() {
|
||||
if self.params.iter().take(i).any(|(o, _)| o == k) {
|
||||
return Err(Error::Manifest(format!("parameter `{k}` is declared twice")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The parameter notation the command palette and `plugin.list` show
|
||||
/// (`{count: int 1..500 = 120, color: color = "#ffffff", mode: "a"|"b"}`).
|
||||
pub fn params_notation(&self) -> String {
|
||||
let parts: Vec<String> = self
|
||||
.params
|
||||
.iter()
|
||||
.map(|(k, p)| match &p.kind {
|
||||
ParamKind::Number { min, max, default } => format!("{k}: {min}..{max} = {default}"),
|
||||
ParamKind::Int { min, max, default } => format!("{k}: int {min}..{max} = {default}"),
|
||||
ParamKind::Bool { default } => format!("{k}: bool = {default}"),
|
||||
ParamKind::Choice { options, default } => format!("{k}: {} = \"{default}\"", options.iter().map(|o| format!("\"{o}\"")).collect::<Vec<_>>().join("|")),
|
||||
ParamKind::Color { default } => format!("{k}: color = \"{default}\""),
|
||||
})
|
||||
.collect();
|
||||
format!("{{{}}}", parts.join(", "))
|
||||
}
|
||||
|
||||
/// The defaults of every parameter, as the plug-in receives them when none are given.
|
||||
pub fn defaults(&self) -> Map<String, Value> {
|
||||
self.resolve_params(&Value::Null).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Validates user `params` against the schema: missing keys take their defaults, numbers
|
||||
/// are clamped into range (ints rounded), unknown keys are dropped; a value of the wrong
|
||||
/// type, an unknown choice or a malformed colour is an error.
|
||||
pub fn resolve_params(&self, params: &Value) -> Result<Map<String, Value>> {
|
||||
let empty = Map::new();
|
||||
let given = match params {
|
||||
Value::Null => &empty,
|
||||
Value::Object(m) => m,
|
||||
_ => return Err(Error::Params("plug-in parameters must be a JSON object".into())),
|
||||
};
|
||||
let mut out = Map::new();
|
||||
for (k, spec) in &self.params {
|
||||
let v = given.get(k).filter(|v| !v.is_null());
|
||||
let wrong = |what: &str| Error::Params(format!("`{k}` must be {what}"));
|
||||
let resolved = match &spec.kind {
|
||||
ParamKind::Number { min, max, default } => match v {
|
||||
None => json!(default),
|
||||
Some(v) => json!(v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| wrong("a number"))?.clamp(*min, *max)),
|
||||
},
|
||||
ParamKind::Int { min, max, default } => match v {
|
||||
None => json!(default),
|
||||
Some(v) => {
|
||||
let f = v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| wrong("a number"))?;
|
||||
json!(f.round().clamp(*min as f64, *max as f64) as i64)
|
||||
}
|
||||
},
|
||||
ParamKind::Bool { default } => match v {
|
||||
None => json!(default),
|
||||
Some(v) => json!(v.as_bool().ok_or_else(|| wrong("true or false"))?),
|
||||
},
|
||||
ParamKind::Choice { options, default } => match v {
|
||||
None => json!(default),
|
||||
Some(v) => {
|
||||
let s = v.as_str().ok_or_else(|| wrong("a string"))?;
|
||||
if !options.iter().any(|o| o == s) {
|
||||
return Err(Error::Params(format!("`{k}` must be one of {}", options.join(", "))));
|
||||
}
|
||||
json!(s)
|
||||
}
|
||||
},
|
||||
ParamKind::Color { default } => match v {
|
||||
None => json!(default),
|
||||
Some(v) => {
|
||||
let s = v.as_str().filter(|s| valid_color(s)).ok_or_else(|| wrong("a colour like \"#ff8800\""))?;
|
||||
json!(s.to_ascii_lowercase())
|
||||
}
|
||||
},
|
||||
};
|
||||
out.insert(k.clone(), resolved);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the `params` object keeping its key order (serde_json's `Map` would sort it).
|
||||
fn ordered_params<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<(String, ParamSpec)>, D::Error> {
|
||||
struct V;
|
||||
impl<'de> serde::de::Visitor<'de> for V {
|
||||
type Value = Vec<(String, ParamSpec)>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("an object of parameter specs")
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> std::result::Result<Self::Value, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while let Some((k, v)) = map.next_entry::<String, Value>()? {
|
||||
if out.len() >= MAX_PARAMS {
|
||||
return Err(serde::de::Error::custom(format!("too many parameters (limit {MAX_PARAMS})")));
|
||||
}
|
||||
let spec = param_spec(&k, &v).map_err(serde::de::Error::custom)?;
|
||||
out.push((k, spec));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
d.deserialize_any(V)
|
||||
}
|
||||
|
||||
/// One parameter spec from its JSON object.
|
||||
fn param_spec(name: &str, v: &Value) -> std::result::Result<ParamSpec, String> {
|
||||
if !valid_key(name) {
|
||||
return Err(format!("invalid parameter name {name:?}: use 1-32 characters from a-z A-Z 0-9 _, not starting with _ (and not `id`)"));
|
||||
}
|
||||
let bad = |what: &str| format!("parameter `{name}`: {what}");
|
||||
let obj = v.as_object().ok_or_else(|| bad("must be an object like {\"type\": \"number\", …}"))?;
|
||||
let label = match obj.get("label") {
|
||||
None | Some(Value::Null) => humanize(name),
|
||||
Some(Value::String(s)) if printable(s, 48) => s.trim().to_string(),
|
||||
Some(_) => return Err(bad("`label` must be 1-48 printable characters")),
|
||||
};
|
||||
let num = |key: &str| -> std::result::Result<Option<f64>, String> {
|
||||
match obj.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_f64().filter(|f| f.is_finite() && f.abs() <= 1e12).map(Some).ok_or_else(|| bad(&format!("`{key}` must be a finite number"))),
|
||||
}
|
||||
};
|
||||
let kind = match obj.get("type").and_then(Value::as_str) {
|
||||
Some("number") => {
|
||||
let (min, max) = (num("min")?.unwrap_or(0.0), num("max")?.unwrap_or(1.0));
|
||||
if min > max {
|
||||
return Err(bad("`min` is above `max`"));
|
||||
}
|
||||
ParamKind::Number { min, max, default: num("default")?.unwrap_or(min).clamp(min, max) }
|
||||
}
|
||||
Some("int") => {
|
||||
let (min, max) = (num("min")?.unwrap_or(0.0).round() as i64, num("max")?.unwrap_or(1_000_000.0).round() as i64);
|
||||
if min > max {
|
||||
return Err(bad("`min` is above `max`"));
|
||||
}
|
||||
ParamKind::Int { min, max, default: (num("default")?.unwrap_or(min as f64).round() as i64).clamp(min, max) }
|
||||
}
|
||||
Some("bool") => ParamKind::Bool { default: obj.get("default").and_then(Value::as_bool).unwrap_or(false) },
|
||||
Some("choice") => {
|
||||
let options: Vec<String> = obj.get("options").and_then(Value::as_array).map(|a| a.iter().filter_map(|o| o.as_str().map(str::to_string)).collect()).unwrap_or_default();
|
||||
if options.is_empty() || options.len() > 32 || options.iter().any(|o| !printable(o, 48)) {
|
||||
return Err(bad("`options` must be 1-32 printable strings of up to 48 characters"));
|
||||
}
|
||||
let default = match obj.get("default").and_then(Value::as_str) {
|
||||
Some(d) if options.iter().any(|o| o == d) => d.to_string(),
|
||||
Some(_) => return Err(bad("`default` is not one of the options")),
|
||||
None => options.first().cloned().unwrap_or_default(),
|
||||
};
|
||||
ParamKind::Choice { options, default }
|
||||
}
|
||||
Some("color") => {
|
||||
let default = obj.get("default").and_then(Value::as_str).unwrap_or("#000000");
|
||||
if !valid_color(default) {
|
||||
return Err(bad("`default` must be a colour like \"#ff8800\""));
|
||||
}
|
||||
ParamKind::Color { default: default.to_ascii_lowercase() }
|
||||
}
|
||||
_ => return Err(bad("`type` must be number, int, bool, choice or color")),
|
||||
};
|
||||
Ok(ParamSpec { label, kind })
|
||||
}
|
||||
|
||||
/// `count_max` → "Count max".
|
||||
fn humanize(key: &str) -> String {
|
||||
let s = key.replace('_', " ");
|
||||
let mut c = s.chars();
|
||||
c.next().map_or_else(String::new, |f| f.to_uppercase().chain(c).collect())
|
||||
}
|
||||
|
||||
/// `[A-Za-z0-9._-]{1,64}`.
|
||||
pub fn valid_id(id: &str) -> bool {
|
||||
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
|
||||
}
|
||||
|
||||
fn valid_key(k: &str) -> bool {
|
||||
(1..=32).contains(&k.len()) && !k.starts_with('_') && k != "id" && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
}
|
||||
|
||||
/// `#rrggbb` or `#rrggbbaa`.
|
||||
pub fn valid_color(s: &str) -> bool {
|
||||
s.strip_prefix('#').is_some_and(|h| (h.len() == 6 || h.len() == 8) && h.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
}
|
||||
|
||||
/// 1..=`max` characters, none of them control or invisible format characters, at least one
|
||||
/// visible: a name that can't spoof or hide in a menu.
|
||||
fn printable(s: &str, max: usize) -> bool {
|
||||
let s = s.trim();
|
||||
let n = s.chars().count();
|
||||
(1..=max).contains(&n) && s.chars().all(|c| !c.is_control() && !hidden_format(c)) && s.chars().any(|c| !c.is_whitespace())
|
||||
}
|
||||
|
||||
/// Unicode format characters that change or hide text (bidi overrides, zero-width spaces,
|
||||
/// soft hyphens), except the zero-width (non-)joiner that some scripts need.
|
||||
fn hidden_format(c: char) -> bool {
|
||||
matches!(c, '\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}' | '\u{fff9}'..='\u{fffb}')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn man(params: &str) -> Result<Manifest> {
|
||||
Manifest::parse(format!(r#"{{"id":"org.test.x","name":"X","kind":"command","params":{params}}}"#).as_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_keep_their_order_and_resolve_with_defaults_and_clamping() {
|
||||
let m = man(r##"{"zeta":{"type":"int","min":1,"max":10,"default":3},"alpha":{"type":"number","min":0,"max":1,"default":0.5,"label":"Opacity"},"on":{"type":"bool"},"mode":{"type":"choice","options":["a","b"]},"tint":{"type":"color","default":"#FF8800"}}"##).unwrap();
|
||||
assert_eq!(m.params.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["zeta", "alpha", "on", "mode", "tint"]);
|
||||
assert_eq!(m.params[0].1.label, "Zeta");
|
||||
assert_eq!(m.params[1].1.label, "Opacity");
|
||||
let d = m.defaults();
|
||||
assert_eq!(d["zeta"], 3);
|
||||
assert_eq!(d["mode"], "a");
|
||||
assert_eq!(d["tint"], "#ff8800");
|
||||
let r = m.resolve_params(&json!({"zeta": 99.6, "alpha": -3, "on": true, "mode": "b", "tint": "#00ff00", "extra": 1})).unwrap();
|
||||
assert_eq!(r["zeta"], 10);
|
||||
assert_eq!(r["alpha"], 0.0);
|
||||
assert!(!r.contains_key("extra"));
|
||||
assert!(m.resolve_params(&json!({"mode": "c"})).is_err());
|
||||
assert!(m.resolve_params(&json!({"tint": "red"})).is_err());
|
||||
assert!(m.resolve_params(&json!({"on": 1})).is_err());
|
||||
assert!(m.resolve_params(&json!([1])).is_err());
|
||||
assert!(m.params_notation().starts_with("{zeta: int 1..10 = 3, alpha: 0..1 = 0.5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_manifests_are_rejected_with_a_reason() {
|
||||
let bad = [
|
||||
r#"{"id":"","name":"X","kind":"command"}"#,
|
||||
r#"{"id":"a b","name":"X","kind":"command"}"#,
|
||||
r#"{"id":"a","name":"","kind":"command"}"#,
|
||||
"{\"id\":\"a\",\"name\":\"\\u202eevil\",\"kind\":\"command\"}",
|
||||
r#"{"id":"a","name":"X","kind":"filter"}"#,
|
||||
r#"{"id":"a","name":"X"}"#,
|
||||
r#"{"id":"a","name":"X","kind":"command","params":{"_x":{"type":"int"}}}"#,
|
||||
r#"{"id":"a","name":"X","kind":"command","params":{"x":{"type":"int","min":5,"max":1}}}"#,
|
||||
r#"{"id":"a","name":"X","kind":"command","params":{"x":{"type":"wat"}}}"#,
|
||||
r#"{"id":"a","name":"X","kind":"command","params":{"x":{"type":"choice","options":[]}}}"#,
|
||||
r#"{"id":"a","name":"X","kind":"command","params":{"x":{"type":"color","default":"blue"}}}"#,
|
||||
r#"{"id":"a","name":"X","kind":"command","params":{"x":{"type":"number","min":1e400}}}"#,
|
||||
r#"{"id":"a","name":"X","kind":"command","params":{"x":{"type":"int"},"x":{"type":"int"}}}"#,
|
||||
"not json",
|
||||
];
|
||||
for b in bad {
|
||||
assert!(Manifest::parse(b.as_bytes()).is_err(), "accepted {b}");
|
||||
}
|
||||
assert!(Manifest::parse(&[0xff, 0xfe]).is_err());
|
||||
assert!(Manifest::parse(&vec![b' '; MAX_MANIFEST_BYTES + 1]).is_err());
|
||||
let many: Vec<String> = (0..=MAX_PARAMS).map(|i| format!("\"p{i}\":{{\"type\":\"bool\"}}")).collect();
|
||||
assert!(man(&format!("{{{}}}", many.join(","))).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! The installed plug-ins and the plug-ins folder.
|
||||
//!
|
||||
//! A [`Registry`] belongs to a session (not to the process), so tests, the CLI and the app
|
||||
//! each see exactly the plug-ins they installed. With a folder set (the app sets its per-OS
|
||||
//! settings folder), installing copies the module into it as `<id>.wasm`, so it is there on
|
||||
//! the next start, and removing deletes that copy.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{Error, Limits, Manifest, Plugin, Result};
|
||||
|
||||
/// Most `.wasm` files read from one folder.
|
||||
const MAX_FOLDER_FILES: usize = 1000;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Registry {
|
||||
folder: Option<PathBuf>,
|
||||
plugins: BTreeMap<String, Arc<Plugin>>,
|
||||
revision: u64,
|
||||
limits: Limits,
|
||||
}
|
||||
|
||||
/// What [`Registry::reload`] and [`Registry::load_folder`] did.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FolderReport {
|
||||
/// Ids of the plug-ins installed, in file-name order.
|
||||
pub loaded: Vec<String>,
|
||||
/// `(file, error)` for each `.wasm` that failed to load.
|
||||
pub failed: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// What [`Registry::install_file`] did.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Installed {
|
||||
pub plugin: Arc<Plugin>,
|
||||
/// The plug-in with the same id it replaced.
|
||||
pub replaced: Option<Arc<Plugin>>,
|
||||
/// Where it was copied (the plug-ins folder), if it was.
|
||||
pub copied_to: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// What [`Registry::remove`] did.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Removed {
|
||||
pub plugin: Arc<Plugin>,
|
||||
/// Its file in the plug-ins folder, now deleted.
|
||||
pub deleted: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn new(folder: Option<PathBuf>) -> Registry {
|
||||
Registry { folder, ..Registry::default() }
|
||||
}
|
||||
|
||||
/// The plug-ins folder, if one is set.
|
||||
pub fn folder(&self) -> Option<&Path> {
|
||||
self.folder.as_deref()
|
||||
}
|
||||
|
||||
pub fn set_folder(&mut self, folder: Option<PathBuf>) {
|
||||
self.folder = folder;
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
pub fn limits(&self) -> &Limits {
|
||||
&self.limits
|
||||
}
|
||||
|
||||
/// Limits for plug-ins loaded from now on.
|
||||
pub fn set_limits(&mut self, limits: Limits) {
|
||||
self.limits = limits;
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str) -> Option<Arc<Plugin>> {
|
||||
self.plugins.get(id).cloned()
|
||||
}
|
||||
|
||||
/// Installed plug-ins, sorted by id.
|
||||
pub fn list(&self) -> impl Iterator<Item = &Arc<Plugin>> {
|
||||
self.plugins.values()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.plugins.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.plugins.is_empty()
|
||||
}
|
||||
|
||||
/// Changes whenever a plug-in is installed or removed, or the folder changes (menus).
|
||||
pub fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
/// Installs a loaded plug-in in memory, replacing one with the same id.
|
||||
pub fn install(&mut self, plugin: Plugin) -> Arc<Plugin> {
|
||||
let p = Arc::new(plugin);
|
||||
self.plugins.insert(p.id().to_string(), p.clone());
|
||||
self.revision += 1;
|
||||
p
|
||||
}
|
||||
|
||||
/// Loads a module from bytes with this registry's limits and installs it in memory.
|
||||
pub fn install_bytes(&mut self, bytes: &[u8]) -> Result<Arc<Plugin>> {
|
||||
Ok(self.install(Plugin::load(bytes, self.limits.clone())?))
|
||||
}
|
||||
|
||||
/// Reads and validates the module at `path` without installing it.
|
||||
pub fn load_file(&self, path: &Path) -> Result<Plugin> {
|
||||
let bytes = read_module(path, self.limits.max_module_bytes)?;
|
||||
Ok(Plugin::load(&bytes, self.limits.clone())?.with_source(path))
|
||||
}
|
||||
|
||||
/// The manifest of the module at `path` and the installed plug-in it would replace.
|
||||
pub fn would_replace(&self, path: &Path) -> Option<(Manifest, Arc<Plugin>)> {
|
||||
let p = self.load_file(path).ok()?;
|
||||
let old = self.get(p.id())?;
|
||||
Some((p.manifest().clone(), old))
|
||||
}
|
||||
|
||||
/// Whether installing the module at `path` would overwrite a file in the plug-ins folder.
|
||||
pub fn install_overwrites(&self, path: &Path) -> Option<(Manifest, PathBuf)> {
|
||||
let folder = self.folder.as_deref()?;
|
||||
let p = self.load_file(path).ok()?;
|
||||
let dest = folder.join(format!("{}.wasm", p.id()));
|
||||
(dest.exists() && !same_file(&dest, path)).then(|| (p.manifest().clone(), dest))
|
||||
}
|
||||
|
||||
/// Installs the module at `path`. With a plug-ins folder, the module is copied into it as
|
||||
/// `<id>.wasm` (atomically) unless it is already there, so it loads on the next start.
|
||||
pub fn install_file(&mut self, path: &Path) -> Result<Installed> {
|
||||
let bytes = read_module(path, self.limits.max_module_bytes)?;
|
||||
let plugin = Plugin::load(&bytes, self.limits.clone())?;
|
||||
let id = plugin.id().to_string();
|
||||
let mut copied_to = None;
|
||||
let plugin = match &self.folder {
|
||||
Some(folder) if !in_folder(path, folder) => {
|
||||
let dest = folder.join(format!("{id}.wasm"));
|
||||
write_atomic(folder, &dest, &bytes)?;
|
||||
copied_to = Some(dest.clone());
|
||||
plugin.with_source(dest)
|
||||
}
|
||||
_ => plugin.with_source(path),
|
||||
};
|
||||
// An older copy of the same plug-in under another file name would load again later.
|
||||
let old = self.get(&id);
|
||||
if let (Some(old), Some(folder)) = (&old, &self.folder)
|
||||
&& let Some(src) = old.source()
|
||||
&& in_folder(src, folder)
|
||||
&& plugin.source().is_some_and(|s| !same_file(s, src))
|
||||
{
|
||||
let _ = std::fs::remove_file(src);
|
||||
}
|
||||
let plugin = self.install(plugin);
|
||||
Ok(Installed { plugin, replaced: old, copied_to })
|
||||
}
|
||||
|
||||
/// Whether `plugin`'s file lives in the plug-ins folder (removing it deletes that file).
|
||||
pub fn owns_file(&self, plugin: &Plugin) -> bool {
|
||||
matches!((plugin.source(), &self.folder), (Some(src), Some(folder)) if in_folder(src, folder))
|
||||
}
|
||||
|
||||
/// Uninstalls `id`, deleting its file when it lives in the plug-ins folder.
|
||||
pub fn remove(&mut self, id: &str) -> Result<Removed> {
|
||||
let plugin = self.get(id).ok_or_else(|| Error::NotFound(id.to_string()))?;
|
||||
let mut deleted = None;
|
||||
if self.owns_file(&plugin)
|
||||
&& let Some(src) = plugin.source()
|
||||
{
|
||||
match std::fs::remove_file(src) {
|
||||
Ok(()) => deleted = Some(src.to_path_buf()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(Error::Io(format!("can't delete {}: {e}", src.display()))),
|
||||
}
|
||||
}
|
||||
self.plugins.remove(id);
|
||||
self.revision += 1;
|
||||
Ok(Removed { plugin, deleted })
|
||||
}
|
||||
|
||||
/// Re-reads the plug-ins folder: plug-ins loaded from it are dropped and every `*.wasm` in
|
||||
/// it is loaded again (so edited, added and deleted files take effect). Plug-ins installed
|
||||
/// from elsewhere stay.
|
||||
pub fn reload(&mut self) -> Result<FolderReport> {
|
||||
let folder = self.folder.clone().ok_or_else(|| Error::Io("no plug-ins folder is set".into()))?;
|
||||
let from_folder: Vec<String> = self.plugins.values().filter(|p| self.owns_file(p)).map(|p| p.id().to_string()).collect();
|
||||
for id in from_folder {
|
||||
self.plugins.remove(&id);
|
||||
}
|
||||
self.revision += 1;
|
||||
if !folder.exists() {
|
||||
return Ok(FolderReport::default());
|
||||
}
|
||||
self.load_folder(&folder)
|
||||
}
|
||||
|
||||
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order. A bad
|
||||
/// module is reported and skipped; the others still load.
|
||||
pub fn load_folder(&mut self, dir: &Path) -> Result<FolderReport> {
|
||||
let rd = std::fs::read_dir(dir).map_err(|e| Error::Io(format!("{}: {e}", dir.display())))?;
|
||||
let mut files: Vec<PathBuf> = rd.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm"))).take(MAX_FOLDER_FILES * 4).collect();
|
||||
files.sort();
|
||||
files.truncate(MAX_FOLDER_FILES);
|
||||
let mut report = FolderReport::default();
|
||||
for f in files {
|
||||
match self.load_file(&f) {
|
||||
Ok(p) => report.loaded.push(self.install(p).id().to_string()),
|
||||
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
|
||||
}
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a module file, refusing anything that isn't a regular file or is over `max` bytes.
|
||||
fn read_module(path: &Path, max: usize) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
let io = |e: std::io::Error| Error::Io(format!("{}: {e}", path.display()));
|
||||
let meta = std::fs::metadata(path).map_err(io)?;
|
||||
if !meta.is_file() {
|
||||
return Err(Error::Io(format!("{} is not a file", path.display())));
|
||||
}
|
||||
if meta.len() > max as u64 {
|
||||
return Err(Error::Module(format!("{} is {} bytes (limit {max})", path.display(), meta.len())));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path).map_err(io)?.take(max as u64 + 1).read_to_end(&mut bytes).map_err(io)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Writes `dest` through a temporary file in the same folder, so a crash never leaves half a
|
||||
/// module behind.
|
||||
fn write_atomic(folder: &Path, dest: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let io = |e: std::io::Error| Error::Io(format!("can't write to the plug-ins folder {}: {e}", folder.display()));
|
||||
std::fs::create_dir_all(folder).map_err(io)?;
|
||||
let tmp = dest.with_extension("wasm.part");
|
||||
std::fs::write(&tmp, bytes).map_err(io)?;
|
||||
std::fs::rename(&tmp, dest).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
io(e)
|
||||
})
|
||||
}
|
||||
|
||||
fn canon(p: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
|
||||
}
|
||||
|
||||
fn same_file(a: &Path, b: &Path) -> bool {
|
||||
canon(a) == canon(b)
|
||||
}
|
||||
|
||||
/// Whether `file` sits directly in `folder`.
|
||||
fn in_folder(file: &Path, folder: &Path) -> bool {
|
||||
file.parent().is_some_and(|p| canon(p) == canon(folder))
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! The wasmi host: loading, instantiating and running a plug-in under resource limits.
|
||||
//!
|
||||
//! Host calls use wasmi's *resumable* calls: `anicraft.call` copies the request out of the
|
||||
//! module's memory and traps with a [`HostCall`] marker; the run loop answers it through the
|
||||
//! [`Host`] (which borrows the session mutably, so it can't live in the `'static` store) and
|
||||
//! resumes the module with the response length. Running out of fuel resumes the same way,
|
||||
//! slice by slice, so the deadline is checked while a module computes.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use wasmi::{Caller, Config, EnforcedLimits, Engine, Extern, ExternType, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val, WasmParams, WasmResults};
|
||||
|
||||
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest};
|
||||
use crate::{Error, Host, Result};
|
||||
|
||||
/// The plug-in ABI version this host implements (`ac_abi_version` must return it).
|
||||
pub const ABI_VERSION: i32 = 1;
|
||||
/// The only import module a plug-in may use.
|
||||
pub const IMPORT_MODULE: &str = "anicraft";
|
||||
/// The imports ABI v1 offers: `(name, params, results)` (all `i32`).
|
||||
const IMPORTS: [(&str, usize, usize); 2] = [("call", 2, 1), ("response", 2, 1)];
|
||||
|
||||
/// Fuel handed out per slice; between slices the host checks the deadline.
|
||||
const FUEL_SLICE: u64 = 10_000_000;
|
||||
/// Longest log line kept, in characters.
|
||||
const MAX_LOG_CHARS: usize = 500;
|
||||
|
||||
/// Resource limits for loading and running plug-ins.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Limits {
|
||||
/// Largest module accepted.
|
||||
pub max_module_bytes: usize,
|
||||
/// Cap on a plug-in's linear memory.
|
||||
pub max_memory_bytes: usize,
|
||||
/// Instructions (fuel) one run may use; loading (start function, manifest) gets a tenth.
|
||||
pub fuel: u64,
|
||||
/// Deepest call nesting.
|
||||
pub max_recursion_depth: usize,
|
||||
/// Wall-clock budget for one run, host calls included, in milliseconds. Native builds
|
||||
/// only: the web build has no clock in `std`, so the fuel budget alone bounds it there.
|
||||
pub wall_time_ms: u64,
|
||||
/// Most `anicraft.call` requests in one run.
|
||||
pub max_calls: u32,
|
||||
/// Largest request a plug-in may send, and largest response it is given.
|
||||
pub max_request_bytes: usize,
|
||||
pub max_response_bytes: usize,
|
||||
/// All requests of one run together: bounds what a run can add to the document.
|
||||
pub max_total_request_bytes: usize,
|
||||
/// Largest params object handed to `ac_run`.
|
||||
pub max_params_bytes: usize,
|
||||
/// Most log lines kept from one run (later ones are counted, not kept).
|
||||
pub max_log_lines: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_module_bytes: 16 << 20,
|
||||
max_memory_bytes: 256 << 20,
|
||||
fuel: 1_000_000_000,
|
||||
max_recursion_depth: 1024,
|
||||
wall_time_ms: 5_000,
|
||||
max_calls: 100_000,
|
||||
max_request_bytes: 1 << 20,
|
||||
max_response_bytes: 8 << 20,
|
||||
max_total_request_bytes: 64 << 20,
|
||||
max_params_bytes: 64 << 10,
|
||||
max_log_lines: 200,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a finished run did.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RunReport {
|
||||
/// `log` messages, in order (at most [`Limits::max_log_lines`]).
|
||||
pub log: Vec<String>,
|
||||
/// Log messages dropped beyond the limit.
|
||||
pub log_dropped: u32,
|
||||
/// Host requests made, and their total size.
|
||||
pub calls: u32,
|
||||
pub request_bytes: u64,
|
||||
/// Instructions used.
|
||||
pub fuel: u64,
|
||||
}
|
||||
|
||||
/// A loaded, validated plug-in. Cheap to share (`Arc`): every run gets its own store and
|
||||
/// instance.
|
||||
pub struct Plugin {
|
||||
manifest: Manifest,
|
||||
engine: Engine,
|
||||
module: Module,
|
||||
limits: Limits,
|
||||
size: usize,
|
||||
source: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Plugin {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Plugin").field("manifest", &self.manifest).field("size", &self.size).field("source", &self.source).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker a host import traps with to hand a request to the run loop.
|
||||
#[derive(Debug)]
|
||||
struct HostCall;
|
||||
|
||||
impl std::fmt::Display for HostCall {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("host call")
|
||||
}
|
||||
}
|
||||
|
||||
impl wasmi::errors::HostError for HostCall {}
|
||||
|
||||
/// Store data: the memory limiter and the request/response being exchanged.
|
||||
struct Ctx {
|
||||
limits: StoreLimits,
|
||||
max_request: usize,
|
||||
/// The request `anicraft.call` copied out, for the run loop to answer.
|
||||
pending: Option<Vec<u8>>,
|
||||
/// The last response, for `anicraft.response`.
|
||||
response: Vec<u8>,
|
||||
}
|
||||
|
||||
/// One live instance: a store with its own memory limit, and the module's exports.
|
||||
struct Live {
|
||||
store: Store<Ctx>,
|
||||
instance: Instance,
|
||||
memory: Memory,
|
||||
/// Instructions used by finished calls.
|
||||
used: u64,
|
||||
}
|
||||
|
||||
impl Live {
|
||||
fn func<P: WasmParams, R: WasmResults>(&self, name: &str) -> Result<TypedFunc<P, R>> {
|
||||
self.instance.get_typed_func::<P, R>(&self.store, name).map_err(|e| Error::Abi(format!("export `{name}`: {e}")))
|
||||
}
|
||||
|
||||
/// `len` bytes at `ptr` in the module's memory.
|
||||
fn bytes(&self, ptr: u32, len: u32, what: &str) -> Result<&[u8]> {
|
||||
let (p, l) = (ptr as usize, len as usize);
|
||||
self.memory.data(&self.store).get(p..p.saturating_add(l)).ok_or_else(|| Error::Abi(format!("{what} points outside the module's memory")))
|
||||
}
|
||||
}
|
||||
|
||||
/// When a run must stop (native builds: a wall-clock deadline).
|
||||
struct Deadline {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
at: std::time::Instant,
|
||||
}
|
||||
|
||||
impl Deadline {
|
||||
fn new(ms: u64) -> Self {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = ms;
|
||||
Self {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
at: std::time::Instant::now() + std::time::Duration::from_millis(ms),
|
||||
}
|
||||
}
|
||||
fn check(&self) -> Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::time::Instant::now() >= self.at {
|
||||
return Err(Error::Limit("time budget".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn wasm_err(e: wasmi::Error) -> Error {
|
||||
if e.as_trap_code() == Some(wasmi::TrapCode::OutOfFuel) { Error::Limit("instruction budget".into()) } else { Error::Trap(e.to_string()) }
|
||||
}
|
||||
|
||||
/// The module's exported memory, from inside a host function.
|
||||
fn caller_memory(caller: &Caller<'_, Ctx>) -> std::result::Result<Memory, wasmi::Error> {
|
||||
caller.get_export("memory").and_then(Extern::into_memory).ok_or_else(|| wasmi::Error::new("the module must export its memory as `memory`"))
|
||||
}
|
||||
|
||||
/// `anicraft.call(ptr, len) -> i32`: copies the request out and hands it to the run loop.
|
||||
fn host_call(caller: Caller<'_, Ctx>, ptr: i32, len: i32) -> std::result::Result<i32, wasmi::Error> {
|
||||
let mut caller = caller;
|
||||
let (p, l) = (ptr as u32 as usize, len as u32 as usize);
|
||||
if l > caller.data().max_request {
|
||||
return Err(wasmi::Error::new(format!("request of {l} bytes is over the {} byte limit", caller.data().max_request)));
|
||||
}
|
||||
let memory = caller_memory(&caller)?;
|
||||
let bytes = memory.data(&caller).get(p..p.saturating_add(l)).ok_or_else(|| wasmi::Error::new("anicraft.call: the request points outside memory"))?.to_vec();
|
||||
caller.data_mut().pending = Some(bytes);
|
||||
Err(wasmi::Error::host(HostCall))
|
||||
}
|
||||
|
||||
/// `anicraft.response(ptr, cap) -> i32`: copies up to `cap` bytes of the last response.
|
||||
fn host_response(caller: Caller<'_, Ctx>, ptr: i32, cap: i32) -> std::result::Result<i32, wasmi::Error> {
|
||||
let mut caller = caller;
|
||||
let memory = caller_memory(&caller)?;
|
||||
let (data, ctx) = memory.data_and_store_mut(&mut caller);
|
||||
let n = ctx.response.len().min(cap.max(0) as usize);
|
||||
let p = ptr as u32 as usize;
|
||||
let dst = data.get_mut(p..p.saturating_add(n)).ok_or_else(|| wasmi::Error::new("anicraft.response: the buffer points outside memory"))?;
|
||||
dst.copy_from_slice(ctx.response.get(..n).unwrap_or_default());
|
||||
Ok(n as i32)
|
||||
}
|
||||
|
||||
impl Plugin {
|
||||
/// Validates and loads a module: checks its imports and exports, the ABI version, and
|
||||
/// reads the manifest.
|
||||
pub fn load(bytes: &[u8], limits: Limits) -> Result<Plugin> {
|
||||
if bytes.len() > limits.max_module_bytes {
|
||||
return Err(Error::Module(format!("the module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes)));
|
||||
}
|
||||
if !bytes.starts_with(b"\0asm") {
|
||||
return Err(Error::Module("not a WebAssembly binary (it doesn't start with \\0asm)".into()));
|
||||
}
|
||||
let mut config = Config::default();
|
||||
config.consume_fuel(true).enforced_limits(EnforcedLimits::strict()).set_max_recursion_depth(limits.max_recursion_depth.max(16));
|
||||
let engine = Engine::new(&config);
|
||||
let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?;
|
||||
for imp in module.imports() {
|
||||
let known = IMPORTS.iter().find(|(n, _, _)| imp.module() == IMPORT_MODULE && imp.name() == *n);
|
||||
let Some((_, np, nr)) = known else {
|
||||
return Err(Error::Abi(format!(
|
||||
"the module imports `{}.{}`; plug-ins may import only anicraft.call and anicraft.response (no WASI, files, clock or network)",
|
||||
imp.module(),
|
||||
imp.name()
|
||||
)));
|
||||
};
|
||||
let ok = match imp.ty() {
|
||||
ExternType::Func(f) => f.params().len() == *np && f.results().len() == *nr && f.params().iter().chain(f.results()).all(|t| *t == wasmi::ValType::I32),
|
||||
_ => false,
|
||||
};
|
||||
if !ok {
|
||||
return Err(Error::Abi(format!("`{IMPORT_MODULE}.{}` must be a function ({}) -> i32", imp.name(), vec!["i32"; *np].join(", "))));
|
||||
}
|
||||
}
|
||||
let mut p = Plugin { manifest: placeholder_manifest(), engine, module, limits, size: bytes.len(), source: None };
|
||||
let deadline = Deadline::new(p.limits.wall_time_ms);
|
||||
let load_fuel = p.limits.fuel / 10;
|
||||
let mut live = p.instantiate(load_fuel)?;
|
||||
let version: TypedFunc<(), i32> = live.func("ac_abi_version")?;
|
||||
let v = p.call(&mut live, &version, (), load_fuel, &deadline, &mut None)?;
|
||||
if v != ABI_VERSION {
|
||||
return Err(Error::Abi(format!("ac_abi_version returned {v}; this AniCraft runs ABI version {ABI_VERSION}")));
|
||||
}
|
||||
let manifest: TypedFunc<(), i64> = live.func("ac_manifest")?;
|
||||
let packed = p.call(&mut live, &manifest, (), load_fuel, &deadline, &mut None)? as u64;
|
||||
let (ptr, len) = ((packed & 0xffff_ffff) as u32, (packed >> 32) as u32);
|
||||
if len as usize > MAX_MANIFEST_BYTES {
|
||||
return Err(Error::Manifest(format!("it is {len} bytes (limit {MAX_MANIFEST_BYTES})")));
|
||||
}
|
||||
p.manifest = Manifest::parse(live.bytes(ptr, len, "ac_manifest")?)?;
|
||||
// The other exports must exist with the right types.
|
||||
live.func::<i32, i32>("ac_alloc")?;
|
||||
live.func::<(i32, i32), i32>("ac_run")?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
pub fn manifest(&self) -> &Manifest {
|
||||
&self.manifest
|
||||
}
|
||||
pub fn id(&self) -> &str {
|
||||
&self.manifest.id
|
||||
}
|
||||
pub fn limits(&self) -> &Limits {
|
||||
&self.limits
|
||||
}
|
||||
/// Module size in bytes.
|
||||
pub fn size(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
/// The file the module was loaded from, if any.
|
||||
pub fn source(&self) -> Option<&std::path::Path> {
|
||||
self.source.as_deref()
|
||||
}
|
||||
pub fn with_source(mut self, source: impl Into<std::path::PathBuf>) -> Self {
|
||||
self.source = Some(source.into());
|
||||
self
|
||||
}
|
||||
|
||||
fn instantiate(&self, fuel: u64) -> Result<Live> {
|
||||
let limits = StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build();
|
||||
let ctx = Ctx { limits, max_request: self.limits.max_request_bytes, pending: None, response: Vec::new() };
|
||||
let mut store = Store::new(&self.engine, ctx);
|
||||
store.limiter(|c| &mut c.limits);
|
||||
// The start function (if any) runs on this fuel.
|
||||
store.set_fuel(fuel).map_err(wasm_err)?;
|
||||
let mut linker = Linker::<Ctx>::new(&self.engine);
|
||||
linker.func_wrap(IMPORT_MODULE, "call", host_call).map_err(|e| Error::Abi(e.to_string()))?;
|
||||
linker.func_wrap(IMPORT_MODULE, "response", host_response).map_err(|e| Error::Abi(e.to_string()))?;
|
||||
let instance = linker.instantiate_and_start(&mut store, &self.module).map_err(|e| match wasm_err(e) {
|
||||
Error::Trap(m) => Error::Module(format!("it can't start: {m}")),
|
||||
other => other,
|
||||
})?;
|
||||
let memory = instance.get_memory(&store, "memory").ok_or_else(|| Error::Abi("the module must export its memory as `memory`".into()))?;
|
||||
Ok(Live { store, instance, memory, used: 0 })
|
||||
}
|
||||
|
||||
/// Calls `f` with at most `fuel` instructions, in slices, checking the deadline between
|
||||
/// them and answering host calls through `host` (`None`: host calls are an error).
|
||||
fn call<P: WasmParams, R: WasmResults>(&self, live: &mut Live, f: &TypedFunc<P, R>, params: P, fuel: u64, deadline: &Deadline, host: &mut Option<(&mut dyn Host, &mut RunReport)>) -> Result<R> {
|
||||
let mut left = fuel;
|
||||
let give = left.min(FUEL_SLICE);
|
||||
left -= give;
|
||||
live.store.set_fuel(give).map_err(wasm_err)?;
|
||||
let mut call = f.call_resumable(&mut live.store, params).map_err(wasm_err)?;
|
||||
loop {
|
||||
match call {
|
||||
TypedResumableCall::Finished(r) => {
|
||||
live.used = live.used.saturating_add((fuel - left).saturating_sub(live.store.get_fuel().unwrap_or(0)));
|
||||
return Ok(r);
|
||||
}
|
||||
TypedResumableCall::HostTrap(inv) => {
|
||||
if inv.host_error().downcast_ref::<HostCall>().is_none() {
|
||||
return Err(Error::Trap(inv.host_error().to_string()));
|
||||
}
|
||||
deadline.check()?;
|
||||
let request = live.store.data_mut().pending.take().unwrap_or_default();
|
||||
let response = match host {
|
||||
Some((h, report)) => self.answer(&mut **h, report, &request)?,
|
||||
None => return Err(Error::Abi("host calls are allowed only while the plug-in runs (not while loading)".into())),
|
||||
};
|
||||
let n = response.len() as i32;
|
||||
live.store.data_mut().response = response;
|
||||
call = inv.resume(&mut live.store, &[Val::I32(n)]).map_err(wasm_err)?;
|
||||
}
|
||||
TypedResumableCall::OutOfFuel(inv) => {
|
||||
let need = inv.required_fuel();
|
||||
if left == 0 || need > left {
|
||||
return Err(Error::Limit("instruction budget".into()));
|
||||
}
|
||||
deadline.check()?;
|
||||
let give = left.min(FUEL_SLICE.max(need));
|
||||
left -= give;
|
||||
live.store.set_fuel(give).map_err(wasm_err)?;
|
||||
call = inv.resume(&mut live.store).map_err(wasm_err)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers one request: `log` here, everything else through the host. Always a JSON
|
||||
/// envelope; only a broken channel (too many calls) stops the run.
|
||||
fn answer(&self, host: &mut dyn Host, report: &mut RunReport, request: &[u8]) -> Result<Vec<u8>> {
|
||||
report.calls = report.calls.saturating_add(1);
|
||||
if report.calls > self.limits.max_calls {
|
||||
return Err(Error::Limit(format!("host-call budget ({} requests)", self.limits.max_calls)));
|
||||
}
|
||||
report.request_bytes = report.request_bytes.saturating_add(request.len() as u64);
|
||||
if report.request_bytes > self.limits.max_total_request_bytes as u64 {
|
||||
return Err(Error::Limit(format!("request budget ({} MiB per run)", self.limits.max_total_request_bytes >> 20)));
|
||||
}
|
||||
let result: std::result::Result<Value, String> = match serde_json::from_slice::<Value>(request) {
|
||||
Err(e) => Err(format!("the request is not JSON: {e}")),
|
||||
Ok(req) => match req.get("op").and_then(Value::as_str) {
|
||||
None => Err("the request needs an \"op\" (command, document, elements or log)".into()),
|
||||
Some("log") => {
|
||||
let msg = req.get("message").map(|m| m.as_str().map_or_else(|| m.to_string(), str::to_string)).unwrap_or_default();
|
||||
if report.log.len() < self.limits.max_log_lines {
|
||||
report.log.push(msg.chars().filter(|c| !c.is_control()).take(MAX_LOG_CHARS).collect());
|
||||
} else {
|
||||
report.log_dropped = report.log_dropped.saturating_add(1);
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
Some(op) => host.request(op, &req),
|
||||
},
|
||||
};
|
||||
// `ok` first, so a plug-in can tell success from the first bytes.
|
||||
let envelope = |ok: bool, v: &Value| {
|
||||
let body = serde_json::to_string(v).unwrap_or_else(|_| "null".into());
|
||||
if ok { format!("{{\"ok\":true,\"result\":{body}}}") } else { format!("{{\"ok\":false,\"error\":{body}}}") }.into_bytes()
|
||||
};
|
||||
let bytes = match &result {
|
||||
Ok(v) => envelope(true, v),
|
||||
Err(e) => envelope(false, &Value::String(e.clone())),
|
||||
};
|
||||
if bytes.len() > self.limits.max_response_bytes {
|
||||
let msg = format!("the response is {} bytes, over the {} byte limit; ask for less (e.g. without paths)", bytes.len(), self.limits.max_response_bytes);
|
||||
return Ok(envelope(false, &Value::String(msg)));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Runs the plug-in once in a fresh instance with validated `params` (see
|
||||
/// [`Manifest::resolve_params`]). The host answers its requests; any failure is an error
|
||||
/// and the caller should discard what the run changed.
|
||||
pub fn run(&self, host: &mut dyn Host, params: &Map<String, Value>) -> Result<RunReport> {
|
||||
let deadline = Deadline::new(self.limits.wall_time_ms);
|
||||
let text = serde_json::to_vec(params).map_err(|e| Error::Params(e.to_string()))?;
|
||||
if text.len() > self.limits.max_params_bytes {
|
||||
return Err(Error::Params(format!("{} bytes of parameters (limit {})", text.len(), self.limits.max_params_bytes)));
|
||||
}
|
||||
let mut live = self.instantiate(self.limits.fuel)?;
|
||||
let alloc: TypedFunc<i32, i32> = live.func("ac_alloc")?;
|
||||
let run: TypedFunc<(i32, i32), i32> = live.func("ac_run")?;
|
||||
let mut report = RunReport::default();
|
||||
let ptr = self.call(&mut live, &alloc, text.len().max(1) as i32, self.limits.fuel / 10, &deadline, &mut None)? as u32;
|
||||
if ptr == 0 {
|
||||
return Err(Error::Failed("ac_alloc returned 0 (out of memory)".into()));
|
||||
}
|
||||
let (p, l) = (ptr as usize, text.len());
|
||||
live.memory.data_mut(&mut live.store).get_mut(p..p.saturating_add(l)).ok_or_else(|| Error::Abi("ac_alloc returned a block outside memory".into()))?.copy_from_slice(&text);
|
||||
live.used = 0;
|
||||
let rc = {
|
||||
let mut h: Option<(&mut dyn Host, &mut RunReport)> = Some((host, &mut report));
|
||||
self.call(&mut live, &run, (ptr as i32, l as i32), self.limits.fuel, &deadline, &mut h)
|
||||
};
|
||||
report.fuel = live.used;
|
||||
let rc = rc?;
|
||||
if rc != 0 {
|
||||
let why = report.log.last().map_or_else(String::new, |m| format!(": {m}"));
|
||||
return Err(Error::Failed(format!("{} returned error code {rc}{why}", self.manifest.name)));
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholder_manifest() -> Manifest {
|
||||
Manifest {
|
||||
id: String::new(),
|
||||
name: String::new(),
|
||||
version: String::new(),
|
||||
kind: crate::Kind::Command,
|
||||
description: String::new(),
|
||||
author: String::new(),
|
||||
selection: crate::SelectionNeed::Optional,
|
||||
params: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! ABI v1 and sandbox tests, on modules written in WebAssembly text (compiled by `wat`), so no
|
||||
//! binary fixtures are committed. Hostile modules must end in an error, quickly, every time.
|
||||
|
||||
use anicraft_plugins::{Error, Host, Limits, Plugin, Registry};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const MANIFEST: &str = r#"{"id":"org.test.probe","name":"Probe","version":"1.0.0","kind":"command","author":"Tests","params":{"count":{"type":"int","min":1,"max":10,"default":2}}}"#;
|
||||
|
||||
/// WAT string literal contents for `s`.
|
||||
fn esc(s: &str) -> String {
|
||||
s.bytes().map(|b| if b == b'"' || b == b'\\' || !(0x20..0x7f).contains(&b) { format!("\\{b:02x}") } else { (b as char).to_string() }).collect()
|
||||
}
|
||||
|
||||
/// A plug-in module: the manifest at 1024, `data` strings at their offsets, `body` as
|
||||
/// `ac_run`'s code (params: $p $len; locals $n $m), `extra` module fields.
|
||||
fn module_with(manifest: &str, data: &[(u32, &str)], body: &str, extra: &str) -> Vec<u8> {
|
||||
let mut d = format!("(data (i32.const 1024) \"{}\")\n", esc(manifest));
|
||||
for (at, s) in data {
|
||||
d.push_str(&format!("(data (i32.const {at}) \"{}\")\n", esc(s)));
|
||||
}
|
||||
let text = format!(
|
||||
r#"(module
|
||||
(import "anicraft" "call" (func $call (param i32 i32) (result i32)))
|
||||
(import "anicraft" "response" (func $response (param i32 i32) (result i32)))
|
||||
(memory (export "memory") 2)
|
||||
(global $heap (mut i32) (i32.const 65536))
|
||||
{d}
|
||||
(func (export "ac_abi_version") (result i32) i32.const 1)
|
||||
(func (export "ac_manifest") (result i64)
|
||||
(i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 1024)))
|
||||
(func (export "ac_alloc") (param $size i32) (result i32) (local $p i32)
|
||||
global.get $heap local.set $p
|
||||
(global.set $heap (i32.add (global.get $heap) (local.get $size)))
|
||||
local.get $p)
|
||||
(func (export "ac_run") (param $p i32) (param $len i32) (result i32) (local $n i32) (local $m i32)
|
||||
{body})
|
||||
{extra})"#,
|
||||
len = manifest.len()
|
||||
);
|
||||
wat::parse_str(&text).unwrap_or_else(|e| panic!("bad test WAT: {e}\n{text}"))
|
||||
}
|
||||
|
||||
fn module(data: &[(u32, &str)], body: &str) -> Vec<u8> {
|
||||
module_with(MANIFEST, data, body, "")
|
||||
}
|
||||
|
||||
/// A host that records requests and answers `echo` with its request.
|
||||
#[derive(Default)]
|
||||
struct Rec {
|
||||
ops: Vec<String>,
|
||||
delay: Option<Duration>,
|
||||
}
|
||||
|
||||
impl Host for Rec {
|
||||
fn request(&mut self, op: &str, req: &Value) -> Result<Value, String> {
|
||||
self.ops.push(op.to_string());
|
||||
if let Some(d) = self.delay {
|
||||
std::thread::sleep(d);
|
||||
}
|
||||
match op {
|
||||
"echo" => Ok(req.clone()),
|
||||
_ => Err(format!("unknown op '{op}'")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run(bytes: &[u8], limits: Limits) -> (Result<anicraft_plugins::RunReport, Error>, Rec, Duration) {
|
||||
let p = Plugin::load(bytes, limits).expect("loads");
|
||||
let mut host = Rec::default();
|
||||
let t = Instant::now();
|
||||
let r = p.run(&mut host, &p.manifest().defaults());
|
||||
(r, host, t.elapsed())
|
||||
}
|
||||
|
||||
fn small() -> Limits {
|
||||
Limits { fuel: 20_000_000, wall_time_ms: 2_000, ..Limits::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_loads_reads_its_params_and_talks_to_the_host() {
|
||||
// Sends a log line and an echo request, reads the echo back and checks its envelope.
|
||||
let log = r#"{"op":"log","message":"hello"}"#;
|
||||
let echo = r#"{"op":"echo","x":1}"#;
|
||||
let body = format!(
|
||||
r#"
|
||||
(drop (call $call (i32.const 4096) (i32.const {})))
|
||||
(local.set $n (call $call (i32.const 8192) (i32.const {})))
|
||||
(local.set $m (call $response (i32.const 16384) (local.get $n)))
|
||||
(if (i32.ne (local.get $m) (local.get $n)) (then (return (i32.const 2))))
|
||||
;; {{"ok":true,...}}
|
||||
(if (i32.ne (i32.load8_u (i32.const 16390)) (i32.const 116)) (then (return (i32.const 3))))
|
||||
;; the params arrived as JSON: {{"count":2}}
|
||||
(if (i32.ne (i32.load8_u (local.get $p)) (i32.const 123)) (then (return (i32.const 4))))
|
||||
(if (i32.ne (local.get $len) (i32.const 11)) (then (return (i32.const 5))))
|
||||
i32.const 0"#,
|
||||
log.len(),
|
||||
echo.len()
|
||||
);
|
||||
let bytes = module(&[(4096, log), (8192, echo)], &body);
|
||||
let p = Plugin::load(&bytes, Limits::default()).unwrap();
|
||||
assert_eq!(p.manifest().name, "Probe");
|
||||
assert_eq!(p.manifest().params.len(), 1);
|
||||
let mut host = Rec::default();
|
||||
let report = p.run(&mut host, &p.manifest().defaults()).unwrap();
|
||||
assert_eq!(report.log, ["hello"]);
|
||||
assert_eq!(report.calls, 2);
|
||||
assert_eq!(host.ops, ["echo"]);
|
||||
assert!(report.fuel > 0 && report.fuel < 10_000, "fuel {}", report.fuel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_requests_get_an_error_answer_and_the_run_goes_on() {
|
||||
let body = r#"
|
||||
(local.set $n (call $call (i32.const 4096) (i32.const 3)))
|
||||
(drop (call $response (i32.const 16384) (local.get $n)))
|
||||
;; {"ok":false
|
||||
(if (i32.ne (i32.load8_u (i32.const 16390)) (i32.const 102)) (then (return (i32.const 9))))
|
||||
(drop (call $call (i32.const 5000) (i32.const 2)))
|
||||
(drop (call $call (i32.const 6000) (i32.const 13)))
|
||||
i32.const 0"#;
|
||||
let (r, host, _) = run(&module(&[(4096, "nop"), (5000, "{}"), (6000, r#"{"op":"what"}"#)], body), Limits::default());
|
||||
r.unwrap();
|
||||
assert_eq!(host.ops, ["what"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonzero_return_is_a_failure_with_the_last_log_line() {
|
||||
let msg = r#"{"op":"log","message":"select something first"}"#;
|
||||
let body = format!("(drop (call $call (i32.const 4096) (i32.const {}))) i32.const 7", msg.len());
|
||||
let (r, _, _) = run(&module(&[(4096, msg)], &body), Limits::default());
|
||||
let e = r.unwrap_err();
|
||||
assert!(matches!(&e, Error::Failed(m) if m.contains("code 7") && m.contains("select something first")), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_are_validated_at_load() {
|
||||
let ok = module(&[], "i32.const 0");
|
||||
Plugin::load(&ok, Limits::default()).unwrap();
|
||||
let wat = |t: &str| wat::parse_str(t).unwrap();
|
||||
let base_exports = format!(
|
||||
r#"(memory (export "memory") 1) (data (i32.const 1024) "{}")
|
||||
(func (export "ac_abi_version") (result i32) i32.const 1)
|
||||
(func (export "ac_manifest") (result i64) (i64.or (i64.shl (i64.const {}) (i64.const 32)) (i64.const 1024)))
|
||||
(func (export "ac_alloc") (param i32) (result i32) i32.const 4096)"#,
|
||||
esc(MANIFEST),
|
||||
MANIFEST.len()
|
||||
);
|
||||
let cases: Vec<(&str, Vec<u8>, &str)> = vec![
|
||||
("not wasm", b"MZ\x90\x00 definitely not wasm".to_vec(), "\\0asm"),
|
||||
("truncated", ok[..ok.len() / 2].to_vec(), "valid"),
|
||||
("wasi import", wat(&format!(r#"(module (import "wasi_snapshot_preview1" "fd_write" (func (param i32 i32 i32 i32) (result i32))) {base_exports} (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#)), "wasi_snapshot_preview1.fd_write"),
|
||||
("unknown anicraft import", wat(&format!(r#"(module (import "anicraft" "open_file" (func (param i32) (result i32))) {base_exports} (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#)), "anicraft.open_file"),
|
||||
("wrong import type", wat(&format!(r#"(module (import "anicraft" "call" (func (param i64) (result i32))) {base_exports} (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#)), "must be a function"),
|
||||
("imported memory", wat(r#"(module (import "anicraft" "memory" (memory 1)))"#), "anicraft.memory"),
|
||||
("missing ac_run", wat(&format!("(module {base_exports})")), "ac_run"),
|
||||
("wrong ac_run type", wat(&format!(r#"(module {base_exports} (func (export "ac_run") (result i32) i32.const 0))"#)), "ac_run"),
|
||||
("no memory export", wat(r#"(module (func (export "ac_abi_version") (result i32) i32.const 1))"#), "memory"),
|
||||
("abi 2", wat(&format!(r#"(module {} (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#, base_exports.replace("(result i32) i32.const 1)", "(result i32) i32.const 2)"))), "returned 2"),
|
||||
("manifest outside memory", wat(r#"(module (memory (export "memory") 1) (func (export "ac_abi_version") (result i32) i32.const 1) (func (export "ac_manifest") (result i64) (i64.or (i64.shl (i64.const 100) (i64.const 32)) (i64.const 65500))) (func (export "ac_alloc") (param i32) (result i32) i32.const 0) (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#), "outside"),
|
||||
("huge manifest", wat(r#"(module (memory (export "memory") 1) (func (export "ac_abi_version") (result i32) i32.const 1) (func (export "ac_manifest") (result i64) i64.const 0x7fffffff00000000) (func (export "ac_alloc") (param i32) (result i32) i32.const 0) (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#), "limit"),
|
||||
("bad manifest", module_with(r#"{"id":"bad id","name":"X","kind":"command"}"#, &[], "i32.const 0", ""), "invalid id"),
|
||||
("memory over the cap", wat(&format!(r#"(module {} (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#, base_exports.replace("(memory (export \"memory\") 1)", "(memory (export \"memory\") 5000)"))), "start"),
|
||||
("endless start function", wat(&format!(r#"(module {base_exports} (func $s (loop $l (br $l))) (start $s) (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#)), "instruction budget"),
|
||||
("host call while loading", wat(&format!(r#"(module (import "anicraft" "call" (func $c (param i32 i32) (result i32))) {} (func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#, base_exports.replace("(result i32) i32.const 1)", "(result i32) (drop (call $c (i32.const 0) (i32.const 0))) i32.const 1)"))), "only while"),
|
||||
];
|
||||
for (name, bytes, want) in cases {
|
||||
let t = Instant::now();
|
||||
let e = Plugin::load(&bytes, small()).expect_err(name);
|
||||
assert!(e.to_string().contains(want), "{name}: {e}");
|
||||
assert!(t.elapsed() < Duration::from_secs(5), "{name} took {:?}", t.elapsed());
|
||||
}
|
||||
let big = vec![0u8; 1 << 10];
|
||||
assert!(Plugin::load(&big, Limits { max_module_bytes: 100, ..Limits::default() }).is_err());
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn an_endless_loop_runs_out_of_fuel() {
|
||||
let (r, _, t) = run(&module(&[], "(loop $l (br $l)) i32.const 0"), small());
|
||||
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("instruction")), "{r:?}");
|
||||
println!("20 M instructions of a busy loop: {t:?}");
|
||||
assert!(t < Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_run_hits_the_time_budget() {
|
||||
let (r, _, t) = run(&module(&[], "(loop $l (br $l)) i32.const 0"), Limits { fuel: u64::MAX / 2, wall_time_ms: 200, ..Limits::default() });
|
||||
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("time")), "{r:?}");
|
||||
assert!(t < Duration::from_secs(2), "{t:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slow_host_calls_count_against_the_time_budget() {
|
||||
let log = r#"{"op":"echo"}"#;
|
||||
let body = format!("(loop $l (drop (call $call (i32.const 4096) (i32.const {}))) (br $l)) i32.const 0", log.len());
|
||||
let p = Plugin::load(&module(&[(4096, log)], &body), Limits { wall_time_ms: 150, ..Limits::default() }).unwrap();
|
||||
let mut host = Rec { delay: Some(Duration::from_millis(20)), ..Rec::default() };
|
||||
let t = Instant::now();
|
||||
let r = p.run(&mut host, &Map::new());
|
||||
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("time")), "{r:?}");
|
||||
assert!(t.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_growth_stops_at_the_cap() {
|
||||
// Grows until memory.grow fails, then reports how far it got as the error code.
|
||||
let body = "(block $done (loop $l (br_if $done (i32.eq (memory.grow (i32.const 16)) (i32.const -1))) (br $l))) memory.size";
|
||||
let (r, _, _) = run(&module(&[], body), Limits { max_memory_bytes: 8 << 20, ..small() });
|
||||
// 8 MiB is 128 pages: from 2 pages in steps of 16 it stops at 114 (130 would be over).
|
||||
assert!(matches!(r, Err(Error::Failed(ref m)) if m.contains("code 114")), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_recursion_traps() {
|
||||
let extra = r#"(func $down (param i32) (result i32) (call $down (i32.add (local.get 0) (i32.const 1))))"#;
|
||||
let (r, _, t) = run(&module_with(MANIFEST, &[], "(call $down (i32.const 0))", extra), small());
|
||||
assert!(matches!(r, Err(Error::Trap(_)) | Err(Error::Limit(_))), "{r:?}");
|
||||
assert!(t < Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traps_and_bad_pointers_end_the_run() {
|
||||
let cases = [
|
||||
("unreachable", "unreachable"),
|
||||
("divide by zero", "(i32.div_s (i32.const 1) (i32.const 0))"),
|
||||
("request outside memory", "(call $call (i32.const 131000) (i32.const 1000))"),
|
||||
("huge request", "(call $call (i32.const 0) (i32.const 0x7fffffff))"),
|
||||
("response outside memory", "(drop (call $call (i32.const 0) (i32.const 2))) (call $response (i32.const 131060) (i32.const 1000))"),
|
||||
("load outside memory", "(i32.load (i32.const 0x7ffffff0))"),
|
||||
];
|
||||
for (name, body) in cases {
|
||||
let (r, _, _) = run(&module(&[(0, "{}")], body), small());
|
||||
assert!(matches!(r, Err(Error::Trap(_)) | Err(Error::Abi(_))), "{name}: {r:?}");
|
||||
}
|
||||
// A negative capacity copies nothing.
|
||||
let (r, _, _) = run(&module(&[(0, "{}")], "(drop (call $call (i32.const 0) (i32.const 2))) (call $response (i32.const 0) (i32.const -5))"), small());
|
||||
r.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flood_of_host_calls_is_cut_off_and_the_log_stays_bounded() {
|
||||
let log = r#"{"op":"log","message":"spam spam spam"}"#;
|
||||
let body = format!("(loop $l (drop (call $call (i32.const 4096) (i32.const {}))) (br $l)) i32.const 0", log.len());
|
||||
let limits = Limits { max_calls: 5_000, max_log_lines: 50, ..small() };
|
||||
let p = Plugin::load(&module(&[(4096, log)], &body), limits).unwrap();
|
||||
let r = p.run(&mut Rec::default(), &Map::new());
|
||||
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("host-call")), "{r:?}");
|
||||
// A run within the call budget keeps at most 50 lines and counts the rest.
|
||||
let body = format!("(local.set $n (i32.const 0)) (loop $l (drop (call $call (i32.const 4096) (i32.const {}))) (local.set $n (i32.add (local.get $n) (i32.const 1))) (br_if $l (i32.lt_u (local.get $n) (i32.const 400)))) i32.const 0", log.len());
|
||||
let p = Plugin::load(&module(&[(4096, log)], &body), Limits { max_log_lines: 50, ..small() }).unwrap();
|
||||
let rep = p.run(&mut Rec::default(), &Map::new()).unwrap();
|
||||
assert_eq!((rep.log.len(), rep.log_dropped), (50, 350));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_total_size_of_requests_is_bounded() {
|
||||
// 1,000 requests of 64 KiB each: over a 16 MiB budget long before the call budget.
|
||||
let body = "(loop $l (drop (call $call (i32.const 0) (i32.const 65536))) (br $l)) i32.const 0";
|
||||
let limits = Limits { max_total_request_bytes: 16 << 20, ..small() };
|
||||
let p = Plugin::load(&module(&[(0, "{}")], body), limits).unwrap();
|
||||
let r = p.run(&mut Rec::default(), &Map::new());
|
||||
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("request budget")), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_responses_become_errors() {
|
||||
struct Big;
|
||||
impl Host for Big {
|
||||
fn request(&mut self, _: &str, _: &Value) -> Result<Value, String> {
|
||||
Ok(json!("x".repeat(100_000)))
|
||||
}
|
||||
}
|
||||
let req = r#"{"op":"big"}"#;
|
||||
let body = format!("(local.set $n (call $call (i32.const 4096) (i32.const {}))) (drop (call $response (i32.const 16384) (i32.const 64))) (if (i32.ne (i32.load8_u (i32.const 16390)) (i32.const 102)) (then (return (i32.const 1)))) (local.get $n) (i32.const 1000) i32.gt_u", req.len());
|
||||
let p = Plugin::load(&module(&[(4096, req)], &body), Limits { max_response_bytes: 10_000, ..Limits::default() }).unwrap();
|
||||
// Returns 0: the answer was a short error, not 100 kB.
|
||||
p.run(&mut Big, &Map::new()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_run_starts_from_a_fresh_instance() {
|
||||
// Counts runs in a global: always 1 in a fresh instance.
|
||||
let extra = "(global $runs (mut i32) (i32.const 0))";
|
||||
let body = "(global.set $runs (i32.add (global.get $runs) (i32.const 1))) (i32.ne (global.get $runs) (i32.const 1))";
|
||||
let p = Plugin::load(&module_with(MANIFEST, &[], body, extra), Limits::default()).unwrap();
|
||||
for _ in 0..3 {
|
||||
p.run(&mut Rec::default(), &Map::new()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("anicraft-plugins-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_registry_installs_into_its_folder_reloads_and_removes() {
|
||||
let root = temp_dir("registry");
|
||||
let folder = root.join("plugins");
|
||||
let src = root.join("downloaded-probe.wasm");
|
||||
std::fs::write(&src, module(&[], "i32.const 0")).unwrap();
|
||||
let mut reg = Registry::new(Some(folder.clone()));
|
||||
assert!(reg.install_overwrites(&src).is_none());
|
||||
let inst = reg.install_file(&src).unwrap();
|
||||
let dest = folder.join("org.test.probe.wasm");
|
||||
assert_eq!(inst.copied_to.as_deref(), Some(dest.as_path()));
|
||||
assert!(dest.exists() && inst.replaced.is_none());
|
||||
assert!(reg.owns_file(&inst.plugin));
|
||||
// Installing it again would replace the copy.
|
||||
assert!(reg.install_overwrites(&src).is_some());
|
||||
assert!(reg.would_replace(&src).is_some());
|
||||
// A broken file in the folder is reported, the good one still loads.
|
||||
std::fs::write(folder.join("broken.wasm"), b"\0asm\x01\0\0\0garbage").unwrap();
|
||||
std::fs::write(folder.join("notes.txt"), b"ignored").unwrap();
|
||||
let rev = reg.revision();
|
||||
let rep = reg.reload().unwrap();
|
||||
assert!(reg.revision() > rev);
|
||||
assert_eq!(rep.loaded, ["org.test.probe"]);
|
||||
assert_eq!(rep.failed.len(), 1);
|
||||
assert!(rep.failed[0].0.ends_with("broken.wasm"));
|
||||
// Removing deletes the copy, not the original.
|
||||
let rm = reg.remove("org.test.probe").unwrap();
|
||||
assert_eq!(rm.deleted.as_deref(), Some(dest.as_path()));
|
||||
assert!(!dest.exists() && src.exists());
|
||||
assert!(reg.is_empty());
|
||||
assert!(matches!(reg.remove("org.test.probe"), Err(Error::NotFound(_))));
|
||||
// Without a folder, installs stay in memory and removing deletes nothing.
|
||||
let mut mem = Registry::default();
|
||||
let inst = mem.install_file(&src).unwrap();
|
||||
assert!(inst.copied_to.is_none() && !mem.owns_file(&inst.plugin));
|
||||
assert!(mem.remove("org.test.probe").unwrap().deleted.is_none());
|
||||
assert!(src.exists());
|
||||
assert!(mem.reload().is_err());
|
||||
assert!(mem.install_file(&root).is_err());
|
||||
assert!(mem.install_file(&root.join("missing.wasm")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
@@ -13,6 +13,12 @@ use std::sync::{Arc, OnceLock};
|
||||
/// Families tried, in order, when none is asked for or the one asked for isn't installed.
|
||||
pub const DEFAULT_FAMILIES: &[&str] = &["Inter", "Arial", "Helvetica", "Helvetica Neue", "Segoe UI", "DejaVu Sans", "Liberation Sans", "Noto Sans", "Roboto", "Ubuntu"];
|
||||
|
||||
/// Installed families tried for the device font `_serif`, in order.
|
||||
const SERIF_FAMILIES: &[&str] = &["Times New Roman", "Times", "Georgia", "DejaVu Serif", "Liberation Serif", "Noto Serif"];
|
||||
|
||||
/// Installed families tried for the device font `_typewriter`, in order.
|
||||
const MONO_FAMILIES: &[&str] = &["Courier New", "Courier", "JetBrains Mono", "DejaVu Sans Mono", "Liberation Mono", "Noto Sans Mono", "Consolas", "Menlo"];
|
||||
|
||||
/// Largest text block laid out (characters).
|
||||
pub const MAX_CHARS: usize = 100_000;
|
||||
|
||||
@@ -60,6 +66,24 @@ pub struct Layout {
|
||||
pub family: String,
|
||||
/// Characters the font has no glyph for (drawn as its "notdef" box).
|
||||
pub missing: usize,
|
||||
/// Lines laid out (at least one), and the distance between their baselines (pixels): a
|
||||
/// line that continued the block would start `lines × line_height` below its top.
|
||||
pub lines: usize,
|
||||
pub line_height: f32,
|
||||
}
|
||||
|
||||
/// What a font name written by another program means on this computer: a PostScript name
|
||||
/// (`Arial-BoldMT`, as Animate documents store faces), a family name, or a device font
|
||||
/// (`_sans`, `_serif`, `_typewriter`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FaceMatch {
|
||||
/// The installed family, or `None` when it isn't installed (layout then falls back to the
|
||||
/// default family).
|
||||
pub family: Option<String>,
|
||||
/// The family the name stands for, installed or not ("Times New Roman"), for reports.
|
||||
pub wanted: String,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -134,6 +158,46 @@ impl Fonts {
|
||||
&self.families
|
||||
}
|
||||
|
||||
/// The installed family named `name`, ignoring case and spaces ("SegoeUI" finds "Segoe UI").
|
||||
fn installed(&self, name: &str) -> Option<String> {
|
||||
let key = |s: &str| s.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase).collect::<String>();
|
||||
let want = key(name);
|
||||
if want.is_empty() {
|
||||
return None;
|
||||
}
|
||||
self.families.iter().find(|f| key(f) == want).cloned()
|
||||
}
|
||||
|
||||
/// What `name` (a PostScript name, a family or a device font) is on this computer: the
|
||||
/// face with that PostScript name, else the family, else the family the name suggests
|
||||
/// ([`guess_family`]).
|
||||
pub fn find_face(&self, name: &str) -> FaceMatch {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return FaceMatch { family: None, wanted: String::new(), bold: false, italic: false };
|
||||
}
|
||||
if let Some(f) = self.db.faces().find(|f| f.post_script_name.eq_ignore_ascii_case(name))
|
||||
&& let Some((family, _)) = f.families.first()
|
||||
{
|
||||
return FaceMatch { family: Some(family.clone()), wanted: family.clone(), bold: f.weight.0 >= 600, italic: f.style != fontdb::Style::Normal };
|
||||
}
|
||||
let device: Option<&[&str]> = match name {
|
||||
"_sans" => Some(DEFAULT_FAMILIES),
|
||||
"_serif" => Some(SERIF_FAMILIES),
|
||||
"_typewriter" => Some(MONO_FAMILIES),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(list) = device {
|
||||
let family = list.iter().find_map(|f| self.installed(f));
|
||||
return FaceMatch { wanted: family.clone().unwrap_or_else(|| name.to_string()), family, bold: false, italic: false };
|
||||
}
|
||||
if let Some(family) = self.installed(name) {
|
||||
return FaceMatch { wanted: family.clone(), family: Some(family), bold: false, italic: false };
|
||||
}
|
||||
let (wanted, bold, italic) = guess_family(name);
|
||||
FaceMatch { family: self.installed(&wanted), wanted, bold, italic }
|
||||
}
|
||||
|
||||
/// The family used for `asked`: itself when installed (any case), else the default.
|
||||
pub fn resolve(&self, asked: &str) -> Option<String> {
|
||||
let find = |name: &str| self.families.iter().find(|f| f.eq_ignore_ascii_case(name)).cloned();
|
||||
@@ -163,6 +227,32 @@ impl Fonts {
|
||||
}
|
||||
}
|
||||
|
||||
/// The family, boldness and slant a PostScript name suggests, for fonts that aren't installed:
|
||||
/// `TimesNewRomanPS-BoldItalicMT` is Times New Roman, bold and italic.
|
||||
pub fn guess_family(postscript: &str) -> (String, bool, bool) {
|
||||
let name: String = postscript.trim().chars().take(256).collect();
|
||||
let (base, style) = name.split_once(['-', ',']).unwrap_or((&name, ""));
|
||||
let style = style.to_ascii_lowercase();
|
||||
let bold = ["bold", "black", "heavy"].iter().any(|w| style.contains(w));
|
||||
let italic = ["italic", "oblique"].iter().any(|w| style.contains(w));
|
||||
// The suffixes PostScript names give Monotype and PostScript versions of a face.
|
||||
let mut base = base;
|
||||
for suffix in ["MT", "PS"] {
|
||||
base = base.strip_suffix(suffix).filter(|b| !b.is_empty()).unwrap_or(base);
|
||||
}
|
||||
// CamelCase to words: "HelveticaNeue" → "Helvetica Neue"; capital runs stay ("ComicSansMS").
|
||||
let mut family = String::with_capacity(base.len() + 4);
|
||||
let mut prev: Option<char> = None;
|
||||
for c in base.chars() {
|
||||
if c.is_uppercase() && prev.is_some_and(|p| p.is_lowercase() || p.is_ascii_digit()) {
|
||||
family.push(' ');
|
||||
}
|
||||
family.push(c);
|
||||
prev = Some(c);
|
||||
}
|
||||
(family.trim().to_string(), bold, italic)
|
||||
}
|
||||
|
||||
/// Clamps a style to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px).
|
||||
pub fn sanitize(style: &Style) -> Style {
|
||||
let fin = |v: f32, d: f32| if v.is_finite() { v } else { d };
|
||||
@@ -257,7 +347,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option<Layout>
|
||||
}
|
||||
}
|
||||
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 })
|
||||
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 })
|
||||
}
|
||||
|
||||
/// Shapes `text` in one direction. Glyphs come back in visual order (left to right), clusters
|
||||
@@ -437,4 +527,50 @@ mod tests {
|
||||
assert_eq!(fonts.layout(&"x".repeat(MAX_CHARS + 1), &style(10.0)), Err(TextError::TooLong));
|
||||
assert_eq!(Fonts::from_faces(Vec::new()).layout("x", &style(10.0)), Err(TextError::NoFonts));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_names_suggest_families() {
|
||||
let g = |n: &str| guess_family(n);
|
||||
assert_eq!(g("ArialMT"), ("Arial".into(), false, false));
|
||||
assert_eq!(g("Arial-BoldMT"), ("Arial".into(), true, false));
|
||||
assert_eq!(g("TimesNewRomanPS-BoldItalicMT"), ("Times New Roman".into(), true, true));
|
||||
assert_eq!(g("TimesNewRomanPSMT"), ("Times New Roman".into(), false, false));
|
||||
assert_eq!(g("HelveticaNeue-LightOblique"), ("Helvetica Neue".into(), false, true));
|
||||
assert_eq!(g("ComicSansMS"), ("Comic Sans MS".into(), false, false));
|
||||
assert_eq!(g("Myriad Pro"), ("Myriad Pro".into(), false, false));
|
||||
assert_eq!(g("Gotham-Black"), ("Gotham".into(), true, false));
|
||||
assert_eq!(g(""), (String::new(), false, false));
|
||||
assert_eq!(g("MT"), ("MT".into(), false, false), "a suffix alone is the name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faces_are_found_by_postscript_name_family_or_device_font() {
|
||||
let none = Fonts::from_faces(Vec::new());
|
||||
let m = none.find_face("Futura-Bold");
|
||||
assert_eq!((m.family, m.wanted.as_str(), m.bold, m.italic), (None, "Futura", true, false));
|
||||
assert_eq!(none.find_face(" ").wanted, "");
|
||||
let Some(fonts) = fonts() else { return };
|
||||
let face = fonts.db.faces().find(|f| !f.post_script_name.is_empty() && f.families.first().is_some_and(|(n, _)| !n.starts_with('.')));
|
||||
if let Some(face) = face {
|
||||
let m = fonts.find_face(&face.post_script_name);
|
||||
assert!(m.family.is_some(), "{}", face.post_script_name);
|
||||
}
|
||||
let first = fonts.families()[0].clone();
|
||||
assert_eq!(fonts.find_face(&first.to_uppercase()).family, Some(first.clone()));
|
||||
assert_eq!(fonts.find_face(&first.replace(' ', "")).family, Some(first), "spaces don't matter");
|
||||
assert!(fonts.find_face("_sans").family.is_some(), "the default families include an installed one");
|
||||
let missing = fonts.find_face("NoSuchFamily-Italic");
|
||||
assert_eq!((missing.family, missing.wanted.as_str(), missing.italic), (None, "No Such Family", true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layouts_report_their_lines() {
|
||||
let Some(fonts) = fonts() else { return };
|
||||
let one = fonts.layout("one", &style(20.0)).unwrap();
|
||||
let three = fonts.layout("one\ntwo\nthree", &style(20.0)).unwrap();
|
||||
assert_eq!((one.lines, three.lines), (1, 3));
|
||||
assert!((one.line_height - three.line_height).abs() < 1e-3 && one.line_height >= 10.0);
|
||||
assert!((three.height - one.height - 2.0 * one.line_height).abs() < 0.01);
|
||||
assert_eq!(fonts.layout("", &style(20.0)).unwrap().lines, 1);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ repository.workspace = true
|
||||
anicraft-geom.workspace = true
|
||||
anicraft-doc.workspace = true
|
||||
anicraft-xml.workspace = true
|
||||
# Lays imported text out with the fonts on this computer (ADR 0012, ADR 0014).
|
||||
anicraft-text.workspace = true
|
||||
# Inflate for .fla (zip) archives; already in the tree through png (MIT OR Zlib OR Apache-2.0).
|
||||
miniz_oxide = "0.8"
|
||||
thiserror.workspace = true
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
//! primitives; symbol instances with their matrix, alpha and tint, 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. Everything else (text, sound, motion tweens with property curves,
|
||||
//! filters, bitmaps kept only in Animate's own storage) is counted in the report instead of
|
||||
//! guessed at.
|
||||
//! JPEG in the package; text fields, laid out with this computer's fonts (`text`, ADR 0014).
|
||||
//! Everything else (sound, motion tweens with property curves, bevel and gradient filters,
|
||||
//! bitmaps kept only in Animate's own storage) is counted in the report instead of guessed at.
|
||||
|
||||
use crate::edges::{self, Edge};
|
||||
use crate::xml::{self, Element as X};
|
||||
@@ -18,7 +18,8 @@ use anicraft_doc::{
|
||||
Scene, SymbolKind, Timeline, Tween, TweenKind,
|
||||
};
|
||||
use anicraft_geom::{Affine, FillRule, Path, Vec2};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use anicraft_text::{FaceMatch, Fonts};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -33,25 +34,40 @@ pub enum XflError {
|
||||
NotXfl(String),
|
||||
}
|
||||
|
||||
/// What the import couldn't bring across, by kind ("3 bitmaps").
|
||||
/// What the import couldn't bring across, by kind ("3 bitmaps"), and the fonts it couldn't
|
||||
/// find.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Report {
|
||||
pub skipped: BTreeMap<String, usize>,
|
||||
pub notes: Vec<String>,
|
||||
/// Font families the document's text asks for that aren't on this computer.
|
||||
pub missing_fonts: BTreeSet<String>,
|
||||
/// The family that text was laid out in instead.
|
||||
pub fallback_font: Option<String>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
fn skip(&mut self, what: &str) {
|
||||
pub(crate) fn skip(&mut self, what: &str) {
|
||||
*self.skipped.entry(what.to_string()).or_default() += 1;
|
||||
}
|
||||
/// One line for a status bar: "Imported. Not yet supported: 2 bitmaps, 1 text field."
|
||||
/// One line for a status bar: "Imported. Not yet supported: 2 sounds. Fonts not on this
|
||||
/// computer, drawn in Inter: Futura, Gotham."
|
||||
pub fn summary(&self) -> String {
|
||||
if self.skipped.is_empty() && self.notes.is_empty() {
|
||||
if self.skipped.is_empty() && self.notes.is_empty() && self.missing_fonts.is_empty() {
|
||||
return "Imported everything in the file.".into();
|
||||
}
|
||||
let mut out = String::from("Imported.");
|
||||
let mut parts: Vec<String> = self.skipped.iter().map(|(k, n)| format!("{n} {k}")).collect();
|
||||
parts.extend(self.notes.iter().cloned());
|
||||
format!("Imported. Not yet supported: {}.", parts.join(", "))
|
||||
if !parts.is_empty() {
|
||||
out.push_str(&format!(" Not yet supported: {}.", parts.join(", ")));
|
||||
}
|
||||
if !self.missing_fonts.is_empty() {
|
||||
let names: Vec<&str> = self.missing_fonts.iter().map(String::as_str).collect();
|
||||
let instead = self.fallback_font.as_deref().map(|f| format!(", drawn in {f}")).unwrap_or_default();
|
||||
out.push_str(&format!(" Fonts not on this computer{instead}: {}.", names.join(", ")));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,9 +93,13 @@ struct Builder<'a> {
|
||||
/// Library item name → bitmap id, for the bitmaps that could be read.
|
||||
bitmaps: HashMap<String, BitmapId>,
|
||||
report: Report,
|
||||
/// The fonts text is laid out with; the computer's, found on the first text field.
|
||||
fonts: Option<&'a Fonts>,
|
||||
/// Face name → what it is on this computer, looked up once per name.
|
||||
faces: HashMap<String, FaceMatch>,
|
||||
}
|
||||
|
||||
fn color(el: &X, key: &str, alpha_key: &str) -> Rgba {
|
||||
pub(crate) fn color(el: &X, key: &str, alpha_key: &str) -> Rgba {
|
||||
let rgb = el.attr(key).and_then(|c| u32::from_str_radix(c.trim().trim_start_matches('#'), 16).ok()).unwrap_or(0);
|
||||
Rgba::hex(rgb).with_alpha(el.f32(alpha_key).unwrap_or(1.0).clamp(0.0, 1.0))
|
||||
}
|
||||
@@ -238,6 +258,25 @@ impl<'a> Builder<'a> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A text field: one text element per block (`text::field`), placed by the field's matrix.
|
||||
fn text_field(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
|
||||
let fonts: &'a Fonts = match self.fonts {
|
||||
Some(f) => f,
|
||||
None => Fonts::get(),
|
||||
};
|
||||
self.fonts = Some(fonts);
|
||||
let m = parent.mul(&matrix(el));
|
||||
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.
|
||||
if i == 0 {
|
||||
e.name.clone_from(&name);
|
||||
}
|
||||
out.push(Arc::new(e));
|
||||
}
|
||||
}
|
||||
|
||||
fn instance(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
|
||||
let Some(&symbol) = el.attr("libraryItemName").and_then(|n| self.ids.get(n)) else {
|
||||
self.report.skip("instances of missing symbols");
|
||||
@@ -278,7 +317,7 @@ impl<'a> Builder<'a> {
|
||||
"DOMSymbolInstance" => self.instance(el, parent, out),
|
||||
"DOMRectangleObject" | "DOMOvalObject" => self.primitive(el, parent, out),
|
||||
"DOMBitmapInstance" => self.bitmap_instance(el, parent, out),
|
||||
"DOMStaticText" | "DOMDynamicText" | "DOMInputText" => self.report.skip("text fields"),
|
||||
"DOMStaticText" | "DOMDynamicText" | "DOMInputText" => self.text_field(el, parent, out),
|
||||
"DOMVideoInstance" => self.report.skip("videos"),
|
||||
_ => self.report.skip("other elements"),
|
||||
}
|
||||
@@ -438,14 +477,25 @@ impl<'a> Builder<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports an XFL package through `read` (paths inside the package).
|
||||
/// Imports an XFL package through `read` (paths inside the package). Text is laid out with
|
||||
/// the fonts on this computer.
|
||||
pub fn import_with(read: &Reader<'_>) -> Result<(Document, Report), XflError> {
|
||||
import_from(read, None)
|
||||
}
|
||||
|
||||
/// Imports an XFL package, laying text out with `fonts` (tests, and hosts with their own font
|
||||
/// library).
|
||||
pub fn import_with_fonts(read: &Reader<'_>, fonts: &Fonts) -> Result<(Document, Report), XflError> {
|
||||
import_from(read, Some(fonts))
|
||||
}
|
||||
|
||||
fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Document, Report), XflError> {
|
||||
let bytes = read("DOMDocument.xml")?.ok_or_else(|| XflError::NotXfl("no DOMDocument.xml".into()))?;
|
||||
let root = xml::parse(&bytes)?;
|
||||
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(), bitmaps: HashMap::new(), report: Report::default() };
|
||||
let mut b = Builder { doc: Document::default(), read, ids: HashMap::new(), pending: Vec::new(), bitmaps: HashMap::new(), report: Report::default(), fonts, faces: HashMap::new() };
|
||||
b.doc.library.clear();
|
||||
b.doc.scenes.clear();
|
||||
b.doc.stage = Stage {
|
||||
|
||||
@@ -8,11 +8,14 @@
|
||||
|
||||
pub mod edges;
|
||||
pub mod import;
|
||||
pub mod text;
|
||||
/// The shared XML reader (`anicraft-xml`), under its old path.
|
||||
pub use anicraft_xml as xml;
|
||||
pub mod zip;
|
||||
|
||||
pub use import::{Report, XflError, import_path, import_with};
|
||||
pub use import::{Report, XflError, import_path, import_with, import_with_fonts};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod text_tests;
|
||||
@@ -90,7 +90,7 @@ fn stage_layers_frames_and_tweens() {
|
||||
assert_eq!(doc.timeline(0).frame_count(), 15);
|
||||
assert_eq!(doc.frame_count(), 16, "the movie: scene 1, then the one-frame scene 2");
|
||||
// What couldn't come across is reported, not guessed.
|
||||
assert_eq!(report.skipped.get("text fields"), Some(&1));
|
||||
assert!(report.skipped.keys().all(|k| !k.contains("text")), "an empty text field makes nothing and reports nothing");
|
||||
assert_eq!(report.skipped.get("instances of missing bitmaps"), Some(&1));
|
||||
assert_eq!(report.skipped.get("missing library files"), Some(&1));
|
||||
// Frame scripts, on the scene's frames and inside symbols, are counted (ADR 0013).
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
//! Text fields (`DOMStaticText`, `DOMDynamicText`, `DOMInputText`) → text blocks laid out by
|
||||
//! `anicraft-text` (ADR 0014).
|
||||
//!
|
||||
//! A field holds text runs (`<textRuns><DOMTextRun><characters>…</characters><textAttrs>
|
||||
//! <DOMTextAttrs face="Arial-BoldMT" size="24" fillColor="#FF0000" alignment="center"
|
||||
//! letterSpacing="1" lineSpacing="2"/>`). An AniCraft text block has one style, so a field
|
||||
//! 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.
|
||||
|
||||
use crate::import::{Report, color};
|
||||
use crate::xml::Element as X;
|
||||
use anicraft_doc::{Rgba, TextAlign, TextBlock};
|
||||
use anicraft_geom::Vec2;
|
||||
use anicraft_text::{Align, FaceMatch, Fonts, TextError};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The space between a text field's box and its text, on every side (pixels), as in Animate's
|
||||
/// text fields.
|
||||
pub const GUTTER: f32 = 2.0;
|
||||
|
||||
/// Most runs read from one field.
|
||||
const MAX_RUNS: usize = 10_000;
|
||||
|
||||
/// One run's style, as `DOMTextAttrs` gives it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct RunStyle {
|
||||
face: String,
|
||||
size: f32,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
color: Rgba,
|
||||
align: TextAlign,
|
||||
letter_spacing: f32,
|
||||
line_spacing: f32,
|
||||
left_margin: f32,
|
||||
right_margin: f32,
|
||||
}
|
||||
|
||||
/// A laid-out block and where its box's top-left goes, in the field's coordinates.
|
||||
pub struct Placed {
|
||||
pub block: TextBlock,
|
||||
pub offset: Vec2,
|
||||
}
|
||||
|
||||
fn run_style(attrs: Option<&X>, flags: &mut Flags) -> RunStyle {
|
||||
let Some(a) = attrs else {
|
||||
return RunStyle { face: String::new(), size: 12.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, left_margin: 0.0, right_margin: 0.0 };
|
||||
};
|
||||
let num = |k: &str, lo: f32, hi: f32| a.f32(k).unwrap_or(0.0).clamp(lo, hi);
|
||||
let align = match a.attr("alignment") {
|
||||
Some("center") => TextAlign::Center,
|
||||
Some("right") => TextAlign::Right,
|
||||
Some(j) if j.starts_with("justify") => {
|
||||
flags.justified = true;
|
||||
TextAlign::Left
|
||||
}
|
||||
_ => TextAlign::Left,
|
||||
};
|
||||
if a.f32("indent").is_some_and(|i| i != 0.0) {
|
||||
flags.indented = true;
|
||||
}
|
||||
if a.attr("characterPosition").is_some_and(|p| p != "normal") {
|
||||
flags.shifted = true;
|
||||
}
|
||||
RunStyle {
|
||||
face: a.attr("face").unwrap_or("").chars().take(256).collect(),
|
||||
size: a.f32("size").unwrap_or(12.0).clamp(1.0, 2000.0),
|
||||
bold: a.bool("bold").unwrap_or(false),
|
||||
italic: a.bool("italic").unwrap_or(false),
|
||||
color: if a.attr("fillColor").is_some() { color(a, "fillColor", "alpha") } else { Rgba::BLACK.with_alpha(a.f32("alpha").unwrap_or(1.0).clamp(0.0, 1.0)) },
|
||||
align,
|
||||
letter_spacing: num("letterSpacing", -1000.0, 1000.0),
|
||||
line_spacing: num("lineSpacing", -1000.0, 1000.0),
|
||||
left_margin: num("leftMargin", 0.0, 10_000.0),
|
||||
right_margin: num("rightMargin", 0.0, 10_000.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a field used that AniCraft draws differently, reported once per field.
|
||||
#[derive(Default)]
|
||||
struct Flags {
|
||||
justified: bool,
|
||||
indented: bool,
|
||||
shifted: bool,
|
||||
}
|
||||
|
||||
/// A line of the field: its pieces, each with the style of the run it came from.
|
||||
type Line = Vec<(String, usize)>;
|
||||
|
||||
/// The style a line is drawn in: that of the most visible characters (the first on a tie), or
|
||||
/// of its first piece when it is empty.
|
||||
fn main_style(line: &Line) -> (usize, bool) {
|
||||
// Visible characters per style, in the order the styles first appear.
|
||||
let mut totals: Vec<(usize, usize)> = Vec::new();
|
||||
for (t, s) in line {
|
||||
let n = t.chars().filter(|c| !c.is_whitespace()).count();
|
||||
match totals.iter_mut().find(|(x, _)| x == s) {
|
||||
Some(e) => e.1 += n,
|
||||
None => totals.push((*s, n)),
|
||||
}
|
||||
}
|
||||
let mut best: Option<(usize, usize)> = None;
|
||||
for &(s, n) in &totals {
|
||||
if best.is_none_or(|(_, b)| n > b) {
|
||||
best = Some((s, n));
|
||||
}
|
||||
}
|
||||
(best.map_or(0, |(s, _)| s), totals.iter().filter(|(_, n)| *n > 0).count() > 1)
|
||||
}
|
||||
|
||||
/// 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<String, FaceMatch>, report: &mut Report) -> Vec<Placed> {
|
||||
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)");
|
||||
}
|
||||
if !el.list("filters").is_empty() {
|
||||
report.skip("filters on text");
|
||||
}
|
||||
let mut flags = Flags::default();
|
||||
let mut styles: Vec<RunStyle> = Vec::new();
|
||||
let mut lines: Vec<Line> = vec![Vec::new()];
|
||||
let mut chars = 0usize;
|
||||
let runs = el.list("textRuns");
|
||||
let mut cut = runs.len() > MAX_RUNS;
|
||||
for run in runs.iter().filter(|r| r.name == "DOMTextRun").take(MAX_RUNS) {
|
||||
let style = run_style(run.child("textAttrs").and_then(|t| t.child("DOMTextAttrs")), &mut flags);
|
||||
let s = match styles.iter().position(|x| *x == style) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
styles.push(style);
|
||||
styles.len() - 1
|
||||
}
|
||||
};
|
||||
let text = run.child("characters").map_or("", |c| c.text.as_str());
|
||||
// Animate ends lines with a carriage return; any line break starts a new line here.
|
||||
let text = text.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n");
|
||||
for (i, piece) in text.split('\n').enumerate() {
|
||||
if i > 0 {
|
||||
lines.push(Vec::new());
|
||||
chars += 1;
|
||||
}
|
||||
let room = anicraft_text::MAX_CHARS.saturating_sub(chars);
|
||||
let n = piece.chars().count();
|
||||
if n > room {
|
||||
cut = true;
|
||||
}
|
||||
let piece: String = piece.chars().take(room).collect();
|
||||
chars += n.min(room);
|
||||
if let Some(l) = lines.last_mut() {
|
||||
l.push((piece, s));
|
||||
}
|
||||
}
|
||||
if chars >= anicraft_text::MAX_CHARS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if cut {
|
||||
report.skip("text cut to 100,000 characters per field");
|
||||
}
|
||||
// Trailing empty lines draw nothing.
|
||||
while lines.last().is_some_and(|l| l.iter().all(|(t, _)| t.trim().is_empty())) {
|
||||
lines.pop();
|
||||
}
|
||||
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)");
|
||||
}
|
||||
|
||||
// Consecutive lines in the same style make one block.
|
||||
let mut blocks: Vec<(usize, String)> = Vec::new();
|
||||
for line in &lines {
|
||||
let (s, mixed) = main_style(line);
|
||||
if mixed {
|
||||
report.skip("lines with mixed text styles (drawn in their main style)");
|
||||
}
|
||||
let text: String = line.iter().map(|(t, _)| t.as_str()).collect();
|
||||
match blocks.last_mut() {
|
||||
Some((ls, t)) if *ls == s => {
|
||||
t.push('\n');
|
||||
t.push_str(&text);
|
||||
}
|
||||
_ => blocks.push((s, text)),
|
||||
}
|
||||
}
|
||||
|
||||
let auto = el.bool("autoExpand").unwrap_or(false);
|
||||
let field_width = el.f32("width").filter(|w| *w > 0.0).map(|w| w.min(100_000.0));
|
||||
let origin = Vec2::new(el.f32("left").unwrap_or(0.0) + GUTTER, el.f32("top").unwrap_or(0.0) + GUTTER);
|
||||
let mut out: Vec<Placed> = Vec::new();
|
||||
let mut y = 0.0f32;
|
||||
for (s, text) in blocks {
|
||||
let Some(st) = styles.get(s) else { continue };
|
||||
let face = faces.entry(st.face.clone()).or_insert_with(|| fonts.find_face(&st.face)).clone();
|
||||
// A fixed-width field wraps inside its margins; an auto-size one never wraps.
|
||||
let width = if auto { None } else { field_width.map(|w| (w - st.left_margin - st.right_margin).max(1.0)) };
|
||||
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,
|
||||
};
|
||||
let layout = match fonts.layout(&text, &style) {
|
||||
Ok(l) => l,
|
||||
Err(TextError::NoFonts) => {
|
||||
report.skip("text fields (no fonts on this computer)");
|
||||
return Vec::new();
|
||||
}
|
||||
Err(TextError::TooLong) => {
|
||||
report.skip("text cut to 100,000 characters per field");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// A family that isn't installed falls back to the default, as the text engine does
|
||||
// (ADR 0012), and the report names it.
|
||||
if face.family.is_none() && !face.wanted.is_empty() {
|
||||
report.missing_fonts.insert(face.wanted.clone());
|
||||
report.fallback_font.get_or_insert_with(|| layout.family.clone());
|
||||
}
|
||||
let block = TextBlock {
|
||||
text,
|
||||
font: layout.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,
|
||||
outline: Arc::new(layout.outline),
|
||||
box_width: layout.width,
|
||||
box_height: layout.height,
|
||||
};
|
||||
out.push(Placed { block, offset: Vec2::new(origin.x + st.left_margin, origin.y + y) });
|
||||
y += layout.lines as f32 * layout.line_height;
|
||||
}
|
||||
// Auto-size blocks align against the widest one, as lines of one field do.
|
||||
if auto {
|
||||
let widest = out.iter().map(|p| p.block.box_width).fold(0.0, f32::max);
|
||||
for p in &mut out {
|
||||
p.offset.x += match p.block.align {
|
||||
TextAlign::Left => 0.0,
|
||||
TextAlign::Center => (widest - p.block.box_width) * 0.5,
|
||||
TextAlign::Right => widest - p.block.box_width,
|
||||
};
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Text import tests on self-authored XFL snippets (ADR 0014).
|
||||
|
||||
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_text::Fonts;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The computer's fonts and an installed family, or `None` (and the test passes) on a computer
|
||||
/// without fonts.
|
||||
fn fonts() -> Option<(&'static Fonts, String)> {
|
||||
let f = Fonts::get();
|
||||
let family = f.resolve("")?;
|
||||
Some((f, family))
|
||||
}
|
||||
|
||||
/// A document with these elements on its one frame.
|
||||
fn doc_with(elements: &str) -> String {
|
||||
format!(r#"<DOMDocument width="550" height="400"><timelines><DOMTimeline name="Scene 1"><layers><DOMLayer name="Text"><frames><DOMFrame index="0"><elements>{elements}</elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>"#)
|
||||
}
|
||||
|
||||
fn import_doc(xml: &str, fonts: &Fonts) -> (Document, Report) {
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> { Ok((p == "DOMDocument.xml").then(|| xml.as_bytes().to_vec())) };
|
||||
import_with_fonts(&read, fonts).unwrap()
|
||||
}
|
||||
|
||||
fn texts(doc: &Document) -> Vec<(Arc<Element>, Arc<TextBlock>)> {
|
||||
doc.timeline(0).layers[0].keyframes[0].elements.iter().filter_map(|e| if let ElementKind::Text(t) = &e.kind { Some((e.clone(), t.clone())) } else { None }).collect()
|
||||
}
|
||||
|
||||
fn run(chars: &str, attrs: &str) -> String {
|
||||
format!("<DOMTextRun><characters>{chars}</characters><textAttrs><DOMTextAttrs {attrs}/></textAttrs></DOMTextRun>")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_text_keeps_its_style_matrix_and_lines() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let field = format!(
|
||||
r##"<DOMStaticText autoExpand="true" width="200" height="60"><matrix><Matrix a="2" d="2" tx="100" ty="50"/></matrix><textRuns>{}</textRuns></DOMStaticText>"##,
|
||||
run("Hello
World", &format!(r##"face="{family}" size="24" fillColor="#FF0000" alignment="center" letterSpacing="1.5" lineSpacing="4""##))
|
||||
);
|
||||
let (doc, report) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
assert_eq!(t.len(), 1);
|
||||
let (el, b) = &t[0];
|
||||
assert_eq!(b.text, "Hello\nWorld", "Animate's carriage returns are line breaks");
|
||||
assert_eq!((b.font.as_str(), b.size, b.color, b.align), (family.as_str(), 24.0, Rgba::hex(0xff0000), TextAlign::Center));
|
||||
assert_eq!((b.letter_spacing, b.line_spacing, b.width, b.bold, b.italic), (1.5, 4.0, None, false, false));
|
||||
// The matrix places the field; its text sits inside the gutter.
|
||||
assert_eq!(el.transform.m, [2.0, 0.0, 0.0, 2.0, 100.0 + 2.0 * GUTTER, 50.0 + 2.0 * GUTTER]);
|
||||
// Two lines, laid out by the text engine and stored as outlines.
|
||||
let one = fonts.layout("Hello", &anicraft_text::Style { family: family.clone(), size: 24.0, line_spacing: 4.0, ..Default::default() }).unwrap();
|
||||
assert!(b.box_height > one.height + one.line_height - 0.5, "{} vs {}", b.box_height, one.height);
|
||||
assert!(!b.outline.cmds.is_empty());
|
||||
assert!(report.skipped.is_empty() && report.missing_fonts.is_empty(), "{report:?}");
|
||||
assert_eq!(report.summary(), "Imported everything in the file.");
|
||||
// It renders, red, where the matrix puts it.
|
||||
let list = evaluate(&doc, 0);
|
||||
let item = list.items.iter().find(|i| i.fill == Some(Paint::Solid(Rgba::hex(0xff0000)))).expect("the text renders");
|
||||
assert!(item.transform.translation().x > 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_width_fields_wrap_and_auto_size_ones_do_not() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let words = "one two three four five six seven eight nine ten";
|
||||
let field = |extra: &str| format!(r#"<DOMStaticText {extra} width="90"><textRuns>{}</textRuns></DOMStaticText>"#, run(words, &format!(r#"face="{family}" size="14""#)));
|
||||
let (doc, _) = import_doc(&doc_with(&(field("") + &field(r#"autoExpand="true""#))), fonts);
|
||||
let t = texts(&doc);
|
||||
assert_eq!(t[0].1.width, Some(90.0), "fixed width");
|
||||
assert!(t[0].1.box_height > 3.0 * 14.0, "wrapped onto several lines: {}", t[0].1.box_height);
|
||||
assert!(t[0].1.outline.bounds().max.x <= 92.0);
|
||||
assert_eq!(t[1].1.width, None, "auto-size");
|
||||
assert!(t[1].1.box_width > 200.0 && t[1].1.box_height < 2.0 * 14.0 * 1.5, "one line: {} × {}", t[1].1.box_width, t[1].1.box_height);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_in_different_styles_become_blocks_stacked_line_by_line() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let title = format!(r##"face="{family}" size="30" bold="true" fillColor="#112233""##);
|
||||
let body = format!(r##"face="{family}" size="12" fillColor="#445566""##);
|
||||
// A title line, two body lines (the second continues in a separate run of the same style),
|
||||
// then a line that mixes both styles: most of its characters are body text.
|
||||
let runs = [run("Title
", &title), run("line one
line ", &body), run("two
", &body), run("Big", &title), run(" and mostly small", &body), run("

", &body)].concat();
|
||||
let field = format!(r#"<DOMStaticText autoExpand="true"><matrix><Matrix tx="10" ty="20"/></matrix><textRuns>{runs}</textRuns></DOMStaticText>"#);
|
||||
let (doc, report) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
let blocks: Vec<(&str, f32, bool)> = t.iter().map(|(_, b)| (b.text.as_str(), b.size, b.bold)).collect();
|
||||
assert_eq!(blocks, [("Title", 30.0, true), ("line one\nline two\nBig and mostly small", 12.0, false)], "trailing empty lines are dropped");
|
||||
assert_eq!(t[1].1.color, Rgba::hex(0x445566));
|
||||
// The body starts where the title's next line would.
|
||||
let title_layout = fonts.layout("Title", &anicraft_text::Style { family: family.clone(), size: 30.0, bold: true, ..Default::default() }).unwrap();
|
||||
let (y0, y1) = (t[0].0.transform.translation().y, t[1].0.transform.translation().y);
|
||||
assert!((y0 - (20.0 + GUTTER)).abs() < 1e-4);
|
||||
assert!((y1 - y0 - title_layout.line_height).abs() < 1e-3, "{y0} → {y1}, line height {}", title_layout.line_height);
|
||||
assert_eq!(t[0].0.transform.translation().x, t[1].0.transform.translation().x, "left-aligned blocks share the left edge");
|
||||
assert_eq!(report.skipped.get("lines with mixed text styles (drawn in their main style)"), Some(&1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn centred_auto_size_blocks_centre_on_each_other() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let a = format!(r#"face="{family}" size="40" alignment="center""#);
|
||||
let b = format!(r#"face="{family}" size="12" alignment="center""#);
|
||||
let field = format!(r#"<DOMStaticText autoExpand="true"><textRuns>{}{}</textRuns></DOMStaticText>"#, run("WIDE HEADLINE
", &a), run("small", &b));
|
||||
let (doc, _) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
let centre = |i: usize| t[i].0.transform.translation().x + t[i].1.box_width * 0.5;
|
||||
assert!((centre(0) - centre(1)).abs() < 0.01, "{} vs {}", centre(0), centre(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_fonts_fall_back_and_are_reported() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let field = format!(
|
||||
r#"<DOMStaticText><textRuns>{}</textRuns></DOMStaticText><DOMStaticText><textRuns>{}{}</textRuns></DOMStaticText>"#,
|
||||
run("Hi", r#"face="NoSuchFace-BoldItalic" size="20""#),
|
||||
run("again", r#"face="NoSuchFace-BoldItalic" size="20""#),
|
||||
run("
mono", r#"face="ZzMissingMonoPSMT" size="20""#)
|
||||
);
|
||||
let (doc, report) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
assert_eq!(t.len(), 3);
|
||||
assert_eq!((t[0].1.bold, t[0].1.italic), (true, true), "the face name says bold italic");
|
||||
assert!(fonts.families().contains(&t[0].1.font), "laid out in an installed family: {}", t[0].1.font);
|
||||
assert_eq!(report.missing_fonts.iter().map(String::as_str).collect::<Vec<_>>(), ["No Such Face", "Zz Missing Mono"]);
|
||||
assert_eq!(report.fallback_font.as_deref(), Some(family.as_str()));
|
||||
assert_eq!(report.summary(), format!("Imported. Fonts not on this computer, drawn in {family}: No Such Face, Zz Missing Mono."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_and_input_text_come_across_as_static_text_and_are_reported() {
|
||||
let Some((fonts, _)) = fonts() else { return };
|
||||
let field = format!(
|
||||
r#"<DOMDynamicText name="score" width="100"><textRuns>{}</textRuns></DOMDynamicText><DOMInputText name="answer"><textRuns>{}</textRuns></DOMInputText><DOMStaticText orientation="vertical left to right"><textRuns>{}</textRuns></DOMStaticText>"#,
|
||||
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::<Vec<_>>(), ["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!(report.skipped.get(what), Some(&n), "{what}: {report:?}");
|
||||
}
|
||||
assert!(report.missing_fonts.is_empty(), "no face asks for the default family");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_fonts_text_is_reported_not_guessed() {
|
||||
let none = Fonts::from_faces(Vec::new());
|
||||
let field = format!(r#"<DOMStaticText><textRuns>{}</textRuns></DOMStaticText>"#, run("Hello", r#"face="ArialMT" size="20""#));
|
||||
let (doc, report) = import_doc(&doc_with(&field), &none);
|
||||
assert!(texts(&doc).is_empty());
|
||||
assert_eq!(report.skipped.get("text fields (no fonts on this computer)"), Some(&1));
|
||||
// Empty fields and fields without runs make nothing and report nothing.
|
||||
let (doc, report) = import_doc(&doc_with(r#"<DOMStaticText/><DOMStaticText><textRuns>
|
||||
<DOMTextRun><characters> </characters></DOMTextRun></textRuns></DOMStaticText>"#), &none);
|
||||
assert!(texts(&doc).is_empty() && report.skipped.is_empty(), "{report:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_text_fields_import_without_panicking() {
|
||||
let Some((fonts, _)) = fonts() else { return };
|
||||
let many: String = (0..12_000).map(|i| run("x", &format!(r#"size="{}""#, i % 7 + 1))).collect();
|
||||
let long = "y ".repeat(60_000);
|
||||
let field = format!(
|
||||
r#"<DOMStaticText width="nan" left="1e30"><textRuns>{many}</textRuns></DOMStaticText>
|
||||
<DOMStaticText width="-5"><textRuns>{}{}</textRuns></DOMStaticText>
|
||||
<DOMStaticText><textRuns><DOMTextRun><characters>z</characters><textAttrs><DOMTextAttrs size="nan" letterSpacing="1e20" lineSpacing="-1e20" fillColor="nonsense" leftMargin="-4"/></textAttrs></DOMTextRun></textRuns></DOMStaticText>"#,
|
||||
run(&long, ""),
|
||||
run(&long, "")
|
||||
);
|
||||
let start = std::time::Instant::now();
|
||||
let (doc, report) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
assert!(!t.is_empty());
|
||||
assert!(t.iter().all(|(_, b)| b.text.chars().count() <= anicraft_text::MAX_CHARS && b.size.is_finite()));
|
||||
assert!(t.iter().any(|(_, b)| b.text.chars().count() > 99_000 && !b.outline.cmds.is_empty()), "the long field is laid out, cut to the limit");
|
||||
assert!(report.skipped.contains_key("text cut to 100,000 characters per field"), "{report:?}");
|
||||
assert!(start.elapsed().as_secs() < 30, "bounded work: {:?}", start.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_with_uses_this_computers_fonts() {
|
||||
if fonts().is_none() {
|
||||
return;
|
||||
}
|
||||
let xml = doc_with(&format!(r#"<DOMStaticText><textRuns>{}</textRuns></DOMStaticText>"#, run("Hi", r#"size="20""#)));
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> { Ok((p == "DOMDocument.xml").then(|| xml.as_bytes().to_vec())) };
|
||||
let (doc, _) = import_with(&read).unwrap();
|
||||
assert_eq!(texts(&doc).len(), 1);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
//! AniCraft XML (layer L0): a small, strict-enough XML element reader shared by the importers.
|
||||
//!
|
||||
//! XFL and SVG keep everything that matters in elements and attributes (XFL even stores shape
|
||||
//! geometry as an attribute), so the reader builds a tree of elements with attributes and
|
||||
//! ignores text. It handles the prolog, comments, CDATA, doctype, processing instructions, the
|
||||
//! five standard entities and numeric character references. Limits on input size, depth and
|
||||
//! geometry as an attribute), so the reader builds a tree of elements with attributes. An
|
||||
//! element's own character data (text and CDATA, such as XFL's `<characters>`) is kept in
|
||||
//! [`Element::text`], except whitespace-only text between child elements (indentation). It
|
||||
//! handles the prolog, comments, CDATA, doctype, processing instructions, the five standard
|
||||
//! entities and numeric character references. Limits on input size, depth and
|
||||
//! element count keep a hostile file from exhausting memory or the stack. Never panics.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -19,6 +21,9 @@ pub struct Element {
|
||||
pub name: String,
|
||||
pub attrs: HashMap<String, String>,
|
||||
pub children: Vec<Element>,
|
||||
/// The element's character data, entities resolved (XFL's `<characters>`). Whitespace
|
||||
/// between child elements is dropped.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Element {
|
||||
@@ -98,16 +103,32 @@ impl P<'_> {
|
||||
}
|
||||
Ok(String::from_utf8_lossy(self.s.get(start..self.i).unwrap_or_default()).into_owned())
|
||||
}
|
||||
/// Skips text, comments and other non-element content up to the next tag.
|
||||
fn skip_misc(&mut self) -> Result<(), XmlError> {
|
||||
/// Skips text, comments and other non-element content up to the next tag, adding text and
|
||||
/// CDATA to `text` when there is one.
|
||||
fn skip_misc(&mut self, mut text: Option<&mut String>) -> Result<(), XmlError> {
|
||||
loop {
|
||||
let start = self.i;
|
||||
while self.peek().is_some_and(|c| c != b'<') {
|
||||
self.i += 1;
|
||||
}
|
||||
if let Some(t) = text.as_deref_mut()
|
||||
&& self.i > start
|
||||
{
|
||||
let raw = String::from_utf8_lossy(self.s.get(start..self.i).unwrap_or_default());
|
||||
if raw.contains('&') {
|
||||
t.push_str(&unescape(&raw));
|
||||
} else {
|
||||
t.push_str(&raw);
|
||||
}
|
||||
}
|
||||
if self.starts(b"<!--") {
|
||||
self.skip_until(b"-->")?;
|
||||
} else if self.starts(b"<![CDATA[") {
|
||||
let from = self.i + 9;
|
||||
self.skip_until(b"]]>")?;
|
||||
if let Some(t) = text.as_deref_mut() {
|
||||
t.push_str(&String::from_utf8_lossy(self.s.get(from..self.i.saturating_sub(3)).unwrap_or_default()));
|
||||
}
|
||||
} else if self.starts(b"<?") {
|
||||
self.skip_until(b"?>")?;
|
||||
} else if self.starts(b"<!") {
|
||||
@@ -174,7 +195,7 @@ impl P<'_> {
|
||||
}
|
||||
// Content: children until the matching end tag.
|
||||
loop {
|
||||
self.skip_misc()?;
|
||||
self.skip_misc(Some(&mut el.text))?;
|
||||
if self.peek().is_none() {
|
||||
return self.err("missing end tag");
|
||||
}
|
||||
@@ -186,6 +207,9 @@ impl P<'_> {
|
||||
return self.err("mismatched end tag");
|
||||
}
|
||||
self.i += 1;
|
||||
if !el.children.is_empty() && el.text.trim().is_empty() {
|
||||
el.text = String::new();
|
||||
}
|
||||
return Ok(el);
|
||||
}
|
||||
el.children.push(self.element(depth + 1)?);
|
||||
@@ -244,7 +268,7 @@ pub fn parse(src: &[u8]) -> Result<Element, XmlError> {
|
||||
// A UTF-8 byte-order mark is allowed.
|
||||
let src = src.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(src);
|
||||
let mut p = P { s: src, i: 0, count: 0 };
|
||||
p.skip_misc()?;
|
||||
p.skip_misc(None)?;
|
||||
if p.peek().is_none() {
|
||||
return p.err("no root element");
|
||||
}
|
||||
@@ -271,7 +295,17 @@ mod tests {
|
||||
let tl = &root.list("timelines")[0];
|
||||
assert_eq!(tl.attr("name"), Some("Scene & \"1\" AB"));
|
||||
assert!(tl.list("layers").is_empty());
|
||||
assert_eq!(root.children.len(), 1, "CDATA and text are skipped");
|
||||
assert_eq!(root.children.len(), 1, "CDATA and text are not elements");
|
||||
assert!(root.text.contains(" <ignored/> ") && root.text.contains("text is ignored"), "{:?}", root.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_data_is_kept_and_indentation_dropped() {
|
||||
let x = b"<t>\n <characters>a <b>
line 2</characters>\n <characters> </characters><c><![CDATA[x<y]]>z</c>\n</t>";
|
||||
let root = parse(x).unwrap();
|
||||
assert_eq!(root.text, "", "whitespace between elements");
|
||||
let texts: Vec<&str> = root.children.iter().map(|c| c.text.as_str()).collect();
|
||||
assert_eq!(texts, ["a <b>\rline 2", " ", "x<yz"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -44,5 +44,7 @@ own timelines, nested to any depth.
|
||||
|
||||
* Imported documents render and animate in AniCraft immediately and can be edited with every
|
||||
tool, then saved as `.anicraft`.
|
||||
* Next slices: bitmaps (needs bitmap fills, M5), text (M5), masks (M2), motion tweens, shape
|
||||
* Text fields come across as text blocks (ADR 0014: one block per run of same-style lines,
|
||||
missing fonts named in the report).
|
||||
* Next slices: bitmaps (needs bitmap fills, M5), masks (M2), motion tweens, shape
|
||||
tweens, more scenes, and a corpus of larger self-authored files.
|
||||
@@ -48,6 +48,7 @@ so neither may depend on which fonts happen to be installed.
|
||||
block, stored like any shape's path).
|
||||
* 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
|
||||
fonts for missing characters (missing glyphs draw as the font's "notdef" box).
|
||||
@@ -0,0 +1,71 @@
|
||||
# ADR 0014: Text from Animate documents
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Relates to: roadmap M4 (XFL import), ADR 0009 (XFL import), ADR 0012 (text)
|
||||
|
||||
## Context
|
||||
|
||||
Animate documents are full of text: titles, captions, speech bubbles, credits, score
|
||||
counters. The XFL importer reported every text field as skipped. AniCraft now has a text
|
||||
engine (ADR 0012): `ElementKind::Text(TextBlock)`, one style per block, laid out by
|
||||
`anicraft-text` and stored as outlines.
|
||||
|
||||
An XFL text field (`DOMStaticText`, `DOMDynamicText`, `DOMInputText`) has a matrix, a box
|
||||
(`width`, `height`, optional `left`/`top`), `autoExpand` for auto-size versus fixed width, and
|
||||
a list of text runs: `<DOMTextRun><characters>…</characters><textAttrs><DOMTextAttrs …/>`.
|
||||
The attributes give a face (a PostScript name such as `Arial-BoldMT`, or a device font such
|
||||
as `_sans`), size, fill colour and alpha, alignment, letter spacing, line spacing, margins
|
||||
and indent. Lines end with a carriage return (`
`). This structure comes from public
|
||||
descriptions of XFL and from self-authored files only.
|
||||
|
||||
AniCraft's block has one style, but a field may have runs with different styles.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **A field becomes one text block per run of consecutive lines that share a style.** Runs
|
||||
are split into lines at line breaks; each line takes one style; consecutive lines with the
|
||||
same style make one block, and the blocks stack downwards, each starting where the line
|
||||
after the previous block would (`lines × line_height`, which `anicraft-text` now reports).
|
||||
This keeps the most common mixed case exact: a big title line over smaller body lines,
|
||||
each block editable as text. A **line** that mixes styles (one bold word in a sentence)
|
||||
takes the style of most of its visible characters, and the report counts it. Splitting
|
||||
inside a line would need per-glyph positions from one shared layout; it waits for
|
||||
per-character styles in the text model (ADR 0012, "not yet").
|
||||
2. **Placement.** The element's transform is the field's matrix, then the box offset
|
||||
(`left`, `top`) plus a 2-pixel gutter, the inset of text in Animate's text fields. A
|
||||
fixed-width field wraps at `width` (less its margins); an auto-size field never wraps, and
|
||||
its centred or right-aligned blocks align against the widest block, as lines of one field
|
||||
do.
|
||||
3. **Fonts.** A face is looked up on this computer by its PostScript name, then as a family
|
||||
name (ignoring case and spaces), then as the family the PostScript name suggests
|
||||
(`TimesNewRomanPS-BoldItalicMT` is Times New Roman, bold, italic); `_sans`, `_serif` and
|
||||
`_typewriter` map to installed sans, serif and monospaced families. Boldness and slant
|
||||
come from the face (and `bold`/`italic` attributes when present). A family that isn't
|
||||
installed falls back as the text engine does (ADR 0012), the block records the family
|
||||
actually used, and the report names the missing families and the fallback: "Fonts not on
|
||||
this computer, drawn in Arial: Futura." The lookup lives in `anicraft-text`
|
||||
(`Fonts::find_face`, `guess_family`), so other importers can use it.
|
||||
4. **Dynamic and input text come across as static text**, keeping their instance name on the
|
||||
element, and are counted in the report. They become fields with scripting (M6).
|
||||
5. **Report, don't guess** (ADR 0009): justified text (drawn left-aligned), first-line
|
||||
indents, superscript and subscript, vertical text, filters on text, text cut to the
|
||||
engine's 100,000-character limit, and text on a computer with no fonts at all (nothing is
|
||||
drawn) are counted. Empty fields make nothing.
|
||||
6. **Import lays text out once, with this computer's fonts.** The imported document stores
|
||||
the outlines like any text (ADR 0012), so it then looks the same everywhere. The desktop app
|
||||
registers its embedded Inter before opening a file from the command line, so command-line
|
||||
and menu imports lay out with the same fonts.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Imported titles and captions render, export and stay editable as text (Text tool, Properties,
|
||||
`text.edit`).
|
||||
* Lines with mixed styles lose their minor styles until text blocks have per-character styles;
|
||||
the report says how many.
|
||||
* Positions depend on the fonts' metrics: with the original fonts installed, text sits where
|
||||
Animate puts it within about a pixel; a fallback family changes widths, as it would in
|
||||
Animate.
|
||||
* The shared XML reader now keeps character data (`Element::text`), needed for
|
||||
`<characters>`; 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.
|
||||
@@ -0,0 +1,71 @@
|
||||
# ADR 0015: Crash-recovery autosave
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Relates to: roadmap M8 (crash-recovery autosave), ADR 0001 (persistent document), ADR 0003
|
||||
(file format), ADR 0004 (destructive actions), ADR 0006 (platform layer)
|
||||
|
||||
## Context
|
||||
|
||||
A crash, a power cut or a killed process must never cost an artist more than about a minute of
|
||||
work. Saving the user's own file behind their back is not an option: they decide when their
|
||||
file changes (Animate's own "auto-save" overwrites the document, and many users turn it off for
|
||||
that reason). What they need is a separate copy that only matters when something went wrong.
|
||||
|
||||
The document is a persistent tree (ADR 0001), so a snapshot is an `Arc` clone (0.05 µs on the
|
||||
200k-instance stress document), but serializing it is not free (about 125 ms for its 65 MB).
|
||||
That must never happen on the UI thread.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Recovery copies, never the user's file.** Each running editor is one *recovery session*
|
||||
with a generated id. Its copy lives in the recovery folder as `<id>.anicraft` (an ordinary
|
||||
`.anicraft` file) with a description `<id>.json` (original path, display name, time, app
|
||||
version, frames, scenes). The folder is `Recovery` in the per-OS settings folder
|
||||
(`platform::recovery_dir`; `ANICRAFT_RECOVERY_DIR` overrides it). Ids are restricted to
|
||||
`[A-Za-z0-9_-]`, so a copy can never be written outside the folder, and a write refuses a
|
||||
target that is the user's document or a file that isn't a recovery copy.
|
||||
2. **Atomic writes.** Each file goes to `<name>.tmp`, is flushed to disk (`sync_all`) and renamed
|
||||
over the previous one, so a crash mid-write leaves the last good copy.
|
||||
3. **Liveness by OS file lock.** A running session holds an exclusive lock on `<id>.lock`
|
||||
(`std::fs::File::try_lock`, Rust 1.89+; `LockFileEx` on Windows, `flock` elsewhere). The OS
|
||||
drops the lock when the process ends, however it ends, so at start-up a copy whose lock can
|
||||
be taken was left by a session that didn't close cleanly, and one whose lock is held belongs
|
||||
to another open AniCraft window and is not offered. No heartbeat files, no PIDs to guess
|
||||
about. Stale locks with no copy are pruned at start.
|
||||
4. **Background writer.** `recovery::Autosaver` owns a thread. The shell hands it a snapshot
|
||||
(O(1)); the thread serializes and writes. Jobs run in order (a clear after a save can never
|
||||
overtake the write before it), and when several wait only the newest runs, so a slow disk
|
||||
never builds a queue.
|
||||
5. **When.** A copy is made when the work has been unsaved for the interval (default 1 minute,
|
||||
15 s to 10 min) or after N changes (default 25; 0 = by time only), whichever comes first;
|
||||
not by change count in the middle of a drag (time still applies). The shell schedules a
|
||||
repaint for when the interval runs out, since egui only repaints on input. Preferences ›
|
||||
Files › Autosave sets both, and turns it off.
|
||||
6. **Clean up.** Saving (or undoing back to the saved state, New, Open) clears the session's
|
||||
copy. A clean exit (nothing unsaved, or the user chose Don't Save) removes the copy and the
|
||||
lock. Any other exit writes the work once more and leaves it for the next start. A panic
|
||||
unwinding through `Drop` never deletes anything: only `Autosaver::finish` decides.
|
||||
7. **Restore / Discard / Later.** At start-up, left-behind copies are listed in a non-blocking
|
||||
window (the editor stays usable). **Restore** opens the copy as unsaved work with its
|
||||
original path remembered, so Save goes back there, unless that file changed after the
|
||||
copy was written (saved just before the crash): then it opens untitled and Save asks for a
|
||||
name, so older recovered work never replaces newer work. The restoring session writes its
|
||||
own copy at once and then removes the old one, so there is never a moment with no copy.
|
||||
**Discard** deletes for good, so it takes a second click on a red button (ADR 0004:
|
||||
irreversible; the engine refuses `file.discard_recovery` without `confirm`). **Later**
|
||||
keeps everything; File › Recover Autosaved Documents… brings the window back.
|
||||
8. **Headless.** `file.recovery_list`, `file.recover`, `file.discard_recovery` and
|
||||
`file.autosave` take the folder as `dir`, so scripts, the CLI and MCP agents can recover
|
||||
work too. A headless `file.autosave` holds no lock (commands are stateless), so its copy is
|
||||
offered as left behind; that is the right default for a crashed script.
|
||||
|
||||
## Consequences
|
||||
|
||||
* One more folder in the settings folder; a crash leaves at most one copy per session there.
|
||||
* Locking needs a file system with locks. Where `try_lock` is unsupported, liveness can't be
|
||||
told and every copy is offered (restoring only reads; the owner rewrites its copy).
|
||||
* The copy is a full `.anicraft` file each time. On the stress document that is 0.18 s of
|
||||
background work per copy and 65 MB written; incremental copies would only matter for much
|
||||
larger documents and can come later without changing the folder layout.
|
||||
* Not yet: several documents open at once (the editor has one), keeping more than the newest
|
||||
copy per session, and recovering the undo history (the copy holds the document only).
|
||||
@@ -0,0 +1,84 @@
|
||||
# ADR 0016: Motion tweens and the Motion Editor
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Relates to: roadmap M2 (motion tween + Motion Editor curves), ADR 0001 (persistent document),
|
||||
ADR 0003 (file format), ADR 0004 (destructive actions), ADR 0009 (XFL import)
|
||||
|
||||
## Context
|
||||
|
||||
AniCraft had classic and shape tweens: a keyframe interpolates into the next keyframe with one
|
||||
ease. Animate's *motion tween* works differently, and artists coming from Animate expect it: the
|
||||
tween belongs to one keyframe span and one object in it, each property (position, scale,
|
||||
rotation, skew, colour effect) has its own curve with *property keyframes* anywhere in the span,
|
||||
moving the object at a later frame adds property keyframes instead of timeline keyframes, and
|
||||
the Motion Editor shows each property's curve with Bézier easing. Behaviour was learned from
|
||||
Adobe's public help pages and from observing the program; nothing was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **A motion tween is a field of a keyframe span**: `Keyframe.motion: Option<MotionTween>`
|
||||
(`crates/doc/src/motion.rs`). It names its `target` element and holds at most one `Track`
|
||||
per `Property` (`x`, `y`, `scale_x`, `scale_y`, `rotation`, `skew`, `alpha`, `tint`). A track
|
||||
is a sorted list of `PropertyKey { frame (offset into the span), value, ease }`. A span has
|
||||
either a classic/shape tween (`Keyframe.tween`) or a motion tween; commands keep it so, and
|
||||
loading drops a classic tween beside a motion tween.
|
||||
2. **Values are stored in the units the editor shows**: pixels, percent and degrees (rotation
|
||||
is not wrapped, so 0 → 720 turns twice). The element on the keyframe is the *base*: how the
|
||||
object looks on the span's first frame. A property without a track keeps the base's value;
|
||||
when no transform property is keyed the base transform is used bit for bit, otherwise the
|
||||
transform is composed from the property values (`T · R · Skew · S`, the inverse of
|
||||
`Affine::decompose`). Before its first key a track holds the first value, after its last it
|
||||
holds the last.
|
||||
3. **Per-segment ease is an `Easing`** on the key that starts the segment, so the existing
|
||||
presets work and a custom curve is `Easing::CubicBezier(x1, y1, x2, y2)` — CSS-style handles
|
||||
*relative to the segment's box* (time 0..1, value 0..1 with overshoot allowed). We chose
|
||||
relative handles over absolute (time, value) tangents because they survive value edits and
|
||||
retiming unchanged, keep time monotonic (x is clamped to 0..1), and reuse one easing type
|
||||
everywhere. The cost: a flat segment (equal values) shows no ease; the editor still shows its
|
||||
handles against a share of the view. `Easing::as_bezier` gives every preset its handles
|
||||
(exact except the two in-out polynomials).
|
||||
4. **Evaluation stays pure**: `evaluate_guided` applies `MotionTween::apply(base, offset)` to
|
||||
the target; other elements on the key hold. Every export (PNG, GIF, SVG, Lottie, video,
|
||||
sprite sheet) and hit testing see motion tweens through `evaluate` with no extra code.
|
||||
5. **Auto-key is done once, in the session, for every command.** When a command asks for the
|
||||
keyframe to edit (`Session::editable_keyframe`) inside a motion span, the target is swapped
|
||||
for how it looks at the playhead; after the command, what changed in its transform or colour
|
||||
effect becomes property keys at the playhead (rotation unwrapped against the curve, so a
|
||||
turn past 180° keeps turning the same way) and the base comes back, with any other change
|
||||
(fill, path, name) kept. On the span's first frame an unkeyed property changes the base
|
||||
itself. Moving, nudging, free transform, rotate/flip, align, the Properties fields and
|
||||
alpha all key properties without knowing about motion tweens. Insert Keyframe (F6) inside a
|
||||
span keys every property there instead of splitting the span.
|
||||
6. **Timeline operations keep the motion.** Splitting a span (copy frames across it, moving
|
||||
keyframes onto it) gives the second half a re-based copy of the tween
|
||||
(`MotionTween::split_at`), pasted frames and duplicated scenes re-point the target at the
|
||||
copied object, and removing a motion tween (or replacing it by a classic one) leaves the
|
||||
object as it is on the first frame. When the target's id is gone but the key holds one
|
||||
element, that element is the target, so edits that replace the object (Convert to Symbol)
|
||||
keep its motion.
|
||||
7. **Create Motion Tween** works on any span with artwork: several objects first become one
|
||||
graphic symbol (Animate asks; we do it and say so, and Ctrl+Z undoes it, per ADR 0004), and a
|
||||
one-frame span grows to one second, as in Animate.
|
||||
8. **The file format stays version 3**: `motion` is an additive, `#[serde(default)]` field, as
|
||||
filters and blend modes were. Files without it open unchanged; a build older than this one
|
||||
would open a file with motion tweens and show the objects static (it ignores the field).
|
||||
9. **The Motion Editor is a tab of the timeline dock** (Window › Motion Editor, or double-click
|
||||
a motion span), following the active layer and playhead: a property list (value at the
|
||||
playhead, editable; a key toggle) and the selected property's curve, with draggable keys and
|
||||
Bézier handles. It is view state; every change is a `motion.*` command, and each drag is one
|
||||
undo step (a session gesture).
|
||||
|
||||
Headless: `timeline.create_motion_tween`, `timeline.remove_tween`, `motion.set_key`,
|
||||
`motion.remove_key`, `motion.set_ease`, `motion.info`.
|
||||
|
||||
## Consequences
|
||||
|
||||
* A motion tween animates one object. Artwork added to a motion span later holds still.
|
||||
* 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.
|
||||
* Not yet (later PRs): motion paths drawn and edited on the stage (the path the X/Y curves
|
||||
trace, with orient to path), 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
|
||||
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).
|
||||
@@ -0,0 +1,89 @@
|
||||
# ADR 0017: WebAssembly plug-ins over the command registry
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Relates to: requirements U2, roadmap M6, ADR 0001 (undo), ADR 0004 (destructive actions),
|
||||
ADR 0006 (platforms), ADR 0013 (ActionScript); `docs/plugins.md` is the contract
|
||||
|
||||
## Context
|
||||
|
||||
U2 settled AniCraft's scripting surface: the Craft-family plug-in system, as in PhotoCraft
|
||||
(sandboxed WebAssembly run by `wasmi`, `plugin.*` commands, fuel, memory and time limits, one
|
||||
undo step per run). PhotoCraft's filters are pure functions: pixels in, pixels out, and no
|
||||
imports at all. AniCraft's plug-ins are different work: generate shapes, transform the
|
||||
selection, later drive the timeline from frame scripts. They must read the document and edit
|
||||
it, and the project rules say every edit is a command. Hostile or buggy plug-ins must never
|
||||
crash or hang the app, touch files, or leave half an edit behind.
|
||||
|
||||
## Options considered
|
||||
|
||||
| Option | Verdict |
|
||||
|---|---|
|
||||
| **A. No imports** (PhotoCraft's model): document in, document out as one JSON blob | Every plug-in would re-implement edits and the host would have to diff and validate a whole document. Bypasses the command registry, so no shared checks; large documents cost a full copy both ways. Rejected. |
|
||||
| **B. WASI** (a standard system interface) | Brings files, clocks, randomness and environment into reach; we would spend the design disabling it. Rejected. |
|
||||
| **C. Wide typed ABI** (one import per operation: `draw_rect(x, y, w, h…)`) | Fast, but every new command needs a new import and a new ABI version; the plug-in surface drifts from the registry. Rejected. |
|
||||
| **D. Component model / WIT** | Not supported by `wasmi`'s stable feature set; heavy toolchain for authors. Revisit later. |
|
||||
| **E. `wasmtime`** instead of `wasmi` | A JIT: faster, but large, uses `unsafe` code generation, and doesn't run in the web build. The Craft family standardised on `wasmi`. Rejected. |
|
||||
| **F. Two imports, JSON requests routed to the command registry** | Chosen. |
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Crate `anicraft-plugins` (L0)**: the sandbox. It knows WebAssembly, the manifest and the
|
||||
limits, not the document. The engine implements its `Host` trait.
|
||||
2. **ABI v1** (`docs/plugins.md`): exports `ac_abi_version`, `ac_manifest`, `ac_alloc`,
|
||||
`ac_run`, `memory`; the only imports allowed are `anicraft.call(ptr, len) -> len` and
|
||||
`anicraft.response(ptr, cap) -> n`. A request is `{"op": …}`: `command` (any registry
|
||||
command by id with JSON params), `document` (a compact view), `elements` (the active
|
||||
layer's elements, optionally with paths) and `log`. Answers are `{"ok", "result"|"error"}`.
|
||||
New ops are additive; the version changes only when an existing contract does.
|
||||
3. **Host calls are resumable traps.** `anicraft.call` copies the request out and traps with a
|
||||
marker; the run loop answers it through the `Host` (which borrows the session mutably, so it
|
||||
can't live inside wasmi's `'static` store) and resumes. Fuel runs out the same way, in
|
||||
10 M-instruction slices, which is where the wall-clock deadline is checked.
|
||||
4. **Limits**: 16 MiB modules, 256 MiB memory, 10⁹ instructions and 5 s per run, 100,000
|
||||
requests, 1 MiB requests (64 MiB in all) and 8 MiB responses, 64 KiB params, 200 log lines, call depth
|
||||
1,024, wasmi's strict module limits, a fresh instance per run. Every violation is an error.
|
||||
5. **Policy**: plug-ins may call document commands only. `file.*`, `plugin.*`, undo/redo and
|
||||
the clipboard commands are refused, and so is any namespace the policy doesn't know (a test
|
||||
fails when a new namespace appears, forcing a decision). Irreversible confirmations are
|
||||
refused inside a run.
|
||||
6. **One undo step, atomic.** `plugin.run` is one mutating command. The commands a plug-in
|
||||
makes run *nested* (`Session::execute_nested`): checked and atomic each, no history of their
|
||||
own, state ids refreshed so later requests see earlier edits. Any failure restores the
|
||||
document as it was before the run. The step is named after the plug-in ("Undo Star Field").
|
||||
The app's live preview runs inside a gesture and puts the document back before each re-run
|
||||
(`Session::revert_gesture`), so OK records one step and Cancel none.
|
||||
7. **Registry per session, folder per OS.** Installed plug-ins live on the `Session` (not a
|
||||
process global, not the document), survive New/Open, and are never saved in documents. The
|
||||
app's folder is `<settings folder>/plugins` (from `platform.rs`, ADR 0006), or
|
||||
`ANICRAFT_PLUGINS`; install copies the module there atomically as `<id>.wasm`. The CLI loads
|
||||
plug-ins only with `--plugins` or `ANICRAFT_PLUGINS`, so headless runs stay repeatable.
|
||||
8. **Confirmations (ADR 0004)**: replacing an installed plug-in's file and removing a plug-in
|
||||
whose file is in the folder are irreversible, so they need `"confirm": true`.
|
||||
9. **UI**: a **Commands** menu between Modify and Control, as in Animate, with Plug-ins
|
||||
(installed plug-ins, disabled with a reason when they need a selection), Install Plug-in…,
|
||||
Manage Plug-ins… and Reload Plug-ins; plug-ins in the command palette; a dialog generated
|
||||
from the manifest's parameters with a live preview beside the stage.
|
||||
10. **Samples** in Rust (`examples/plugins`: Star Field, Jitter Selection, a small SDK), built
|
||||
by a script and never committed as binaries; the host's tests use WAT fixtures compiled
|
||||
by the `wat` crate (dev-dependency). The guest SDK has the only `unsafe` a Rust plug-in
|
||||
needs (two imports, raw pointers of the exports). It is guest code inside the sandbox, outside
|
||||
the AniCraft workspace and its `unsafe_code = "forbid"`.
|
||||
|
||||
## Building on it
|
||||
|
||||
Frame scripts and ActionScript tier 2 (ADR 0013) reuse this host: a `frame-script` kind whose
|
||||
`ac_run` answers playback events with ops from the timeline action IR (`stop`, `play`,
|
||||
`goto`, …), run by the pure player, never by mutating the document. Exporters and easing
|
||||
presets are further kinds. None of them changes v1.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Plug-ins get the whole command registry, with the same validation as the UI, the CLI and
|
||||
MCP, and every run is one undoable, atomic step.
|
||||
* Hostile modules end in an error: endless loops by fuel or time, memory bombs at the cap,
|
||||
request floods at the request budget, bad pointers and traps as errors (tests in
|
||||
`crates/plugins/tests/abi.rs` and `crates/engine/src/plugin_tests.rs`).
|
||||
* JSON costs about 75 µs per request in a debug build: fine for hundreds or a few thousand
|
||||
edits per run, not for per-pixel work. A compact binary view can be added as new ops.
|
||||
* Runs block the UI thread for at most their time budget; background runs with progress and
|
||||
cancel come later.
|
||||
@@ -29,6 +29,7 @@
|
||||
app/ workspace root; the root package is the desktop app (`anicraft`)
|
||||
crates/
|
||||
geom L0 Vec2, Affine (+ decompose/compose for tweening), Rect, Path, flattening, hit test
|
||||
plugins L0 WebAssembly plug-in sandbox (wasmi): ABI v1, limits, manifest, registry (ADR 0017)
|
||||
doc L1 Document model + timeline evaluation (keyframes, tweens, easing, symbols)
|
||||
render L2 CPU oracle rasterizer, paints/gradients, compositor, PNG encode
|
||||
engine L3 Session (document + history + selection + playhead), command registry, file format
|
||||
@@ -40,6 +41,7 @@ app/ workspace root; the root package is the desktop app
|
||||
| Layer | Crate | May depend on |
|
||||
|---|---|---|
|
||||
| L0 | `anicraft-geom` | std, serde |
|
||||
| L0 | `anicraft-plugins` | wasmi, serde_json (knows nothing of documents; the engine is its host) |
|
||||
| L1 | `anicraft-doc` | geom |
|
||||
| L2 | `anicraft-render` | geom, doc, rayon, png |
|
||||
| L3 | `anicraft-engine` | geom, doc, render, serde_json |
|
||||
|
||||
|
After Width: | Height: | Size: 661 KiB |
|
After Width: | Height: | Size: 369 KiB |
|
After Width: | Height: | Size: 386 KiB |
|
After Width: | Height: | Size: 373 KiB |
|
After Width: | Height: | Size: 385 KiB |
|
After Width: | Height: | Size: 398 KiB |
|
After Width: | Height: | Size: 444 KiB |
|
After Width: | Height: | Size: 531 KiB |
@@ -43,6 +43,12 @@ cargo deny check advisories # RustSec security advisories (needs ne
|
||||
|
||||
* Full per-crate list: [`third-party-inventory.txt`](third-party-inventory.txt) (regenerate when
|
||||
`Cargo.lock` changes).
|
||||
* **2026-11-09, WebAssembly plug-ins (ADR 0017)**: `wasmi` 2.0 and its `wasmi_core`,
|
||||
`wasmi_ir`, `wasmi_collections` (MIT OR Apache-2.0), `wasmparser` 0.228 (Apache-2.0 WITH
|
||||
LLVM-exception, already allowed) and `spin` (MIT). Tests only: `wat` and its
|
||||
`wasm-encoder`/`wast` (Apache-2.0 WITH LLVM-exception). No new licence. Plug-ins are the
|
||||
user's own files: AniCraft ships none in the binary; the sample plug-ins are source under
|
||||
`examples/plugins` (MIT OR Apache-2.0).
|
||||
|
||||
## 3. Fonts, graphics and other assets
|
||||
|
||||
@@ -80,6 +86,7 @@ cargo deny check advisories # RustSec security advisories (needs ne
|
||||
| **Video export** | H.264/HEVC/AAC are covered by patent pools. VP9, AV1 and Opus are royalty-free. | **Never bundle encoders for patent-pool codecs.** MP4/H.264 only by piping to a user-installed ffmpeg. Default to WebM (VP9/AV1). **As built** (`file.export_video`): AniCraft starts the user's ffmpeg (found via a parameter, `ANICRAFT_FFMPEG` or the PATH) with an argument list, never a shell, writes raw RGBA frames to its stdin, and ships no codec code; the default file type is `.webm` (VP9). |
|
||||
| **XFL / FLA import** (M4) | Adobe's proprietary formats, without a public specification. | Clean room: work only from files users or we author, public community docs and observation. Never use Adobe code, SDKs or decompiled software. Interoperability-focused (generally protected in EU Software Directive art. 6 and US DMCA §1201(f)); **confirm with counsel before shipping**. |
|
||||
| **ActionScript compatibility** (M6, ADR 0013) | A programming language; no known patent pool. Implemented from ECMA-262 (3rd edition) and Adobe's public ActionScript 3.0 references. | Clean room as for XFL: public documents and self-authored files only; never Adobe compilers, SDKs or player code. Keep and run a timeline subset only; no bytecode VM. |
|
||||
| WebAssembly (plug-ins, ADR 0017) | W3C standard under the W3C Royalty-Free Patent Policy. | Allowed. Interpreted by `wasmi` (no code generation). |
|
||||
| SWF export (optional) | Adobe published the SWF specification and lifted its use restrictions in 2009 (Open Screen Project). | Allowed, low priority. |
|
||||
| Lottie | Open specification (Lottie Animation Community, Linux Foundation). | Allowed. |
|
||||
|
||||
@@ -92,7 +99,8 @@ cargo deny check advisories # RustSec security advisories (needs ne
|
||||
* "ActionScript" is also an Adobe trademark. Docs and compatibility messages (import reports,
|
||||
the language a kept script is written in) name it nominatively; the features themselves have
|
||||
generic names (Actions panel, frame scripts, Test Movie). See ADR 0013.
|
||||
* "AniCraft": a trademark clearance search has not been done yet (open item below).
|
||||
* "AniCraft": the project lead accepted the name (2026-11-09). No formal clearance search was
|
||||
done; that was their decision.
|
||||
|
||||
## 6. Release checklist (before any public binary)
|
||||
|
||||
@@ -109,6 +117,6 @@ cargo deny check advisories # RustSec security advisories (needs ne
|
||||
| Item | Status |
|
||||
|---|---|
|
||||
| Counsel review of this document (patents, XFL interoperability, ActionScript compatibility and naming) | Open, before the first public release |
|
||||
| "AniCraft" trademark clearance | Open |
|
||||
| "AniCraft" trademark clearance | Settled by the project lead (2026-11-09): the name is kept |
|
||||
| Freedom-to-operate patent search for core animation features | Open (recommended before 1.0) |
|
||||
| Full licence-text bundle generation (`cargo about`) in the release pipeline | Open (M8) |
|
||||
@@ -3,17 +3,17 @@ All target platforms (Windows, macOS, Linux, Android, wasm). Regenerate when Car
|
||||
Dual-licensed crates appear under each licence they offer; see docs/legal/compliance.md for the licence elected.
|
||||
|
||||
0BSD (1): adler2@2.0.1
|
||||
Apache-2.0 (298): ab_glyph@0.2.32, ab_glyph_rasterizer@0.1.10, accesskit@0.24.1, accesskit_atspi_common@0.18.1, accesskit_consumer@0.35.0, accesskit_consumer@0.36.0, accesskit_consumer@0.38.0, accesskit_macos@0.26.3, accesskit_unix@0.21.1, accesskit_windows@0.32.1, accesskit_winit@0.32.2, adler2@2.0.1, ahash@0.8.12, allocator-api2@0.2.21, android-activity@0.6.1, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-render@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, cc@1.10.0, cfg-if@1.0.5, cgl@0.3.2, codespan-reporting@0.13.1, color@0.3.3, concurrent-queue@2.5.0, core-foundation@0.9.4, core-foundation-sys@0.8.7, core-graphics@0.23.2, core-graphics-types@0.1.3, crc32fast@1.5.3, crossbeam-deque@0.8.8, crossbeam-epoch@0.9.21, crossbeam-utils@0.8.23, cursor-icon@1.2.0, dispatch2@0.3.1, displaydoc@0.2.7, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, form_urlencoded@1.2.2, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, gethostname@1.1.0, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, gl_generator@0.14.0, glow@0.17.0, glutin@0.32.3, glutin_egl_sys@0.7.1, glutin_glx_sys@0.6.1, glutin_wgl_sys@0.6.1, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, idna@1.1.0, idna_adapter@1.2.2, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, khronos_api@3.1.0, kurbo@0.13.1, libc@0.2.191, linebender_resource_handle@0.1.1, linux-raw-sys@0.12.1, linux-raw-sys@0.4.15, litrs@1.0.1, lock_api@0.4.14, log@0.4.34, memmap2@0.9.12, miniz_oxide@0.8.9, miniz_oxide@0.9.1, moxcms@0.8.1, naga@30.0.1, naga-types@30.0.1, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-traits@0.2.19, num_enum@0.7.6, num_enum_derive@0.7.6, objc2-app-kit@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, ordered-stream@0.2.0, owned_ttf_parser@0.25.1, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, pxfm@0.1.30, quick-error@2.0.1, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, renderdoc-sys@1.1.0, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, scoped-tls@1.0.1, scopeguard@1.2.0, self_cell@1.3.0, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, shlex@2.0.1, signal-hook-registry@1.4.8, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, smallvec@1.16.4, smol_str@0.2.2, spirv@0.4.0+sdk-1.4.341.0, stable_deref_trait@1.2.1, static_assertions@1.1.0, syn@2.0.119, syn@3.0.9, tempfile@3.27.0, thiserror@1.0.69, thiserror@2.0.21, thiserror-impl@1.0.69, thiserror-impl@2.0.21, tinyvec@1.13.3, toml_datetime@1.1.2+spec-1.1.0, toml_edit@0.25.17+spec-1.1.0, toml_parser@1.1.5+spec-1.1.0, ttf-parser@0.25.1, type-map@0.5.1, unicode-general-category@1.1.0, unicode-ident@1.0.27, unicode-segmentation@1.13.3, unicode-width@0.2.2, url@2.5.8, utf8_iter@1.0.4, uuid@1.29.0, vello_common@0.1.0, vello_cpu@0.1.0, version_check@0.9.5, wasip2@1.0.4+wasi-0.2.12, wasm-bindgen@0.2.129, wasm-bindgen-futures@0.4.79, wasm-bindgen-macro@0.2.129, wasm-bindgen-macro-support@0.2.129, wasm-bindgen-shared@0.2.129, web-sys@0.3.106, web-timLine truncated
|
||||
Apache-2.0 WITH LLVM-exception (6): linux-raw-sys@0.12.1, linux-raw-sys@0.4.15, rustix@0.38.44, rustix@1.1.5, wasip2@1.0.4+wasi-0.2.12, wit-bindgen@0.57.1
|
||||
BSD-2-Clause (3): arrayref@0.3.9, zerocopy@0.8.63, zerocopy-derive@0.8.63
|
||||
BSD-3-Clause (6): moxcms@0.8.1, num_enum@0.7.6, num_enum_derive@0.7.6, pxfm@0.1.30, tiny-skia@0.11.4, tiny-skia-path@0.11.4
|
||||
Apache-2.0 (297): accesskit@0.24.1, accesskit_atspi_common@0.18.1, accesskit_consumer@0.35.0, accesskit_consumer@0.36.0, accesskit_consumer@0.38.0, accesskit_macos@0.26.3, accesskit_unix@0.21.1, accesskit_windows@0.32.1, accesskit_winit@0.32.2, adler2@2.0.1, ahash@0.8.12, allocator-api2@0.2.21, android-activity@0.6.1, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-plugins@0.1.0, anicraft-render@0.1.0, anicraft-svg@0.1.0, anicraft-text@0.1.0, anicraft-xfl@0.1.0, anicraft-xml@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, cc@1.10.0, cfg-if@1.0.5, cgl@0.3.2, codespan-reporting@0.13.1, color@0.3.3, concurrent-queue@2.5.0, core-foundation@0.9.4, core-foundation-sys@0.8.7, core-graphics@0.23.2, core-graphics-types@0.1.3, crc32fast@1.5.3, crossbeam-deque@0.8.8, crossbeam-epoch@0.9.21, crossbeam-utils@0.8.23, cursor-icon@1.2.0, dispatch2@0.3.1, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, gethostname@1.1.0, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, gl_generator@0.14.0, glow@0.17.0, glutin@0.32.3, glutin_egl_sys@0.7.1, glutin_glx_sys@0.6.1, glutin_wgl_sys@0.6.1, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, khronos_api@3.1.0, kurbo@0.13.1, libc@0.2.191, linebender_resource_handle@0.1.1, linux-raw-sys@0.12.1, linux-raw-sys@0.4.15, litrs@1.0.1, lock_api@0.4.14, log@0.4.34, memmap2@0.9.12, miniz_oxide@0.8.9, miniz_oxide@0.9.1, moxcms@0.8.1, naga@30.0.1, naga-types@30.0.1, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-traits@0.2.19, num_enum@0.7.6, num_enum_derive@0.7.6, objc2-app-kit@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, ordered-stream@0.2.0, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, pxfm@0.1.30, quick-error@2.0.1, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, renderdoc-sys@1.1.0, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, scoped-tls@1.0.1, scopeguard@1.2.0, self_cell@1.3.0, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, shlex@2.0.1, signal-hook-registry@1.4.8, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, smallvec@1.16.4, smol_str@0.2.2, spirv@0.4.0+sdk-1.4.341.0, static_assertions@1.1.0, syn@2.0.119, syn@3.0.9, tempfile@3.27.0, thiserror@1.0.69, thiserror@2.0.21, thiserror-impl@1.0.69, thiserror-impl@2.0.21, tinyvec@1.13.3, toml_datetime@1.1.2+spec-1.1.0, toml_edit@0.25.17+spec-1.1.0, toml_parser@1.1.5+spec-1.1.0, ttf-parser@0.25.1, type-map@0.5.1, unicode-general-category@1.1.0, unicode-ident@1.0.27, unicode-segmentation@1.13.3, unicode-width@0.2.2, uuid@1.29.0, vello_common@0.1.0, vello_cpu@0.1.0, version_check@0.9.5, wasip2@1.0.4+wasi-0.2.12, wasm-bindgen@0.2.129, wasm-bindgen-futures@0.4.79, wasm-bindgen-macro@0.2.129, wasm-bindgen-macro-support@0.2.129, wasm-bindgen-shared@0.2.129, wasmi@2.0.0, wasmi_collections@2.0.0, wasmi_core@2.0.0, wasmi_ir@2.0.0, wasmparser@0.228.0, web-sys@0.3.106, web-timLine truncated
|
||||
Apache-2.0 WITH LLVM-exception (7): linux-raw-sys@0.12.1, linux-raw-sys@0.4.15, rustix@0.38.44, rustix@1.1.5, wasip2@1.0.4+wasi-0.2.12, wasmparser@0.228.0, wit-bindgen@0.57.1
|
||||
BSD-2-Clause (2): zerocopy@0.8.63, zerocopy-derive@0.8.63
|
||||
BSD-3-Clause (4): moxcms@0.8.1, num_enum@0.7.6, num_enum_derive@0.7.6, pxfm@0.1.30
|
||||
BSL-1.0 (2): clipboard-win@5.4.3, error-code@3.4.0
|
||||
GPL-2.0-only (1): self_cell@1.3.0
|
||||
ISC (1): libloading@0.8.9
|
||||
LGPL-2.1-or-later (2): r-efi@5.3.0, r-efi@6.0.0
|
||||
MIT (368): accesskit@0.24.1, accesskit_atspi_common@0.18.1, accesskit_consumer@0.35.0, accesskit_consumer@0.36.0, accesskit_consumer@0.38.0, accesskit_macos@0.26.3, accesskit_unix@0.21.1, accesskit_windows@0.32.1, adler2@2.0.1, ahash@0.8.12, allocator-api2@0.2.21, android-activity@0.6.1, android-properties@0.2.2, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-render@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, block2@0.5.1, block2@0.6.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, byteorder-lite@0.1.0, bytes@1.12.1, calloop@0.13.0, calloop@0.14.5, calloop-wayland-source@0.3.0, calloop-wayland-source@0.4.1, cc@1.10.0, cfg-if@1.0.5, cfg_aliases@0.2.2, cgl@0.3.2, color@0.3.3, color_quant@1.1.0, combine@4.6.9, concurrent-queue@2.5.0, core-foundation@0.9.4, core-foundation-sys@0.8.7, core-graphics@0.23.2, core-graphics-types@0.1.3, core_maths@0.1.1, crc32fast@1.5.3, crossbeam-deque@0.8.8, crossbeam-epoch@0.9.21, crossbeam-utils@0.8.23, crunchy@0.2.4, cursor-icon@1.2.0, dispatch@0.2.0, dispatch2@0.3.1, displaydoc@0.2.7, dlib@0.5.3, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, endi@1.1.1, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fax@0.2.7, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, fontdb@0.23.0, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, form_urlencoded@1.2.2, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, glow@0.17.0, glutin-winit@0.5.0, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, harfrust@0.12.0, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, idna@1.1.0, idna_adapter@1.2.2, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, kurbo@0.13.1, libc@0.2.191, libm@0.2.16, libredox@0.1.25, linebender_resource_handle@0.1.1, linux-raw-sys@0.12.1, linux-raw-sys@0.4.15, litrs@1.0.1, lock_api@0.4.14, log@0.4.34, memchr@2.8.3, memmap2@0.9.12, memoffset@0.9.1, miniz_oxide@0.8.9, miniz_oxide@0.9.1, naga@30.0.1, naga-types@30.0.1, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-traits@0.2.19, num_enum@0.7.6, num_enum_derive@0.7.6, objc-sys@0.3.5, objc2@0.5.3, objc2@0.6.5, objc2-app-kit@0.2.2, objc2-app-kit@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-encode@4.1.0, objc2-foundation@0.2.2, objc2-foundation@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.2.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, orbclient@0.3.55, ordered-float@5.5.0, ordered-stream@0.2.0, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, phf@0.13.1, phf_generator@0.13.1, phf_macros@0.13.1, phf_shared@0.13.1, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, quick-error@2.0.1, quick-xml@0.41.0, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, redox_syscall@0.4.1, redox_syscall@0.5.18, redox_syscall@0.9.5, renderdoc-sys@1.1.0, rfd@0.17.2, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, same-file@1.0.6, scoped-tls@1.0.1, scopeguard@1.2.0, sctk-adwaita@0.10.1, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, shlex@2.0.1, signal-hook-registry@1.4.8, simd-adler32@0.3.10, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, slab@0.4.12, smallvec@1.16.4, smithay-client-toolkit@0.19.2, smithay-client-toolkit@0.20.0, smithay-clipboard@0.7.3, smol_str@0.2.2, stable_deref_trait@1.2.1, static_assertions@1.1.0, strict-num@0.1.1, syn@2.0.119, syn@3.0.9, synstructure@Line truncated
|
||||
MIT (368): accesskit@0.24.1, accesskit_atspi_common@0.18.1, accesskit_consumer@0.35.0, accesskit_consumer@0.36.0, accesskit_consumer@0.38.0, accesskit_macos@0.26.3, accesskit_unix@0.21.1, accesskit_windows@0.32.1, adler2@2.0.1, ahash@0.8.12, allocator-api2@0.2.21, android-activity@0.6.1, android-properties@0.2.2, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-plugins@0.1.0, anicraft-render@0.1.0, anicraft-svg@0.1.0, anicraft-text@0.1.0, anicraft-xfl@0.1.0, anicraft-xml@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, block2@0.5.1, block2@0.6.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, byteorder-lite@0.1.0, bytes@1.12.1, calloop@0.13.0, calloop@0.14.5, calloop-wayland-source@0.3.0, calloop-wayland-source@0.4.1, cc@1.10.0, cfg-if@1.0.5, cfg_aliases@0.2.2, cgl@0.3.2, color@0.3.3, color_quant@1.1.0, combine@4.6.9, concurrent-queue@2.5.0, core-foundation@0.9.4, core-foundation-sys@0.8.7, core-graphics@0.23.2, core-graphics-types@0.1.3, core_maths@0.1.1, crc32fast@1.5.3, crossbeam-deque@0.8.8, crossbeam-epoch@0.9.21, crossbeam-utils@0.8.23, crunchy@0.2.4, cursor-icon@1.2.0, dispatch@0.2.0, dispatch2@0.3.1, dlib@0.5.3, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, endi@1.1.1, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fax@0.2.7, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, fontdb@0.23.0, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, glow@0.17.0, glutin-winit@0.5.0, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, harfrust@0.12.0, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, kurbo@0.13.1, libc@0.2.191, libm@0.2.16, libredox@0.1.25, linebender_resource_handle@0.1.1, linux-raw-sys@0.12.1, linux-raw-sys@0.4.15, litrs@1.0.1, lock_api@0.4.14, log@0.4.34, memchr@2.8.3, memmap2@0.9.12, memoffset@0.9.1, miniz_oxide@0.8.9, miniz_oxide@0.9.1, naga@30.0.1, naga-types@30.0.1, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-traits@0.2.19, num_enum@0.7.6, num_enum_derive@0.7.6, objc-sys@0.3.5, objc2@0.5.3, objc2@0.6.5, objc2-app-kit@0.2.2, objc2-app-kit@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-encode@4.1.0, objc2-foundation@0.2.2, objc2-foundation@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.2.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, orbclient@0.3.55, ordered-float@5.5.0, ordered-stream@0.2.0, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, phf@0.13.1, phf_generator@0.13.1, phf_macros@0.13.1, phf_shared@0.13.1, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, quick-error@2.0.1, quick-xml@0.41.0, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, redox_syscall@0.4.1, redox_syscall@0.5.18, redox_syscall@0.9.5, renderdoc-sys@1.1.0, rfd@0.17.2, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, same-file@1.0.6, scoped-tls@1.0.1, scopeguard@1.2.0, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, shlex@2.0.1, signal-hook-registry@1.4.8, simd-adler32@0.3.10, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, slab@0.4.12, smallvec@1.16.4, smithay-client-toolkit@0.19.2, smithay-client-toolkit@0.20.0, smithay-clipboard@0.7.3, smol_str@0.2.2, spin@0.9.9, static_assertions@1.1.0, syn@2.0.119, syn@3.0.9, tempfile@3.27.0, thiserror@1.0.69,Line truncated
|
||||
OFL-1.1 (1): epaint_default_fonts@0.36.2
|
||||
Ubuntu-font-1.0 (1): epaint_default_fonts@0.36.2
|
||||
Unicode-3.0 (19): icu_collections@2.4.0, icu_locale_core@2.4.0, icu_normalizer@2.4.0, icu_normalizer_data@2.4.0, icu_properties@2.4.0, icu_properties_data@2.4.0, icu_provider@2.4.0, litemap@0.8.3, potential_utf@0.1.6, tinystr@0.8.5, unicode-ident@1.0.27, writeable@0.6.4, yoke@0.8.4, yoke-derive@0.8.4, zerofrom@0.1.8, zerofrom-derive@0.1.8, zerotrie@0.2.5, zerovec@0.11.9, zerovec-derive@0.11.7
|
||||
Unicode-3.0 (1): unicode-ident@1.0.27
|
||||
Unlicense (5): byteorder-lite@0.1.0, memchr@2.8.3, same-file@1.0.6, walkdir@2.5.0, winapi-util@0.1.11
|
||||
Zlib (20): bytemuck@1.25.2, bytemuck_derive@1.12.1, cursor-icon@1.2.0, dispatch2@0.3.1, foldhash@0.2.0, glow@0.17.0, miniz_oxide@0.8.9, miniz_oxide@0.9.1, objc2-app-kit@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.3.2, raw-window-handle@0.6.2, slotmap@1.1.1, tinyvec@1.13.3, xkeysym@0.2.1, zune-core@0.5.3, zune-jpeg@0.5.15
|
||||
@@ -35,6 +35,8 @@ The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k elemen
|
||||
| File size | < 400 bytes per element instance | 342 ✅ | test, every PR |
|
||||
| Save / load 65 MB file | < 500 ms | 123 / 146 ms ✅ | `bench --check` |
|
||||
| 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` |
|
||||
|
||||
**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).
|
||||
@@ -50,6 +52,19 @@ Timing each step of a frame showed the time was outside the drawing itself:
|
||||
Output is unchanged: the sample's frames and a bitmap document render byte-identical before
|
||||
and after.
|
||||
|
||||
**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
|
||||
`Arc` snapshot of the document; the worker serializes and writes atomically (temp file,
|
||||
flushed to disk, renamed).
|
||||
|
||||
| Document | Editing thread | Serialize | Write + flush + rename | Total, in the background |
|
||||
|---|---|---|---|---|
|
||||
| 200k instances, 65 MB | 6.6–15.4 µs | 124–128 ms | 52–55 ms | 183–184 ms |
|
||||
| 800k instances (100 × 400 × 240), 262 MB | 9.9 µs | 501 ms | 210 ms | 725 ms |
|
||||
|
||||
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.
|
||||
|
||||
### How budgets are enforced
|
||||
|
||||
* **Budgets that don't depend on the machine** (undo memory, snapshot sharing, file size,
|
||||
@@ -68,3 +83,4 @@ and after.
|
||||
* [ADR 0001](adr/0001-undo-persistent-snapshots.md): persistent document and snapshot undo
|
||||
* [ADR 0002](adr/0002-render-pipeline.md): render worker, frame cache, band parallelism, culling
|
||||
* [ADR 0003](adr/0003-file-format-v2.md): compact file format with shared paths
|
||||
* [ADR 0015](adr/0015-crash-recovery-autosave.md): crash-recovery autosave on a worker thread
|
||||
@@ -0,0 +1,228 @@
|
||||
# Plug-ins: the WebAssembly plug-in API (ABI v1)
|
||||
|
||||
AniCraft plug-ins are **WebAssembly modules** run in a sandbox, the same host model as the other
|
||||
Craft apps (PhotoCraft's filter plug-ins). One `.wasm` file works on Windows, macOS, Linux and,
|
||||
later, the web build. A plug-in adds a command: it reads the open document and changes it
|
||||
through AniCraft's own command registry, so everything it does is checked like any other edit
|
||||
and can be undone in one step. The decision and the alternatives are in
|
||||
[ADR 0017](adr/0017-wasm-plugins.md).
|
||||
|
||||
This page is the contract for plug-in authors and the reference for the host
|
||||
(`crates/plugins`, the `plugin.*` commands in `crates/engine/src/cmds_plugin.rs`).
|
||||
|
||||
## Using plug-ins
|
||||
|
||||
In the app: **Commands › Plug-ins** lists the installed plug-ins. One with settings opens a
|
||||
dialog generated from its parameters, with a live preview on the stage; **OK** (Enter) keeps
|
||||
the result as one undo step named after the plug-in, **Cancel** (Esc) leaves the document as it
|
||||
was. **Commands › Install Plug-in…** picks a `.wasm` file, **Manage Plug-ins…** shows what is
|
||||
installed (with Run, Remove, the plug-ins folder and Reload), and **Reload Plug-ins** re-reads
|
||||
the folder. The command palette (Ctrl+K) finds plug-ins by name too. A plug-in that works on
|
||||
the selection is greyed out until something is selected.
|
||||
|
||||
| Command | Params | What it does |
|
||||
|---|---|---|
|
||||
| `plugin.install` | `{"path": "x.wasm", "confirm"?: true}` | Validates the module and installs it. With a plug-ins folder, the module is copied there as `<id>.wasm` (atomically). Replacing an installed plug-in's file is irreversible, so it needs `"confirm": true` (ADR 0004). |
|
||||
| `plugin.list` | `{}` | `{"plugins": [{id, name, version, author, description, kind, selection, params, notation, size, source, in_folder}], "folder", "abi"}`. In the app: the Plug-ins window. |
|
||||
| `plugin.run` | `{"id": "…", "params"?: {…}}` | Runs a plug-in. Missing params take their defaults; numbers are clamped to their range; a wrong type is an error. One undo step; on any failure the document is left exactly as it was. Returns the run's log, request count and instructions used. |
|
||||
| `plugin.remove` | `{"id": "…", "confirm"?: true}` | Uninstalls. When its file is in the plug-ins folder it is deleted, which needs `"confirm": true`. |
|
||||
| `plugin.reload` | `{"folder"?: "…"}` | Re-reads every `*.wasm` in the plug-ins folder (first making `folder` the plug-ins folder when given). A bad module is reported and skipped. |
|
||||
|
||||
**Where plug-ins live.** The app uses a `plugins` folder in its settings folder:
|
||||
`%APPDATA%\AniCraft\plugins` on Windows, `~/Library/Application Support/AniCraft/plugins` on
|
||||
macOS, `$XDG_CONFIG_HOME/anicraft/plugins` (default `~/.config/anicraft/plugins`) on Linux. Every
|
||||
`*.wasm` in it loads at start. The `ANICRAFT_PLUGINS` environment variable points somewhere
|
||||
else instead (handy while writing a plug-in). Plug-ins belong to the session, not the
|
||||
document: they stay installed across New and Open, and documents never contain plug-ins.
|
||||
|
||||
**Headless.** `anicraft-cli` loads plug-ins only when asked, so scripted runs are repeatable:
|
||||
`--plugins <folder>` (or `ANICRAFT_PLUGINS`) on any subcommand, or `plugin.reload` with a folder.
|
||||
Over MCP the same commands are available through `anicraft_run`.
|
||||
|
||||
```sh
|
||||
anicraft-cli exec --sample plugin.run '{"id":"org.anicraft.star-field","params":{"count":200}}' \
|
||||
--plugins examples/plugins/dist --save stars.anicraft
|
||||
```
|
||||
|
||||
## The sandbox
|
||||
|
||||
The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssembly interpreter
|
||||
(MIT OR Apache-2.0), built with full validation, its strict module limits and the portable
|
||||
dispatcher (the default tail-call dispatcher can overflow the host stack on a long-running
|
||||
module, which would abort the process). Limits (`anicraft_plugins::Limits`, defaults):
|
||||
|
||||
| Limit | Default | On violation |
|
||||
|---|---|---|
|
||||
| Host imports | only `anicraft.call` and `anicraft.response` (no WASI, files, clock, randomness or network) | module rejected at install |
|
||||
| Module size | 16 MiB | rejected |
|
||||
| Linear memory | 256 MiB per instance | `memory.grow` returns −1; an oversized initial memory fails to load |
|
||||
| Instructions (fuel) | 1,000,000,000 per run (a tenth for loading) | the run stops: "exceeded its instruction budget" |
|
||||
| Wall clock | 5 s per run, host calls included (native builds; checked every 10 M instructions and at every request) | "exceeded its time budget" |
|
||||
| Requests | 100,000 per run | "exceeded its host-call budget" |
|
||||
| Request / response size | 1 MiB / 8 MiB | an oversized request traps; an oversized response becomes an error answer |
|
||||
| All requests of a run | 64 MiB | "exceeded its request budget" (bounds what one run can add to a document) |
|
||||
| Params handed to `ac_run` | 64 KiB | error |
|
||||
| Log | 200 lines of ≤ 500 characters (more are counted, not kept) | dropped |
|
||||
| Call depth | 1,024 frames | trap |
|
||||
|
||||
Every run gets a **fresh instance**, so nothing survives from one run to the next. Traps,
|
||||
exhausted budgets, malformed modules, bad manifests, out-of-range pointers and non-zero return
|
||||
codes all become errors, and the document goes back to how it was before the run. The CPU
|
||||
interpreter runs about 470 M simple instructions per second on the development machine, so the
|
||||
default fuel is roughly two seconds of computing.
|
||||
|
||||
**What a plug-in may do.** Requests reach the same commands the menus, the CLI and MCP use,
|
||||
with the same parameter checks, except:
|
||||
|
||||
* `file.*`: no opening, saving, importing or exporting files;
|
||||
* `plugin.*`: no installing, running or removing plug-ins;
|
||||
* `edit.undo`, `edit.redo`: the whole run is one undo step;
|
||||
* cut, copy and paste (artwork and frames): your clipboard is yours.
|
||||
|
||||
Commands in a namespace the host doesn't know are refused, and a test fails when a new
|
||||
namespace appears without a decision. Commands that would need an irreversible confirmation
|
||||
are refused too.
|
||||
|
||||
## ABI v1
|
||||
|
||||
A plug-in is a core WebAssembly module (MVP plus the usual post-MVP features: bulk memory, sign
|
||||
extension, multi-value, saturating conversions; no SIMD, no memory64). All integers are `i32`
|
||||
unless noted; pointers are offsets into the module's memory.
|
||||
|
||||
### Exports
|
||||
|
||||
| Export | Signature | Meaning |
|
||||
|---|---|---|
|
||||
| `memory` | memory | The module's linear memory. |
|
||||
| `ac_abi_version` | `() -> i32` | Must return `1`. |
|
||||
| `ac_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). |
|
||||
| `ac_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. |
|
||||
| `ac_run` | `(params_ptr, params_len) -> i32` | Runs the command with the validated parameters (UTF-8 JSON object). `0` = success; anything else fails the run (and undoes it), with the last log line as the message. |
|
||||
|
||||
### Imports (module `anicraft`, both optional)
|
||||
|
||||
| Import | Signature | Meaning |
|
||||
|---|---|---|
|
||||
| `call` | `(req_ptr, req_len) -> i32` | Sends one JSON request; returns the length of the response. |
|
||||
| `response` | `(dst_ptr, dst_cap) -> i32` | Copies up to `dst_cap` bytes of the last response to `dst_ptr`; returns the bytes copied. |
|
||||
|
||||
Every response is JSON: `{"ok":true,"result":…}` or `{"ok":false,"error":"…"}` (`ok` always
|
||||
first). A refused or failed request is an answer, not a trap: the plug-in decides what to do.
|
||||
|
||||
### Requests
|
||||
|
||||
| Request | Result |
|
||||
|---|---|
|
||||
| `{"op":"command","id":"draw.star","params":{…}}` | The command's result (see `anicraft-cli commands` for ids and params). |
|
||||
| `{"op":"document"}` | `{abi, stage: {width, height, fps, background}, scene, scenes, frame, frames, layer, layers: [{id, name, kind, visible, locked, parent}], selection: [ids]}` |
|
||||
| `{"op":"elements","selected"?:bool,"paths"?:bool}` | The elements on the active layer at the playhead (tweens applied): `{layer, frame, elements: [{id, kind: shape\|symbol\|text, name, selected, transform: [a,b,c,d,e,f], bounds: [x,y,w,h] (stage), alpha, fill, stroke, path (SVG path data, local space, with "paths")}]}` (at most 10,000). |
|
||||
| `{"op":"log","message":"…"}` | `null`; the line goes into the run's report, and the last one explains a failure. |
|
||||
|
||||
Unknown ops answer `{"ok":false,"error":"unknown op '…'"}`, so a plug-in can feature-detect.
|
||||
New ops and plug-in kinds are added without changing version 1; the version changes only
|
||||
when an existing contract changes.
|
||||
|
||||
**Reserved for later kinds** (not in v1; ADR 0013 and 0014): timeline actions for frame
|
||||
scripts (`stop`, `play`, `goto` by frame or label, targeting named instances), the same IR the
|
||||
ActionScript front end lowers to; exporters (`kind: "exporter"`, frames in, bytes out); easing
|
||||
presets.
|
||||
|
||||
### Manifest
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "org.example.stars",
|
||||
"name": "Star Field",
|
||||
"version": "1.0.0",
|
||||
"kind": "command",
|
||||
"author": "Example",
|
||||
"description": "What it does, one sentence.",
|
||||
"selection": "optional",
|
||||
"params": {
|
||||
"count": {"type": "int", "min": 1, "max": 1000, "default": 120, "label": "Stars"},
|
||||
"size": {"type": "number", "min": 1, "max": 50, "default": 4},
|
||||
"twinkle":{"type": "bool", "default": true},
|
||||
"shape": {"type": "choice", "options": ["star", "dot"], "default": "star"},
|
||||
"color": {"type": "color", "default": "#fff4c2"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
* `id`: 1–64 characters from `A-Z a-z 0-9 . _ -` (reverse-DNS recommended). Installing a
|
||||
module with the same id replaces the old one.
|
||||
* `name`: the menu label, 1–64 printable characters (control characters and invisible
|
||||
format characters such as bidi overrides are rejected). The app adds "…" when there are
|
||||
parameters.
|
||||
* `kind`: `"command"` (the only kind in v1).
|
||||
* `selection`: `"optional"` (default; generators) or `"required"` (selection transforms: the
|
||||
menu item is disabled without a selection and `plugin.run` refuses).
|
||||
* `params`: in dialog order, at most 32. Names are `[A-Za-z0-9_]`, 1–32 characters, not
|
||||
starting with `_`, not `id`. `label` (optional) is the dialog label; by default the name with
|
||||
underscores as spaces. Types: `number` and `int` (`min`, `max`, `default`; a slider),
|
||||
`bool` (a checkbox), `choice` (`options`, `default`; a dropdown), `color` (`"#rrggbb"`; a
|
||||
swatch).
|
||||
|
||||
## Writing a plug-in in Rust
|
||||
|
||||
[`examples/plugins`](../examples/plugins) has a small guest SDK and two complete plug-ins:
|
||||
|
||||
* **Star Field** (`star-field/`): a generator. Scatters stars of varied size, angle and
|
||||
brightness over the stage on a new layer (`layer.new`, `draw.star`,
|
||||
`element.set_transform`, `element.set_alpha`).
|
||||
* **Jitter Selection** (`jitter/`): a selection transform. Moves, turns and scales each selected
|
||||
element about its own centre (`elements`, `element.select`, `modify.transform`).
|
||||
|
||||
```rust
|
||||
use anicraft_plugin_sdk::{self as ac, Rng};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const MANIFEST: &str = r#"{"id":"org.example.dots","name":"Dots","kind":"command",
|
||||
"params":{"count":{"type":"int","min":1,"max":100,"default":10}}}"#;
|
||||
|
||||
ac::plugin!(MANIFEST, run);
|
||||
|
||||
fn run(p: &Value) -> Result<(), String> {
|
||||
let stage = &ac::document()?["stage"];
|
||||
let (w, h) = (stage["width"].as_f64().unwrap_or(550.0), stage["height"].as_f64().unwrap_or(400.0));
|
||||
let mut rng = Rng::new(1);
|
||||
for _ in 0..p["count"].as_u64().unwrap_or(10) {
|
||||
let (x, y) = (rng.unit() * w, rng.unit() * h);
|
||||
ac::command("draw.ellipse", json!({"x": x, "y": y, "w": 8, "h": 8, "stroke": null}))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Build them with `examples/plugins/build.sh` (needs `rustup target add wasm32-unknown-unknown`);
|
||||
the modules land in `examples/plugins/dist/`. `std` and `serde_json` are fine as long as nothing
|
||||
touches WASI. Plug-ins get no randomness: use a seed parameter (the SDK's `Rng`), which also
|
||||
makes every preview match the result. The only `unsafe` code a Rust plug-in needs is the two
|
||||
imports and the exports' raw pointers, all inside the SDK. Any language that compiles to core
|
||||
WebAssembly works (C, Zig, AssemblyScript, hand-written WAT; the host's tests are written in
|
||||
WAT).
|
||||
|
||||
## Performance
|
||||
|
||||
Measured on the development machine (Windows, debug build of AniCraft with optimised
|
||||
dependencies, `anicraft-cli run --sample … --plugins examples/plugins/dist`):
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Load both sample modules (72 KB and 80 KB) | under 5 ms of the CLI's ~45 ms start-up |
|
||||
| Star Field, 120 stars (361 requests, 60 M instructions for 200) | ~27 ms, fast enough for the live preview |
|
||||
| Star Field, 1,000 stars (3,001 requests) | ~230 ms |
|
||||
| Jitter Selection on one element | ~1 ms (0.8 M instructions) |
|
||||
| A busy loop in the interpreter | ~470 M instructions/s (20 M in 43 ms) |
|
||||
|
||||
A request costs about 75 µs here: most of it is the command itself plus the plug-in parsing
|
||||
and writing JSON. Generators that create thousands of elements should expect a fraction of a
|
||||
second per run.
|
||||
|
||||
## Not in v1
|
||||
|
||||
* Frame scripts, exporters and easing plug-ins (reserved above), panels and other UI plug-ins.
|
||||
* Runs on a background thread with progress and cancel: a run blocks the app for at most its
|
||||
time budget (5 s).
|
||||
* A compact binary view of large documents (v1 answers JSON only), and requests that edit a
|
||||
path's points directly by data (today: `path.*` commands, or redraw with `draw.path`).
|
||||
* Signing, a plug-in catalogue, and per-plug-in permissions beyond the fixed policy above.
|
||||
@@ -100,5 +100,5 @@ Priority: **P0** = M0–M2 skeleton must have, **P1** = parity core, **P2** = lo
|
||||
| Id | Question | Current decision (until settled) |
|
||||
|---|---|---|
|
||||
| U1 | Which interchange format first? | Own `.anicraft` + PNG/GIF first (headless verification needs it), then **XFL import** (migration path for existing projects), then Lottie/SVG export. Chosen by the builder in auto mode. |
|
||||
| U2 | Scripting surface replacing ActionScript/JSFL? | **Settled by the project lead: use the sibling apps' plug-in system.** As in PhotoCraft (`docs/plugins.md` there): sandboxed WebAssembly plug-ins run by `wasmi` (pure Rust, MIT OR Apache-2.0, works in the web build), with no host imports, fuel/memory/time limits, `plugin.install/list/run/remove/reload` commands, and one undo step per run. AniCraft's ABI targets vector/timeline work (shape generators, selection transforms, easing presets, exporters) and calls the same command registry. Commands-only scripting (CLI/JSON-lines) stays available. **ActionScript** (asked for by the project lead, low priority) is a compatibility front end on top, not a second engine: ADR 0013. |
|
||||
| U2 | Scripting surface replacing ActionScript/JSFL? | **Settled by the project lead: use the sibling apps' plug-in system.** As in PhotoCraft (`docs/plugins.md` there): sandboxed WebAssembly plug-ins run by `wasmi` (pure Rust, MIT OR Apache-2.0, works in the web build), with no host imports, fuel/memory/time limits, `plugin.install/list/run/remove/reload` commands, and one undo step per run. AniCraft's ABI targets vector/timeline work (shape generators, selection transforms, easing presets, exporters) and calls the same command registry. Commands-only scripting (CLI/JSON-lines) stays available. **ActionScript** (asked for by the project lead, low priority) is a compatibility front end on top, not a second engine: ADR 0013. **Built (first slice, ADR 0017, `docs/plugins.md`)**: command plug-ins that call the registry through a two-import JSON ABI. |
|
||||
| U3 | When does the GPU renderer become primary on stage? | CPU oracle drives the stage until the GPU renderer passes golden parity tests (M3). |
|
||||
@@ -4,18 +4,19 @@ Principle: **infrastructure first, then high-traffic parity, then the long tail.
|
||||
milestone ends with a green tree: build, tests, clippy, a `--screenshot` check and an updated
|
||||
"Honest status" section below.
|
||||
|
||||
## Honest status (2026-11-05, v0.1.0 early alpha)
|
||||
## Honest status (2026-11-09, v0.1.0 early alpha)
|
||||
|
||||
| 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 `<g opacity>`. **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, 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). **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. Headless: `timeline.create_motion_tween`, `motion.*`. Not yet: motion paths on the stage, retiming keys, rescaling keys with the span, XFL motion-tween 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), **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. |
|
||||
| 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 `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Not yet: frame scripts, exporter and easing kinds, background runs with cancel, a binary document view. |
|
||||
| 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; frame scripts are counted in the import report but not kept yet (ADR 0013); **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). |
|
||||
| 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. **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). No per-character styles, motion tweens or shape hints from XFL yet; frame scripts are counted in the import report but not kept yet (ADR 0013); **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). |
|
||||
| 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. 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. |
|
||||
| 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. **Preferences** window: interface and data fonts (bundled default or any installed font), interface scale, 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. |
|
||||
| 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). |
|
||||
@@ -26,19 +27,38 @@ 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~~ ✅ (basic); ~~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 still to do); motion tween + Motion Editor curves; ~~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 still to do); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; motion paths on stage, 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 | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. |
|
||||
| **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); ~~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, mixed directions through the Unicode bidi algorithm, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅ and ~~blend modes~~ ✅ on Movie Clips (bevel and gradient filters later). |
|
||||
| **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); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; 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, Actions panel, `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; HTML canvas runtime export; button states in test-movie preview; 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, Actions panel, `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; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. |
|
||||
| **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; crash-recovery autosave; documentation book. |
|
||||
| **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. |
|
||||
|
||||
## Releases
|
||||
|
||||
**v0.1.0 (early alpha)** marks M0 + M1 complete (see `CHANGELOG.md`). `main` starts with
|
||||
that one commit; publishing it follows the checklist in `docs/release.md`.
|
||||
|
||||
## Parallel tracks (from 2026-11-09)
|
||||
|
||||
Milestones whose next task needs no unfinished work from another milestone run at the same time,
|
||||
one agent per track (AGENTS.md › Milestone tracks). Each task is still its own PR to `main`,
|
||||
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 renderer, first slice, behind a feature flag with parity tests | CPU oracle, tiled stage |
|
||||
| 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); next: frame scripts and Test Movie on the plug-in host | command registry, plug-in host |
|
||||
| M7 | Variable-width strokes | strokes, Pen and Pencil |
|
||||
| M8 | Crash-recovery autosave | `.anicraft` format, session |
|
||||
|
||||
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); GPU as the default stage (on M3's parity).
|
||||
|
||||
## Current focus (after M0 + scale foundations)
|
||||
|
||||
The person confirmed that opening Animate files (XFL) is the first interchange priority. The
|
||||
@@ -55,7 +75,8 @@ has a key (P is the Pen, as in Animate).
|
||||
Next, in order:
|
||||
|
||||
1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, ~~shape tweens~~ ✅,
|
||||
~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), motion tweens, text (with M5), and a larger self-authored
|
||||
~~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
|
||||
corpus checked by render tests.
|
||||
2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅. Next for SVG: text, clip paths and masks (onto mask layers), dashes.
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-plugin-jitter"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"anicraft-plugin-sdk",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-plugin-sdk"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-plugin-star-field"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"anicraft-plugin-sdk",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,23 @@
|
||||
# Sample AniCraft plug-ins (docs/plugins.md). Not part of the AniCraft workspace: they build for
|
||||
# wasm32-unknown-unknown only. Build with ./build.sh.
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["sdk", "star-field", "jitter"]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.0.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
anicraft-plugin-sdk = { path = "sdk" }
|
||||
serde_json = "1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
# A panic traps (`unreachable`); the host reports it and undoes the run.
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# Builds the sample plug-ins to WebAssembly (docs/plugins.md) and copies them to ./dist.
|
||||
# Needs the wasm32-unknown-unknown target: `rustup target add wasm32-unknown-unknown`.
|
||||
# Install one with Commands › Install Plug-in…, or try them headless:
|
||||
# anicraft-cli exec --sample plugin.reload '{"folder": "examples/plugins/dist"}'
|
||||
set -eu
|
||||
cd "$(dirname "$0")"
|
||||
cargo build --release --target wasm32-unknown-unknown
|
||||
out="${CARGO_TARGET_DIR:-target}/wasm32-unknown-unknown/release"
|
||||
mkdir -p dist
|
||||
for name in star_field jitter; do
|
||||
cp "$out/anicraft_plugin_$name.wasm" "dist/$name.wasm"
|
||||
echo "dist/$name.wasm: $(wc -c < "dist/$name.wasm") bytes"
|
||||
done
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "anicraft-plugin-jitter"
|
||||
description = "Sample AniCraft plug-in: moves, turns and scales each selected element by a random amount"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
anicraft-plugin-sdk.workspace = true
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Jitter Selection: moves, turns and scales each selected element by its own random amount,
|
||||
//! about its own centre, for a hand-placed look. A selection transform: it needs a selection,
|
||||
//! and leaves the same elements selected.
|
||||
|
||||
use anicraft_plugin_sdk::{self as ac, Rng};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const MANIFEST: &str = r##"{
|
||||
"id": "org.anicraft.jitter",
|
||||
"name": "Jitter Selection",
|
||||
"version": "1.0.0",
|
||||
"kind": "command",
|
||||
"author": "AniCraft contributors",
|
||||
"description": "Moves, turns and scales each selected element by a random amount.",
|
||||
"selection": "required",
|
||||
"params": {
|
||||
"move": {"type": "number", "min": 0, "max": 200, "default": 12, "label": "Move (px)"},
|
||||
"rotate": {"type": "number", "min": 0, "max": 180, "default": 15, "label": "Turn (°)"},
|
||||
"scale": {"type": "number", "min": 0, "max": 90, "default": 10, "label": "Scale (%)"},
|
||||
"seed": {"type": "int", "min": 0, "max": 99999, "default": 1, "label": "Seed"}
|
||||
}
|
||||
}"##;
|
||||
|
||||
ac::plugin!(MANIFEST, run);
|
||||
|
||||
fn run(p: &Value) -> Result<(), String> {
|
||||
let (mv, rot, sc) = (p["move"].as_f64().unwrap_or(12.0), p["rotate"].as_f64().unwrap_or(15.0), p["scale"].as_f64().unwrap_or(10.0) / 100.0);
|
||||
let mut rng = Rng::new(p["seed"].as_u64().unwrap_or(1));
|
||||
let elements = ac::selected_elements(false)?;
|
||||
let ids: Vec<u64> = elements.iter().filter_map(|e| e["id"].as_u64()).collect();
|
||||
for e in &elements {
|
||||
let (Some(id), Some(b)) = (e["id"].as_u64(), e["bounds"].as_array()) else { continue };
|
||||
let f = |i: usize| b.get(i).and_then(Value::as_f64).unwrap_or(0.0);
|
||||
let (cx, cy) = (f(0) + f(2) * 0.5, f(1) + f(3) * 0.5);
|
||||
let (dx, dy) = (rng.signed() * mv, rng.signed() * mv);
|
||||
let angle = (rng.signed() * rot).to_radians();
|
||||
let k = 1.0 + rng.signed() * sc;
|
||||
// T(centre + offset) · R(angle) · S(k) · T(-centre), in stage space.
|
||||
let (s, c) = angle.sin_cos();
|
||||
let (a, b2, c2, d) = (c * k, s * k, -s * k, c * k);
|
||||
let (e2, f2) = (cx + dx - (a * cx + c2 * cy), cy + dy - (b2 * cx + d * cy));
|
||||
ac::command("element.select", json!({"ids": [id]}))?;
|
||||
ac::command("modify.transform", json!({"a": a, "b": b2, "c": c2, "d": d, "e": e2, "f": f2}))?;
|
||||
}
|
||||
ac::command("element.select", json!({"ids": ids}))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "anicraft-plugin-sdk"
|
||||
description = "Guest-side helpers for AniCraft WebAssembly plug-ins (ABI v1)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Guest-side helpers for AniCraft WebAssembly plug-ins (ABI v1, `docs/plugins.md`).
|
||||
//!
|
||||
//! A plug-in names its manifest and its `run` function with [`plugin!`] and talks to AniCraft
|
||||
//! with [`command`], [`document`], [`selected_elements`] and [`log`]. The only `unsafe` a
|
||||
//! plug-in needs is here: the two host imports and the raw pointers the exports receive.
|
||||
//! Everything else is plain Rust; `std` is fine as long as nothing touches WASI (files, clock,
|
||||
//! randomness), since AniCraft refuses modules with any other import.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[link(wasm_import_module = "anicraft")]
|
||||
unsafe extern "C" {
|
||||
/// Sends `len` bytes of JSON at `ptr`; returns the length of the response.
|
||||
#[link_name = "call"]
|
||||
fn host_call(ptr: *const u8, len: usize) -> i32;
|
||||
/// Copies up to `cap` bytes of the last response to `ptr`; returns the bytes copied.
|
||||
#[link_name = "response"]
|
||||
fn host_response(ptr: *mut u8, cap: usize) -> i32;
|
||||
}
|
||||
|
||||
/// Sends one request (`{"op": …}`) and returns its result, or the host's error message.
|
||||
pub fn request(req: &Value) -> Result<Value, String> {
|
||||
let bytes = serde_json::to_vec(req).map_err(|e| e.to_string())?;
|
||||
// SAFETY: the host reads `bytes.len()` bytes at `bytes.as_ptr()`, which `bytes` owns
|
||||
// for the whole call.
|
||||
let n = unsafe { host_call(bytes.as_ptr(), bytes.len()) };
|
||||
let mut buf = vec![0u8; n.max(0) as usize];
|
||||
// SAFETY: the host writes at most `buf.len()` bytes into `buf`.
|
||||
let got = unsafe { host_response(buf.as_mut_ptr(), buf.len()) };
|
||||
buf.truncate(got.max(0) as usize);
|
||||
let v: Value = serde_json::from_slice(&buf).map_err(|e| format!("unreadable response: {e}"))?;
|
||||
if v["ok"] == true { Ok(v["result"].clone()) } else { Err(v["error"].as_str().unwrap_or("the host refused the request").to_string()) }
|
||||
}
|
||||
|
||||
/// Runs an AniCraft command by id (`draw.star`, `element.translate`, …; see
|
||||
/// `anicraft-cli commands`).
|
||||
pub fn command(id: &str, params: Value) -> Result<Value, String> {
|
||||
request(&json!({"op": "command", "id": id, "params": params})).map_err(|e| format!("{id}: {e}"))
|
||||
}
|
||||
|
||||
/// The compact document view: stage, scene, frame, layers and the selection.
|
||||
pub fn document() -> Result<Value, String> {
|
||||
request(&json!({"op": "document"}))
|
||||
}
|
||||
|
||||
/// The selected elements on the active layer at the playhead (ids, kinds, stage bounds,
|
||||
/// transforms; with `paths`, shape outlines as SVG path data).
|
||||
pub fn selected_elements(paths: bool) -> Result<Vec<Value>, String> {
|
||||
let v = request(&json!({"op": "elements", "selected": true, "paths": paths}))?;
|
||||
Ok(v["elements"].as_array().cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// A line in the run's report (and the error message if the run fails).
|
||||
pub fn log(message: &str) {
|
||||
let _ = request(&json!({"op": "log", "message": message}));
|
||||
}
|
||||
|
||||
/// A small deterministic random generator (SplitMix64). Plug-ins have no source of
|
||||
/// randomness, by design: a seed parameter makes every run, and every preview, repeatable.
|
||||
pub struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
pub fn new(seed: u64) -> Rng {
|
||||
Rng(seed ^ 0x9e37_79b9_7f4a_7c15)
|
||||
}
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
/// Uniform in `0..1`.
|
||||
pub fn unit(&mut self) -> f64 {
|
||||
(self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
/// Uniform in `-1..1`.
|
||||
pub fn signed(&mut self) -> f64 {
|
||||
self.unit() * 2.0 - 1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports the ABI v1 entry points for a plug-in: `plugin!(MANIFEST, run)` where `MANIFEST`
|
||||
/// is the manifest JSON and `run: fn(&serde_json::Value) -> Result<(), String>` gets the
|
||||
/// validated parameters.
|
||||
#[macro_export]
|
||||
macro_rules! plugin {
|
||||
($manifest:expr, $run:path) => {
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn ac_abi_version() -> i32 {
|
||||
1
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn ac_manifest() -> i64 {
|
||||
$crate::manifest_ptr($manifest)
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn ac_alloc(size: i32) -> i32 {
|
||||
$crate::alloc(size)
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn ac_run(ptr: i32, len: i32) -> i32 {
|
||||
$crate::run(ptr, len, $run)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn manifest_ptr(m: &'static str) -> i64 {
|
||||
((m.len() as i64) << 32) | (m.as_ptr() as usize as i64)
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn alloc(size: i32) -> i32 {
|
||||
// A fresh instance runs once and is dropped, so the block is never freed.
|
||||
let mut v = std::mem::ManuallyDrop::new(Vec::<u8>::with_capacity(size.max(1) as usize));
|
||||
v.as_mut_ptr() as usize as i32
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn run(ptr: i32, len: i32, f: fn(&Value) -> Result<(), String>) -> i32 {
|
||||
// SAFETY: the host wrote `len` bytes of parameters into the block it got from `ac_alloc`.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(ptr as usize as *const u8, len.max(0) as usize) };
|
||||
let params: Value = serde_json::from_slice(bytes).unwrap_or(Value::Null);
|
||||
match f(¶ms) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
log(&e);
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "anicraft-plugin-star-field"
|
||||
description = "Sample AniCraft plug-in: scatters stars over the stage on a new layer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
anicraft-plugin-sdk.workspace = true
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Star Field: scatters stars of varied size, angle and brightness over the stage, on a new
|
||||
//! layer by default. A generator: it needs no selection. The seed makes it repeatable.
|
||||
|
||||
use anicraft_plugin_sdk::{self as ac, Rng};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const MANIFEST: &str = r##"{
|
||||
"id": "org.anicraft.star-field",
|
||||
"name": "Star Field",
|
||||
"version": "1.0.0",
|
||||
"kind": "command",
|
||||
"author": "AniCraft contributors",
|
||||
"description": "Scatters stars of varied size, angle and brightness over the stage.",
|
||||
"params": {
|
||||
"count": {"type": "int", "min": 1, "max": 1000, "default": 120, "label": "Stars"},
|
||||
"size_min": {"type": "number", "min": 1, "max": 100, "default": 2, "label": "Smallest (px)"},
|
||||
"size_max": {"type": "number", "min": 1, "max": 200, "default": 9, "label": "Largest (px)"},
|
||||
"points": {"type": "int", "min": 3, "max": 12, "default": 5, "label": "Points"},
|
||||
"color": {"type": "color", "default": "#fff4c2", "label": "Colour"},
|
||||
"seed": {"type": "int", "min": 0, "max": 99999, "default": 7, "label": "Seed"},
|
||||
"new_layer": {"type": "bool", "default": true, "label": "On a new layer"}
|
||||
}
|
||||
}"##;
|
||||
|
||||
ac::plugin!(MANIFEST, run);
|
||||
|
||||
fn run(p: &Value) -> Result<(), String> {
|
||||
let doc = ac::document()?;
|
||||
let (w, h) = (doc["stage"]["width"].as_f64().unwrap_or(550.0), doc["stage"]["height"].as_f64().unwrap_or(400.0));
|
||||
let count = p["count"].as_u64().unwrap_or(120);
|
||||
let (a, b) = (p["size_min"].as_f64().unwrap_or(2.0), p["size_max"].as_f64().unwrap_or(9.0));
|
||||
let (small, large) = (a.min(b), a.max(b));
|
||||
let points = p["points"].as_u64().unwrap_or(5);
|
||||
let color = p["color"].as_str().unwrap_or("#fff4c2");
|
||||
let mut rng = Rng::new(p["seed"].as_u64().unwrap_or(7));
|
||||
if p["new_layer"].as_bool().unwrap_or(true) {
|
||||
ac::command("layer.new", json!({"name": "Star Field"}))?;
|
||||
}
|
||||
for _ in 0..count {
|
||||
// Many small stars, few large ones.
|
||||
let t = rng.unit();
|
||||
let outer = small + (large - small) * t * t * t;
|
||||
let star = json!({
|
||||
"cx": rng.unit() * w, "cy": rng.unit() * h,
|
||||
"outer": outer, "inner": outer * (0.38 + 0.12 * rng.unit()),
|
||||
"points": points, "fill": color, "stroke": null,
|
||||
});
|
||||
ac::command("draw.star", star)?;
|
||||
// The new star is selected: turn it and dim it a little.
|
||||
ac::command("element.set_transform", json!({"rotation": rng.unit() * 360.0 / points as f64}))?;
|
||||
ac::command("element.set_alpha", json!({"alpha": 0.45 + 0.55 * rng.unit()}))?;
|
||||
}
|
||||
ac::command("edit.deselect", json!({}))?;
|
||||
ac::log(&format!("{count} stars"));
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerate every app icon file from assets/app-icon/anicraft.svg (the canonical artwork).
|
||||
#
|
||||
# Needs: resvg (cargo install resvg) and Python with Pillow (for the .ico). The outputs are
|
||||
# committed, so building never needs these tools.
|
||||
#
|
||||
# scripts/icons.sh
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
DIR="$ROOT/assets/app-icon"
|
||||
SVG="$DIR/anicraft.svg"
|
||||
ID="ai.storyteller.anicraft"
|
||||
TMP="$(mktemp -d)"
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
|
||||
command -v resvg >/dev/null || { echo "error: resvg not found (cargo install resvg)" >&2; exit 1; }
|
||||
|
||||
# The SVG is a full-bleed 512 tile, used as-is on Windows and Linux. macOS icons follow Apple's grid:
|
||||
# the tile is 824/1024 of the canvas with a transparent margin, so widen the viewBox around it.
|
||||
MAC="$TMP/mac.svg"
|
||||
sed 's/viewBox="0 0 512 512"/viewBox="-62.136 -62.136 636.272 636.272"/' "$SVG" >"$MAC"
|
||||
grep -q 'viewBox="-62.136' "$MAC" || { echo "error: $SVG has no 512 viewBox" >&2; exit 1; }
|
||||
|
||||
render() { resvg -w "$2" -h "$2" "$1" "$3" </dev/null; }
|
||||
|
||||
render "$SVG" 1024 "$DIR/anicraft-1024.png"
|
||||
# The tile on Apple's grid: the runtime Dock icon (src/main.rs) and store/landing pages.
|
||||
render "$MAC" 1024 "$DIR/anicraft-padded-1024.png"
|
||||
render "$MAC" 512 "$DIR/anicraft-macos-512.png"
|
||||
|
||||
# Linux hicolor theme (the 256 one is also the runtime icon on Windows and Linux, the 128 one
|
||||
# the mark in Help › About).
|
||||
for s in 16 24 32 48 64 128 256 512; do
|
||||
mkdir -p "$DIR/hicolor/${s}x${s}/apps"
|
||||
render "$SVG" "$s" "$DIR/hicolor/${s}x${s}/apps/$ID.png"
|
||||
done
|
||||
mkdir -p "$DIR/hicolor/scalable/apps"
|
||||
cp "$DIR/anicraft-small.svg" "$DIR/hicolor/scalable/apps/$ID.svg"
|
||||
|
||||
# Windows .ico (embedded in anicraft.exe by build.rs): each size rendered, not scaled down.
|
||||
ICO_SIZES=(16 20 24 32 40 48 64 128 256)
|
||||
for s in "${ICO_SIZES[@]}"; do render "$SVG" "$s" "$TMP/ico-$s.png"; done
|
||||
python - "$DIR/anicraft.ico" "$TMP" "${ICO_SIZES[@]}" <<'EOF'
|
||||
import sys
|
||||
from PIL import Image
|
||||
out, tmp, sizes = sys.argv[1], sys.argv[2], [int(s) for s in sys.argv[3:]]
|
||||
imgs = [Image.open(f"{tmp}/ico-{s}.png").convert("RGBA") for s in sizes]
|
||||
imgs[-1].save(out, format="ICO", sizes=[(s, s) for s in sizes], append_images=imgs[:-1])
|
||||
EOF
|
||||
echo "icons written to $DIR"
|
||||
@@ -2,7 +2,7 @@
|
||||
//! `Session::execute`, so everything here is also reachable headless.
|
||||
|
||||
use crate::theme::{self, T};
|
||||
use crate::{dialogs, keymap, menus, panels, pathtools, platform, prefs, stage, timeline};
|
||||
use crate::{autosave, dialogs, keymap, menus, motion_editor, panels, pathtools, platform, prefs, stage, timeline};
|
||||
use std::collections::HashSet;
|
||||
use anicraft_engine::{Session, commands};
|
||||
use egui::{Key, Modifiers};
|
||||
@@ -118,6 +118,14 @@ impl Tool {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the timeline dock shows: the timeline, or the Motion Editor beside it (as in Animate).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum BottomTab {
|
||||
#[default]
|
||||
Timeline,
|
||||
MotionEditor,
|
||||
}
|
||||
|
||||
/// Text being typed on the stage (view state until it is committed as one command).
|
||||
pub struct TextEditing {
|
||||
/// Top-left of the text box, in stage space.
|
||||
@@ -247,6 +255,13 @@ pub struct App {
|
||||
/// Selected frames on the timeline, and the drag on the frame grid.
|
||||
pub frame_sel: Option<timeline::FrameSel>,
|
||||
pub tl_drag: timeline::TlDrag,
|
||||
/// Timeline or Motion Editor, and the Motion Editor's view state: the property whose curve
|
||||
/// it shows, the picked key (frames into the span), its drag and its list scroll.
|
||||
pub bottom: BottomTab,
|
||||
pub me_prop: anicraft_engine::doc::Property,
|
||||
pub me_key: Option<u32>,
|
||||
pub me_drag: Option<motion_editor::MeDrag>,
|
||||
pub me_vscroll: f32,
|
||||
/// 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).
|
||||
@@ -254,6 +269,10 @@ pub struct App {
|
||||
/// Undoable-tier confirmations the user chose not to see again this session.
|
||||
pub skip_confirm: HashSet<String>,
|
||||
pub palette: Option<dialogs::Palette>,
|
||||
/// The open plug-in dialog (its preview is an open gesture).
|
||||
pub plugin_dialog: Option<crate::plugins_ui::Dialog>,
|
||||
/// Commands › Manage Plug-ins.
|
||||
pub show_plugins: bool,
|
||||
pub show_shortcuts: bool,
|
||||
/// The window close was intercepted because of unsaved changes.
|
||||
pub close_dialog: bool,
|
||||
@@ -275,6 +294,8 @@ pub struct App {
|
||||
shortcuts: Vec<(Modifiers, Key, &'static str)>,
|
||||
/// The shortcut editor is waiting for a key press: global shortcuts pause.
|
||||
pub key_capture: Option<dialogs::KeyCapture>,
|
||||
/// Crash-recovery autosave and the copies earlier sessions left behind (ADR 0015).
|
||||
pub recovery: autosave::Recovery,
|
||||
}
|
||||
|
||||
/// How finished this version is, shown next to the version number (docs/release.md).
|
||||
@@ -298,6 +319,7 @@ impl App {
|
||||
let keymap = keymap::Keymap::new(&prefs.shortcuts);
|
||||
let shortcuts = keymap.table();
|
||||
let library_sel = LibraryItem::first(&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.
|
||||
anicraft_engine::text::Fonts::register(crate::theme::embedded_fonts());
|
||||
@@ -339,10 +361,17 @@ impl App {
|
||||
points: Vec::new(),
|
||||
frame_sel: None,
|
||||
tl_drag: timeline::TlDrag::None,
|
||||
bottom: BottomTab::Timeline,
|
||||
me_prop: anicraft_engine::doc::Property::X,
|
||||
me_key: None,
|
||||
me_drag: None,
|
||||
me_vscroll: 0.0,
|
||||
timeline_focus: false,
|
||||
confirm: None,
|
||||
skip_confirm: HashSet::new(),
|
||||
palette: None,
|
||||
plugin_dialog: None,
|
||||
show_plugins: false,
|
||||
show_shortcuts: false,
|
||||
close_dialog: false,
|
||||
allow_close: false,
|
||||
@@ -357,9 +386,14 @@ impl App {
|
||||
keymap,
|
||||
shortcuts,
|
||||
key_capture: None,
|
||||
recovery,
|
||||
};
|
||||
app.apply_prefs(&cc.egui_ctx);
|
||||
app.status_ok("Welcome to AniCraft. Press Enter to play the sample animation.");
|
||||
if let Some(e) = recovery_err {
|
||||
app.status_err(e);
|
||||
}
|
||||
crate::plugins_ui::load_at_start(&mut app);
|
||||
app
|
||||
}
|
||||
|
||||
@@ -475,7 +509,16 @@ impl App {
|
||||
self.run("scene.select", json!({"scene": last}));
|
||||
}
|
||||
Some("files") => self.show_files = true,
|
||||
Some("recovery") => {
|
||||
// Work left behind by a session that didn't close cleanly (sample entries
|
||||
// unless ANICRAFT_RECOVERY_DIR holds real ones).
|
||||
if self.recovery.found.is_empty() {
|
||||
self.recovery.found = autosave::sample_entries();
|
||||
}
|
||||
self.recovery.show = true;
|
||||
}
|
||||
Some("licenses") => self.show_licenses = true,
|
||||
Some("about") => self.show_about = true,
|
||||
Some("zoom") => {
|
||||
// 300% on the ball: many tiles, edges cross shapes (seam check).
|
||||
self.view.fit = false;
|
||||
@@ -487,6 +530,14 @@ impl App {
|
||||
self.scan_system_fonts();
|
||||
}
|
||||
Some("confirm") => self.request("layer.delete", json!({})),
|
||||
Some("plugins") => {
|
||||
// The first generator's dialog, previewing (run with ANICRAFT_PLUGINS set).
|
||||
let first = self.s.plugins.list().find(|p| !p.manifest().params.is_empty() && p.manifest().selection == anicraft_engine::plugins::SelectionNeed::Optional).map(|p| p.id().to_string());
|
||||
match first {
|
||||
Some(id) => crate::plugins_ui::open(self, &id),
|
||||
None => self.show_plugins = true,
|
||||
}
|
||||
}
|
||||
Some("select") => {
|
||||
// The top layer's artwork selected, for its Properties.
|
||||
self.run("layer.select", json!({"index": 0}));
|
||||
@@ -552,6 +603,29 @@ impl App {
|
||||
self.tl_drag = timeline::TlDrag::Span { layer: l.id, start: k.start, end: k.end(), to: k.end() + 6 };
|
||||
}
|
||||
}
|
||||
Some(which @ ("motion" | "motionspan")) => {
|
||||
// The Star layer's span as a motion tween: it moves, turns and fades out, with
|
||||
// an eased X and a custom Bezier on Y, shown in the Motion Editor.
|
||||
self.run("layer.select", json!({"index": 1}));
|
||||
if self.run("timeline.create_motion_tween", json!({"frame": 0})).is_some() {
|
||||
let frames = self.s.active_layer().and_then(|l| l.keyframes.first()).map_or(24, |k| k.duration);
|
||||
let (mid, end) = (frames / 2, frames.saturating_sub(1));
|
||||
let x0 = self.run("motion.info", json!({"frame": 0})).and_then(|v| v["values"]["x"].as_f64()).unwrap_or(0.0);
|
||||
let y0 = self.run("motion.info", json!({"frame": 0})).and_then(|v| v["values"]["y"].as_f64()).unwrap_or(0.0);
|
||||
for (p, f, v) in [("x", mid, x0 + 260.0), ("x", end, x0 + 420.0), ("y", mid, y0 + 160.0), ("y", end, y0), ("rotation", end, 270.0), ("alpha", end, 20.0)] {
|
||||
self.run("motion.set_key", json!({"property": p, "frame": f, "value": v}));
|
||||
}
|
||||
self.run("motion.set_ease", json!({"property": "x", "frame": 1, "easing": "CubicOut"}));
|
||||
self.run("motion.set_ease", json!({"property": "y", "frame": 1, "easing": {"bezier": [0.2, 1.6, 0.6, 1.0]}}));
|
||||
self.s.mark_saved();
|
||||
}
|
||||
if which == "motion" {
|
||||
self.bottom = BottomTab::MotionEditor;
|
||||
}
|
||||
self.me_prop = anicraft_engine::doc::Property::Y;
|
||||
self.me_key = Some(0);
|
||||
self.run("timeline.goto", json!({"frame": 6}));
|
||||
}
|
||||
Some("pen") => {
|
||||
// A pen path still being drawn: a corner, a smooth point with handles, a corner.
|
||||
self.tool = Tool::Pen;
|
||||
@@ -567,7 +641,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.prompt.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
|
||||
@@ -598,6 +672,22 @@ impl App {
|
||||
None => self.status_ok(if id == "file.open" { "Opened" } else { "New document" }),
|
||||
}
|
||||
}
|
||||
"file.recover" => {
|
||||
self.view.fit = true;
|
||||
self.frame_sel = None;
|
||||
self.library_sel = LibraryItem::first(&self.s.doc);
|
||||
self.recovery.restored(v["recovered"].as_str().unwrap_or(""));
|
||||
let name = v["name"].as_str().unwrap_or("Untitled");
|
||||
self.status_ok(if v["original_newer"].as_bool() == Some(true) {
|
||||
format!("Restored “{name}” as a new document (the file on disk is newer). Save to keep it.")
|
||||
} else {
|
||||
format!("Restored “{name}”. It isn't saved yet: Save to keep it.")
|
||||
});
|
||||
}
|
||||
"file.discard_recovery" => {
|
||||
self.recovery.discarded(v["discarded"].as_str().unwrap_or(""));
|
||||
self.status_ok("Discarded the autosaved copy");
|
||||
}
|
||||
"file.save" | "file.save_as" => {
|
||||
self.status_ok(format!("Saved {}", v["saved"].as_str().unwrap_or("")));
|
||||
if self.close_after_save {
|
||||
@@ -647,6 +737,7 @@ impl App {
|
||||
_ => format!("Pasted {what} — Ctrl+Z to undo"),
|
||||
});
|
||||
}
|
||||
"plugin.run" | "plugin.install" | "plugin.remove" | "plugin.reload" => crate::plugins_ui::status(self, id, &v),
|
||||
"timeline.remove_frame" => {
|
||||
let n = v["removed"].as_u64().unwrap_or(1);
|
||||
self.status_ok(format!("Removed {} — Ctrl+Z to undo", if n == 1 { "frame".to_string() } else { format!("{n} frames") }));
|
||||
@@ -673,6 +764,19 @@ impl App {
|
||||
self.request(id, p);
|
||||
return;
|
||||
}
|
||||
if id == "file.recovery_list" {
|
||||
self.recovery.rescan();
|
||||
self.recovery.show = !self.recovery.found.is_empty();
|
||||
if !self.recovery.show {
|
||||
self.status_ok(if self.recovery.active() { "No autosaved work to recover" } else { "Autosave is off on this system, so there is nothing to recover" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if id == "plugin.list" {
|
||||
// Commands › Manage Plug-ins (headless, the same command lists them).
|
||||
self.show_plugins = true;
|
||||
return;
|
||||
}
|
||||
if id == "edit.paste" {
|
||||
// Paste in the centre of what you are looking at.
|
||||
let c = self.view_center_stage();
|
||||
@@ -693,11 +797,12 @@ impl App {
|
||||
"file.export_video" => Some(("Export video (.webm or .mp4, made with your ffmpeg)", "path", "animation.webm".to_string())),
|
||||
"file.export_lottie" => Some(("Export Lottie animation (JSON, for web and apps)", "path", "animation.json".to_string())),
|
||||
"file.import" => Some(("Import to stage (SVG, PNG or JPEG)", "path", "drawing.svg".to_string())),
|
||||
"plugin.install" => Some(("Install plug-in (.wasm file)", "path", "plugin.wasm".to_string())),
|
||||
"modify.convert_to_symbol" => Some(("Convert to symbol — name", "name", format!("Symbol {}", self.s.doc.library.len() + 1))),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((title, key, text)) = prompt {
|
||||
let is_file = matches!(key, "path" | "dir") && id.starts_with("file.");
|
||||
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || id == "plugin.install");
|
||||
if is_file && self.prefs.native_dialogs && self.shot.is_none() {
|
||||
// The platform's own dialog (it blocks, as native dialogs do). Cancel = no-op.
|
||||
self.playing = false;
|
||||
@@ -943,6 +1048,7 @@ impl App {
|
||||
fn about_window(&mut self, ctx: &egui::Context) {
|
||||
let mut open = self.show_about;
|
||||
egui::Window::new("About AniCraft").open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
ui.add(egui::Image::new((app_mark(ctx).id(), egui::vec2(64.0, 64.0))));
|
||||
ui.heading("AniCraft");
|
||||
ui.label(format!("Version {} · {RELEASE_STAGE}", env!("CARGO_PKG_VERSION")));
|
||||
ui.label("Open-source 2D vector animation studio, written in Rust.");
|
||||
@@ -1001,8 +1107,24 @@ 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 {
|
||||
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::<egui::TextureHandle>(id)) {
|
||||
return tex;
|
||||
}
|
||||
let icon = eframe::icon_data::from_png_bytes(PNG).unwrap_or_default();
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied([icon.width as usize, icon.height as usize], &icon.rgba);
|
||||
let options = egui::TextureOptions { mipmap_mode: Some(egui::TextureFilter::Linear), ..egui::TextureOptions::LINEAR };
|
||||
let tex = ctx.load_texture("anicraft-app-mark", image, options);
|
||||
ctx.data_mut(|d| d.insert_temp(id, tex.clone()));
|
||||
tex
|
||||
}
|
||||
|
||||
/// Opens a file or folder with the operating system's default handler.
|
||||
fn open_in_system(path: &std::path::Path) -> Result<(), String> {
|
||||
pub(crate) fn open_in_system(path: &std::path::Path) -> Result<(), String> {
|
||||
let mut cmd = if cfg!(target_os = "windows") {
|
||||
let mut c = std::process::Command::new("explorer");
|
||||
c.arg(path);
|
||||
@@ -1020,6 +1142,13 @@ fn open_in_system(path: &std::path::Path) -> Result<(), String> {
|
||||
}
|
||||
|
||||
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>) {
|
||||
let clean = !self.s.is_dirty() || self.allow_close || self.shot.is_some();
|
||||
self.recovery.finish(&self.s, clean);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
self.handle_screenshot(&ctx);
|
||||
@@ -1058,6 +1187,8 @@ impl eframe::App for App {
|
||||
self.prompt_window(&ctx);
|
||||
self.about_window(&ctx);
|
||||
dialogs::show_all(self, &ctx);
|
||||
autosave::window(self, &ctx);
|
||||
crate::plugins_ui::show(self, &ctx);
|
||||
|
||||
// Never lose work on close: intercept it while there are unsaved changes.
|
||||
if self.allow_close {
|
||||
@@ -1074,10 +1205,14 @@ impl eframe::App for App {
|
||||
self.files_window(&ctx);
|
||||
|
||||
// Close a coalesced edit (property drags) once nothing is being dragged or typed.
|
||||
if self.s.in_gesture() && self.drag == Drag::None && !ctx.egui_is_using_pointer() && ctx.memory(|m| m.focused().is_none()) {
|
||||
// (A plug-in dialog keeps its preview gesture open until OK or Cancel.)
|
||||
if self.s.in_gesture() && self.plugin_dialog.is_none() && self.drag == Drag::None && !ctx.egui_is_using_pointer() && ctx.memory(|m| m.focused().is_none()) {
|
||||
self.s.end_gesture();
|
||||
}
|
||||
|
||||
// After this frame's edits: start a recovery copy when one is due (off this thread).
|
||||
autosave::tick(self, &ctx);
|
||||
|
||||
// An edit late in this frame (after the stage drew) must be shown without waiting for
|
||||
// the next input event: egui only repaints on demand. This was the "drag commits after a
|
||||
// pause" bug.
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::path::Path;
|
||||
|
||||
/// Each crate's layer, as AGENTS.md documents it. The shell (`anicraft`, `src/`) is L5.
|
||||
const LAYERS: &[(&str, u8)] =
|
||||
&[("geom", 0), ("xml", 0), ("doc", 1), ("text", 1), ("render", 2), ("xfl", 2), ("svg", 2), ("engine", 3), ("cli", 4)];
|
||||
&[("geom", 0), ("xml", 0), ("plugins", 0), ("doc", 1), ("text", 1), ("render", 2), ("xfl", 2), ("svg", 2), ("engine", 3), ("cli", 4)];
|
||||
const SHELL_LAYER: u8 = 5;
|
||||
/// UI crates only the shell may use.
|
||||
const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui-wgpu", "egui_glow"];
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
//! Crash recovery in the shell (ADR 0015): when to autosave, and the window that offers work a
|
||||
//! previous session left behind (Restore / Discard / Later).
|
||||
//!
|
||||
//! The engine does the work: [`Autosaver`] serializes snapshots of the persistent document on
|
||||
//! its own thread, and the `file.recover` / `file.discard_recovery` commands act on what was
|
||||
//! left behind. This module only decides *when* (Preferences: every N seconds, or after N
|
||||
//! changes, whichever comes first) and shows the choices.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::prefs::Prefs;
|
||||
use crate::theme::{T, Type, text};
|
||||
use anicraft_engine::recovery::{self, Autosaver, Entry, Outcome, SessionLock};
|
||||
use anicraft_engine::StateId;
|
||||
use egui::Color32;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Autosave state of the running app.
|
||||
#[derive(Default)]
|
||||
pub struct Recovery {
|
||||
saver: Option<Autosaver>,
|
||||
pub dir: Option<PathBuf>,
|
||||
/// Document state the newest copy holds (handed to the writer, or restored from disk).
|
||||
written: Option<StateId>,
|
||||
/// This session has a copy on disk (or one on its way).
|
||||
has_copy: bool,
|
||||
/// Revision at the last copy, to count changes since.
|
||||
rev_at_copy: u64,
|
||||
/// When the document first differed from the newest copy (app time, seconds).
|
||||
dirty_since: Option<f64>,
|
||||
/// When the newest copy was finished (app time, seconds).
|
||||
pub last_copy_at: Option<f64>,
|
||||
/// A restored copy of another session, removed once this session holds the work.
|
||||
adopt: Option<String>,
|
||||
failed: bool,
|
||||
/// Copies left by sessions that didn't close cleanly, and whether the window shows them.
|
||||
pub found: Vec<Entry>,
|
||||
pub show: bool,
|
||||
/// The session whose Discard is waiting for its second click.
|
||||
confirm_discard: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether a new copy is due: unsaved for the whole interval, or enough changes made (not in
|
||||
/// the middle of a drag, which would write a copy per frame of it).
|
||||
pub fn due(unsaved_for: f64, changes: u64, in_gesture: bool, p: &Prefs) -> bool {
|
||||
unsaved_for >= f64::from(p.autosave_secs) || (p.autosave_edits > 0 && changes >= u64::from(p.autosave_edits) && !in_gesture)
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
/// Starts this session's autosave and finds what earlier sessions left behind. Screenshot
|
||||
/// runs leave the real folder alone unless `ANICRAFT_RECOVERY_DIR` names one.
|
||||
pub fn start(shot_mode: bool) -> (Recovery, Option<String>) {
|
||||
let mut r = Recovery::default();
|
||||
if shot_mode && !crate::platform::recovery_dir_overridden() {
|
||||
return (r, None);
|
||||
}
|
||||
let Some(dir) = crate::platform::recovery_dir() else { return (r, Some("Autosave is off: this system has no settings folder".into())) };
|
||||
recovery::prune(&dir);
|
||||
r.found = recovery::scan(&dir, None);
|
||||
r.show = !r.found.is_empty();
|
||||
let err = match SessionLock::acquire(&dir).and_then(Autosaver::start) {
|
||||
Ok(s) => {
|
||||
r.saver = Some(s);
|
||||
None
|
||||
}
|
||||
Err(e) => Some(format!("Autosave is off: {e}")),
|
||||
};
|
||||
r.dir = Some(dir);
|
||||
(r, err)
|
||||
}
|
||||
|
||||
pub fn active(&self) -> bool {
|
||||
self.saver.is_some()
|
||||
}
|
||||
|
||||
/// Rescans for left-behind copies (File › Recover Autosaved Documents…).
|
||||
pub fn rescan(&mut self) {
|
||||
if let Some(dir) = &self.dir {
|
||||
let own = self.saver.as_ref().map(|s| s.id().to_string());
|
||||
self.found = recovery::scan(dir, own.as_deref());
|
||||
}
|
||||
}
|
||||
|
||||
/// A left-behind copy was restored: this session takes the work over (a copy right away),
|
||||
/// and the old copy goes once that is on disk.
|
||||
pub fn restored(&mut self, session: &str) {
|
||||
self.found.retain(|e| e.session != session);
|
||||
self.show = self.show && !self.found.is_empty();
|
||||
self.adopt = Some(session.to_string());
|
||||
self.written = None;
|
||||
self.dirty_since = Some(f64::NEG_INFINITY);
|
||||
}
|
||||
|
||||
pub fn discarded(&mut self, session: &str) {
|
||||
self.found.retain(|e| e.session != session);
|
||||
self.confirm_discard = None;
|
||||
self.show = self.show && !self.found.is_empty();
|
||||
}
|
||||
|
||||
/// Ends the session: a clean exit removes this session's copy; anything else (unsaved work
|
||||
/// the user didn't decide about) is written one last time for the next start.
|
||||
pub fn finish(&mut self, s: &anicraft_engine::Session, clean: bool) {
|
||||
if let Some(saver) = self.saver.take() {
|
||||
let keep = !clean && s.is_dirty();
|
||||
saver.finish(keep.then(|| (s.doc.clone(), s.path.clone())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per frame: collects finished copies and starts a new one when it is due.
|
||||
pub fn tick(app: &mut App, ctx: &egui::Context) {
|
||||
let now = ctx.input(|i| i.time);
|
||||
let outcomes = app.recovery.saver.as_ref().map(Autosaver::poll).unwrap_or_default();
|
||||
for o in outcomes {
|
||||
match o {
|
||||
Outcome::Written { .. } => {
|
||||
app.recovery.last_copy_at = Some(now);
|
||||
app.recovery.failed = false;
|
||||
if let (Some(old), Some(dir)) = (app.recovery.adopt.take(), app.recovery.dir.clone()) {
|
||||
// Through the command, as any front end would. The user chose Restore.
|
||||
let _ = app.s.execute("file.discard_recovery", &json!({"dir": dir.display().to_string(), "session": old, "confirm": true}));
|
||||
}
|
||||
}
|
||||
Outcome::Failed { error, .. } => {
|
||||
if !app.recovery.failed {
|
||||
app.status_err(format!("Autosave failed: {error}. Save your work to be safe; AniCraft will keep trying."));
|
||||
}
|
||||
app.recovery.failed = true;
|
||||
app.recovery.written = None;
|
||||
app.recovery.dirty_since = Some(now);
|
||||
}
|
||||
Outcome::Cleared { .. } => {}
|
||||
}
|
||||
}
|
||||
let r = &mut app.recovery;
|
||||
let Some(saver) = &mut r.saver else { return };
|
||||
if !app.prefs.autosave || !app.s.is_dirty() {
|
||||
// Nothing to protect (saved, back at the saved state, a new document) or autosave off.
|
||||
if r.has_copy {
|
||||
saver.clear();
|
||||
r.has_copy = false;
|
||||
r.last_copy_at = None;
|
||||
}
|
||||
r.written = app.prefs.autosave.then_some(app.s.state);
|
||||
r.rev_at_copy = app.s.revision;
|
||||
r.dirty_since = None;
|
||||
return;
|
||||
}
|
||||
if r.written == Some(app.s.state) {
|
||||
return;
|
||||
}
|
||||
let since = *r.dirty_since.get_or_insert(now);
|
||||
let changes = app.s.revision.saturating_sub(r.rev_at_copy);
|
||||
if due(now - since, changes, app.s.in_gesture(), &app.prefs) {
|
||||
// An `Arc` snapshot: O(1) here; serializing and writing happen on the worker.
|
||||
saver.write(app.s.doc.clone(), app.s.path.as_deref());
|
||||
r.has_copy = true;
|
||||
r.written = Some(app.s.state);
|
||||
r.rev_at_copy = app.s.revision;
|
||||
r.dirty_since = None;
|
||||
} else {
|
||||
// egui repaints on input only: wake up when the interval runs out.
|
||||
let left = (f64::from(app.prefs.autosave_secs) - (now - since)).max(0.05);
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(left));
|
||||
}
|
||||
}
|
||||
|
||||
/// "just now", "4 min ago", "2 h ago", "3 days ago".
|
||||
pub fn ago(secs: u64) -> String {
|
||||
match secs {
|
||||
0..60 => "just now".into(),
|
||||
60..3600 => format!("{} min ago", secs / 60),
|
||||
3600..86400 => format!("{} h ago", secs / 3600),
|
||||
_ => {
|
||||
let d = secs / 86400;
|
||||
if d == 1 { "yesterday".into() } else { format!("{d} days ago") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The status-bar readout: when the open work was last copied, while it is unsaved.
|
||||
pub fn status(app: &App, now: f64) -> Option<String> {
|
||||
if !app.s.is_dirty() || !app.prefs.autosave {
|
||||
return None;
|
||||
}
|
||||
let at = app.recovery.last_copy_at?;
|
||||
Some(format!("autosaved {}", ago((now - at).max(0.0) as u64)))
|
||||
}
|
||||
|
||||
/// Two made-up left-behind documents, for `--open recovery` screenshots.
|
||||
pub fn sample_entries() -> Vec<Entry> {
|
||||
let now = recovery::now_secs();
|
||||
let entry = |session: &str, name: &str, original: Option<&str>, age: u64, frames: u32, scenes: usize| Entry {
|
||||
session: session.into(),
|
||||
document: PathBuf::new(),
|
||||
meta: recovery::RecoveryMeta { name: name.into(), original: original.map(PathBuf::from), saved_at: now.saturating_sub(age), frames, scenes, ..Default::default() },
|
||||
bytes: 0,
|
||||
};
|
||||
let walk = if crate::platform::OS == crate::platform::Os::Windows { "C:\\Users\\you\\Documents\\walk-cycle.anicraft" } else { "/home/you/Documents/walk-cycle.anicraft" };
|
||||
vec![entry("sample-1", "walk-cycle.anicraft", Some(walk), 240, 48, 2), entry("sample-2", "Untitled", None, 3 * 3600, 120, 1)]
|
||||
}
|
||||
|
||||
enum Act {
|
||||
Restore(String),
|
||||
AskDiscard(String),
|
||||
Discard(String),
|
||||
KeepIt,
|
||||
Later,
|
||||
}
|
||||
|
||||
/// The Recover window: non-blocking (the editor stays usable behind it), one row per
|
||||
/// left-behind document with Restore and Discard, and Later to decide another time.
|
||||
pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
if !app.recovery.show || app.recovery.found.is_empty() {
|
||||
app.recovery.show = false;
|
||||
return;
|
||||
}
|
||||
let mut act: Option<Act> = None;
|
||||
let mut open = true;
|
||||
let now = recovery::now_secs();
|
||||
let n = app.recovery.found.len();
|
||||
let confirm = app.recovery.confirm_discard.clone();
|
||||
let btn = egui::vec2(96.0, crate::theme::TARGET + 4.0);
|
||||
egui::Window::new("Recover unsaved work")
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.pivot(egui::Align2::CENTER_CENTER)
|
||||
.default_pos(ctx.content_rect().center())
|
||||
.default_width(520.0)
|
||||
.show(ctx, |ui| {
|
||||
ui.set_width(520.0);
|
||||
let lead = if n == 1 {
|
||||
"AniCraft didn't close properly last time. This document had changes that weren't saved:"
|
||||
} else {
|
||||
"AniCraft didn't close properly last time. These documents had changes that weren't saved:"
|
||||
};
|
||||
ui.label(text(Type::Body, lead).color(T.text_dim));
|
||||
ui.add_space(8.0);
|
||||
for e in &app.recovery.found {
|
||||
egui::Frame::NONE.fill(T.panel_alt).corner_radius(T.radius_menu).inner_margin(egui::Margin::same(10)).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(text(Type::Body, e.meta.name.clone()).strong());
|
||||
let scenes = if e.meta.scenes > 1 { format!(" · {} scenes", e.meta.scenes) } else { String::new() };
|
||||
ui.label(text(Type::Caption, format!("Autosaved {} · {} frames{scenes}", ago(now.saturating_sub(e.meta.saved_at)), e.meta.frames)));
|
||||
match &e.meta.original {
|
||||
Some(o) => {
|
||||
ui.label(text(Type::Path, o.display().to_string()).color(T.text_faint));
|
||||
}
|
||||
None => {
|
||||
ui.label(text(Type::Caption, "Never saved"));
|
||||
}
|
||||
}
|
||||
if e.original_is_newer() {
|
||||
ui.label(text(Type::Caption, "The file was saved after this copy, so it opens as a new document and Save asks for a name.").color(T.error));
|
||||
}
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if confirm.as_deref() == Some(e.session.as_str()) {
|
||||
let discard = egui::Button::new(text(Type::Body, "Discard").color(Color32::WHITE).strong()).fill(T.danger).min_size(btn);
|
||||
if ui.add(discard).clicked() {
|
||||
act = Some(Act::Discard(e.session.clone()));
|
||||
}
|
||||
if ui.add(egui::Button::new("Keep").min_size(btn)).clicked() {
|
||||
act = Some(Act::KeepIt);
|
||||
}
|
||||
} else {
|
||||
let restore = egui::Button::new(text(Type::Body, "Restore").color(Color32::WHITE).strong()).fill(T.accent).min_size(btn);
|
||||
if ui.add(restore).on_hover_text("Open it as unsaved work").clicked() {
|
||||
act = Some(Act::Restore(e.session.clone()));
|
||||
}
|
||||
if ui.add(egui::Button::new("Discard…").min_size(btn)).on_hover_text("Delete this autosaved copy").clicked() {
|
||||
act = Some(Act::AskDiscard(e.session.clone()));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if confirm.as_deref() == Some(e.session.as_str()) {
|
||||
ui.label(text(Type::Caption, "Discarding deletes this work for good. This cannot be undone.").color(T.error));
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add(egui::Button::new("Later").min_size(btn)).clicked() {
|
||||
act = Some(Act::Later);
|
||||
}
|
||||
ui.label(text(Type::Caption, "Later keeps them: File › Recover Autosaved Documents… brings this back."));
|
||||
});
|
||||
});
|
||||
if !open {
|
||||
act = Some(Act::Later);
|
||||
}
|
||||
let dir = app.recovery.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default();
|
||||
match act {
|
||||
// Through `request`: restoring over unsaved changes asks first (ADR 0004).
|
||||
Some(Act::Restore(id)) => {
|
||||
app.recovery.confirm_discard = None;
|
||||
app.request("file.recover", json!({"dir": dir, "session": id}));
|
||||
}
|
||||
Some(Act::AskDiscard(id)) => app.recovery.confirm_discard = Some(id),
|
||||
// The second click on the red button is the confirmation.
|
||||
Some(Act::Discard(id)) => {
|
||||
app.perform("file.discard_recovery", json!({"dir": dir, "session": id, "confirm": true}));
|
||||
}
|
||||
Some(Act::KeepIt) => app.recovery.confirm_discard = None,
|
||||
Some(Act::Later) => {
|
||||
app.recovery.show = false;
|
||||
app.recovery.confirm_discard = None;
|
||||
app.status_ok("Kept the autosaved work. File › Recover Autosaved Documents… brings it back.");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn copies_are_due_by_time_or_by_changes() {
|
||||
let p = Prefs::default(); // 60 s or 25 changes
|
||||
assert!(!due(10.0, 3, false, &p));
|
||||
assert!(due(60.0, 1, false, &p), "never more than the interval");
|
||||
assert!(due(61.0, 1, true, &p), "even in a long gesture");
|
||||
assert!(due(5.0, 25, false, &p));
|
||||
assert!(!due(5.0, 400, true, &p), "not per frame of a drag");
|
||||
let time_only = Prefs { autosave_edits: 0, ..Prefs::default() };
|
||||
assert!(!due(5.0, 10_000, false, &time_only));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ages_read_naturally() {
|
||||
assert_eq!(ago(5), "just now");
|
||||
assert_eq!(ago(240), "4 min ago");
|
||||
assert_eq!(ago(7300), "2 h ago");
|
||||
assert_eq!(ago(90_000), "yesterday");
|
||||
assert_eq!(ago(3 * 86_400), "3 days ago");
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,8 @@ enum Entry {
|
||||
Command(CommandSpec),
|
||||
Tool(Tool),
|
||||
View(&'static str, &'static str, fn(&mut App)),
|
||||
/// An installed plug-in: `(id, menu label)`.
|
||||
Plugin(String, String),
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
@@ -176,6 +178,7 @@ impl Entry {
|
||||
}
|
||||
Entry::Tool(t) => format!("Tool › {}", t.label()),
|
||||
Entry::View(name, _, _) => format!("View › {name}"),
|
||||
Entry::Plugin(_, label) => format!("Commands › Plug-ins › {label}"),
|
||||
}
|
||||
}
|
||||
fn shortcut(&self, km: &crate::keymap::Keymap) -> String {
|
||||
@@ -183,13 +186,14 @@ impl Entry {
|
||||
Entry::Command(c) => km.primary(c.id).unwrap_or("").to_string(),
|
||||
Entry::Tool(t) => km.primary(crate::keymap::tool_id(*t)).unwrap_or("").to_string(),
|
||||
Entry::View(_, sc, _) => (*sc).to_string(),
|
||||
Entry::Plugin(..) => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands the palette can run without extra input (everything optional, or prompted).
|
||||
fn runnable(c: &CommandSpec) -> bool {
|
||||
if matches!(c.id, "file.open" | "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_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename") {
|
||||
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_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('}');
|
||||
@@ -229,7 +233,8 @@ fn fuzzy(query: &str, text: &str) -> Option<i32> {
|
||||
fn palette(app: &mut App, ctx: &egui::Context) {
|
||||
let km = &app.keymap;
|
||||
let Some(p) = &mut app.palette else { return };
|
||||
let all = entries();
|
||||
let mut all = entries();
|
||||
all.extend(app.s.plugins.list().map(|p| Entry::Plugin(p.id().to_string(), crate::plugins_ui::label(p))));
|
||||
let mut matches: Vec<(i32, Entry, String)> =
|
||||
all.into_iter().filter_map(|e| {
|
||||
let key = e.shortcut(km);
|
||||
@@ -299,6 +304,7 @@ fn palette(app: &mut App, ctx: &egui::Context) {
|
||||
Some(Entry::Command(c)) => app.invoke(c.id),
|
||||
Some(Entry::Tool(t)) => app.tool = t,
|
||||
Some(Entry::View(_, _, f)) => f(app),
|
||||
Some(Entry::Plugin(id, _)) => crate::plugins_ui::run_or_ask(app, &id),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
@@ -359,86 +365,117 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
|
||||
.default_pos(ctx.content_rect().center())
|
||||
.default_width(560.0)
|
||||
.show(ctx, |ui| {
|
||||
// A two-column form: labels in a fixed left column, controls and the notes that
|
||||
// explain them in the right one.
|
||||
use crate::theme::{FORM_LABEL_DIALOG as LW, Section, form_note, form_row, section};
|
||||
// Under a radio button or checkbox, notes line up with its text, not its box.
|
||||
// (`form_note` adds one item spacing after its indent, like a row's label column.)
|
||||
let toggle_indent = (ui.spacing().icon_width + ui.spacing().icon_spacing - ui.spacing().item_spacing.x).max(0.0);
|
||||
// Taller than small windows: the sections scroll, the footer stays.
|
||||
let max_h = (ctx.content_rect().height() - 160.0).max(200.0);
|
||||
egui::ScrollArea::vertical().max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {
|
||||
// A two-column form: labels in a fixed left column, controls and the notes that
|
||||
// explain them in the right one.
|
||||
use crate::theme::{FORM_LABEL_DIALOG as LW, Section, form_note, form_row, section};
|
||||
// Under a radio button or checkbox, notes line up with its text, not its box.
|
||||
// (`form_note` adds one item spacing after its indent, like a row's label column.)
|
||||
let toggle_indent = (ui.spacing().icon_width + ui.spacing().icon_spacing - ui.spacing().item_spacing.x).max(0.0);
|
||||
|
||||
section(ui, "prefs_appearance", Section::Rule, "Appearance", None, |ui| {
|
||||
form_row(ui, LW, "Interface font", |ui| {
|
||||
if let Some(c) = font_picker(ui, "pref_ui_font", &p.ui_font, sys.as_ref().map(|s| s.families.as_slice()), bundled_ui) {
|
||||
p.ui_font = c;
|
||||
}
|
||||
});
|
||||
form_row(ui, LW, "Data font", |ui| {
|
||||
let list = sys.as_ref().map(|s| s.monospace.as_slice());
|
||||
if let Some(c) = font_picker(ui, "pref_data_font", &p.data_font, list, bundled_mono) {
|
||||
p.data_font = c;
|
||||
}
|
||||
});
|
||||
form_note(ui, LW, text(Type::Caption, "The data font shows numbers, timecode, rulers and shortcuts; only monospaced families are listed so digits stay aligned."));
|
||||
ui.add_space(4.0);
|
||||
form_row(ui, LW, "Preview", |ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(text(Type::Body, "Layer names, menus and dialog text read like this."));
|
||||
ui.label(text(Type::Data, "Frame 0042 · 1.75 s · X 1280.5 Y 720.0 · Ctrl+Shift+S"));
|
||||
section(ui, "prefs_appearance", Section::Rule, "Appearance", None, |ui| {
|
||||
form_row(ui, LW, "Interface font", |ui| {
|
||||
if let Some(c) = font_picker(ui, "pref_ui_font", &p.ui_font, sys.as_ref().map(|s| s.families.as_slice()), bundled_ui) {
|
||||
p.ui_font = c;
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
form_row(ui, LW, "Interface scale", |ui| {
|
||||
let mut pct = p.ui_scale * 100.0;
|
||||
let r = with_type(ui, Type::Data, |ui| {
|
||||
ui.add(egui::Slider::new(&mut pct, (crate::prefs::SCALE_RANGE.start() * 100.0)..=(crate::prefs::SCALE_RANGE.end() * 100.0)).step_by(5.0).suffix(" %"))
|
||||
form_row(ui, LW, "Data font", |ui| {
|
||||
let list = sys.as_ref().map(|s| s.monospace.as_slice());
|
||||
if let Some(c) = font_picker(ui, "pref_data_font", &p.data_font, list, bundled_mono) {
|
||||
p.data_font = c;
|
||||
}
|
||||
});
|
||||
// Apply on release so the slider doesn't move under the pointer while dragging.
|
||||
if r.drag_stopped() || (r.changed() && !r.dragged()) {
|
||||
p.ui_scale = pct / 100.0;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
section(ui, "prefs_stage", Section::Rule, "Stage", None, |ui| {
|
||||
form_row(ui, LW, "Rendering", |ui| {
|
||||
ui.vertical(|ui| {
|
||||
for (mode, name, tip) in RenderMode::ALL {
|
||||
crate::theme::radio_value(ui, &mut p.render_mode, mode, text(Type::Body, name));
|
||||
form_note(ui, toggle_indent, text(Type::Caption, tip));
|
||||
ui.add_space(2.0);
|
||||
form_note(ui, LW, text(Type::Caption, "The data font shows numbers, timecode, rulers and shortcuts; only monospaced families are listed so digits stay aligned."));
|
||||
ui.add_space(4.0);
|
||||
form_row(ui, LW, "Preview", |ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(text(Type::Body, "Layer names, menus and dialog text read like this."));
|
||||
ui.label(text(Type::Data, "Frame 0042 · 1.75 s · X 1280.5 Y 720.0 · Ctrl+Shift+S"));
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
form_row(ui, LW, "Interface scale", |ui| {
|
||||
let mut pct = p.ui_scale * 100.0;
|
||||
let r = with_type(ui, Type::Data, |ui| {
|
||||
ui.add(egui::Slider::new(&mut pct, (crate::prefs::SCALE_RANGE.start() * 100.0)..=(crate::prefs::SCALE_RANGE.end() * 100.0)).step_by(5.0).suffix(" %"))
|
||||
});
|
||||
// Apply on release so the slider doesn't move under the pointer while dragging.
|
||||
if r.drag_stopped() || (r.changed() && !r.dragged()) {
|
||||
p.ui_scale = pct / 100.0;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
section(ui, "prefs_timeline", Section::Rule, "Timeline", None, |ui| {
|
||||
form_row(ui, LW, "Extra start gap", |ui| {
|
||||
with_type(ui, Type::Data, |ui| {
|
||||
ui.add(egui::DragValue::new(&mut p.timeline_start_gap).range(crate::prefs::GAP_RANGE).speed(0.5).max_decimals(0).suffix(" pt"));
|
||||
section(ui, "prefs_stage", Section::Rule, "Stage", None, |ui| {
|
||||
form_row(ui, LW, "Rendering", |ui| {
|
||||
ui.vertical(|ui| {
|
||||
for (mode, name, tip) in RenderMode::ALL {
|
||||
crate::theme::radio_value(ui, &mut p.render_mode, mode, text(Type::Body, name));
|
||||
form_note(ui, toggle_indent, text(Type::Caption, tip));
|
||||
ui.add_space(2.0);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
form_note(ui, LW, text(Type::Caption, "The timeline always leaves room before frame 1 for the playhead; this adds more. It stays the same at every zoom."));
|
||||
});
|
||||
|
||||
section(ui, "prefs_files", Section::Rule, "Files", None, |ui| {
|
||||
form_row(ui, LW, "File dialogs", |ui| {
|
||||
ui.vertical(|ui| {
|
||||
crate::theme::checkbox(ui, &mut p.native_dialogs, text(Type::Body, "Use the system's open and save dialogs"));
|
||||
form_note(ui, toggle_indent, text(Type::Caption, "Turn off on Linux desktops without an XDG desktop portal; AniCraft then asks for a path instead."));
|
||||
section(ui, "prefs_timeline", Section::Rule, "Timeline", None, |ui| {
|
||||
form_row(ui, LW, "Extra start gap", |ui| {
|
||||
with_type(ui, Type::Data, |ui| {
|
||||
ui.add(egui::DragValue::new(&mut p.timeline_start_gap).range(crate::prefs::GAP_RANGE).speed(0.5).max_decimals(0).suffix(" pt"));
|
||||
});
|
||||
});
|
||||
form_note(ui, LW, text(Type::Caption, "The timeline always leaves room before frame 1 for the playhead; this adds more. It stays the same at every zoom."));
|
||||
});
|
||||
|
||||
section(ui, "prefs_files", Section::Rule, "Files", None, |ui| {
|
||||
form_row(ui, LW, "File dialogs", |ui| {
|
||||
ui.vertical(|ui| {
|
||||
crate::theme::checkbox(ui, &mut p.native_dialogs, text(Type::Body, "Use the system's open and save dialogs"));
|
||||
form_note(ui, toggle_indent, text(Type::Caption, "Turn off on Linux desktops without an XDG desktop portal; AniCraft then asks for a path instead."));
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
form_row(ui, LW, "Autosave", |ui| {
|
||||
ui.vertical(|ui| {
|
||||
crate::theme::checkbox(ui, &mut p.autosave, text(Type::Body, "Keep a recovery copy of unsaved work"));
|
||||
form_note(
|
||||
ui,
|
||||
toggle_indent,
|
||||
text(Type::Caption, "If AniCraft closes unexpectedly, the next start offers to restore it. Copies stay in the settings folder, never over your files, and go away when you save."),
|
||||
);
|
||||
});
|
||||
});
|
||||
ui.add_enabled_ui(p.autosave, |ui| {
|
||||
form_row(ui, LW, "Every", |ui| {
|
||||
let shown = crate::prefs::AUTOSAVE_INTERVALS.iter().find(|(s, _)| *s == p.autosave_secs).map_or_else(|| format!("{} seconds", p.autosave_secs), |(_, l)| (*l).to_string());
|
||||
egui::ComboBox::from_id_salt("pref_autosave_secs").width(160.0).selected_text(text(Type::Body, shown)).show_ui(ui, |ui| {
|
||||
for (secs, label) in crate::prefs::AUTOSAVE_INTERVALS {
|
||||
ui.selectable_value(&mut p.autosave_secs, secs, text(Type::Body, label));
|
||||
}
|
||||
});
|
||||
});
|
||||
form_row(ui, LW, "Or after", |ui| {
|
||||
with_type(ui, Type::Data, |ui| {
|
||||
ui.add(egui::DragValue::new(&mut p.autosave_edits).range(crate::prefs::AUTOSAVE_EDITS_RANGE).speed(0.5).suffix(" changes"));
|
||||
});
|
||||
});
|
||||
form_note(ui, LW, text(Type::Caption, "Whichever comes first. 0 changes: by time only. Copies are written in the background, so drawing never waits."));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
section(ui, "prefs_safety", Section::Rule, "Safety", None, |ui| {
|
||||
form_row(ui, LW, "Confirmations", |ui| {
|
||||
let n = app.skip_confirm.len();
|
||||
if ui.add_enabled(n > 0, egui::Button::new(text(Type::Body, "Show all again"))).clicked() {
|
||||
reset_confirms = true;
|
||||
}
|
||||
ui.label(text(Type::Caption, format!("{n} silenced this session")));
|
||||
section(ui, "prefs_safety", Section::Rule, "Safety", None, |ui| {
|
||||
form_row(ui, LW, "Confirmations", |ui| {
|
||||
let n = app.skip_confirm.len();
|
||||
if ui.add_enabled(n > 0, egui::Button::new(text(Type::Body, "Show all again"))).clicked() {
|
||||
reset_confirms = true;
|
||||
}
|
||||
ui.label(text(Type::Caption, format!("{n} silenced this session")));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
ui.separator();
|
||||
ui.label(text(Type::Caption, format!("{} · settings stored in {}", crate::platform::OS.name(), crate::platform::config_dir().map_or_else(|| "memory only".to_string(), |d| d.display().to_string()))));
|
||||
});
|
||||
@@ -552,7 +589,7 @@ fn fixed_rows() -> Vec<(&'static str, &'static str, Vec<&'static str>)> {
|
||||
]
|
||||
}
|
||||
|
||||
const GROUP_ORDER: [&str; 12] = ["Essentials", "Tools", "File", "Edit", "View", "Insert", "Modify", "Control", "Window", "Help", "Other", "Editing"];
|
||||
const GROUP_ORDER: [&str; 13] = ["Essentials", "Tools", "File", "Edit", "View", "Insert", "Modify", "Commands", "Control", "Window", "Help", "Other", "Editing"];
|
||||
|
||||
/// The action-name column: left-aligned, one row tall, cut off with an ellipsis when long.
|
||||
fn name_cell(ui: &mut egui::Ui, label: &str) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values.
|
||||
|
||||
const SOURCES: [(&str, &str); 11] = [
|
||||
const SOURCES: [(&str, &str); 14] = [
|
||||
("autosave.rs", include_str!("autosave.rs")),
|
||||
("icons.rs", include_str!("icons.rs")),
|
||||
("pathtools.rs", include_str!("pathtools.rs")),
|
||||
("platform.rs", include_str!("platform.rs")),
|
||||
("plugins_ui.rs", include_str!("plugins_ui.rs")),
|
||||
("prefs.rs", include_str!("prefs.rs")),
|
||||
("app.rs", include_str!("app.rs")),
|
||||
("dialogs.rs", include_str!("dialogs.rs")),
|
||||
@@ -11,6 +13,7 @@ const SOURCES: [(&str, &str); 11] = [
|
||||
("panels.rs", include_str!("panels.rs")),
|
||||
("stage.rs", include_str!("stage.rs")),
|
||||
("timeline.rs", include_str!("timeline.rs")),
|
||||
("motion_editor.rs", include_str!("motion_editor.rs")),
|
||||
("main.rs", ""),
|
||||
];
|
||||
|
||||
@@ -78,9 +81,9 @@ fn palette_meets_contrast_and_target_minimums() {
|
||||
assert!(contrast(Color32::WHITE, T.accent) >= 4.5, "white on accent: {:.2}", contrast(Color32::WHITE, T.accent));
|
||||
assert!(contrast(Color32::WHITE, T.danger) >= 4.5);
|
||||
// Marks on timeline blocks, and the blocks against the grid (non-text: 3:1).
|
||||
assert!(contrast(T.ink, T.span) >= 4.5 && contrast(T.ink, T.tween) >= 4.5 && contrast(T.ink, T.tween_shape) >= 4.5, "ink on blocks");
|
||||
assert!(contrast(T.ink, T.span) >= 4.5 && contrast(T.ink, T.tween) >= 4.5 && contrast(T.ink, T.tween_shape) >= 4.5 && contrast(T.ink, T.tween_motion) >= 4.5, "ink on blocks");
|
||||
assert!(contrast(T.text, T.span_empty) >= 4.5);
|
||||
assert!(contrast(T.span, T.panel) >= 3.0 && contrast(T.tween, T.panel) >= 3.0 && contrast(T.tween_shape, T.panel) >= 3.0);
|
||||
assert!(contrast(T.span, T.panel) >= 3.0 && contrast(T.tween, T.panel) >= 3.0 && contrast(T.tween_shape, T.panel) >= 3.0 && contrast(T.tween_motion, T.panel) >= 3.0);
|
||||
// Focus and selection outlines, and checkbox edges, stand out from the panels (WCAG 1.4.11).
|
||||
assert!(contrast(T.control_edge, T.panel_alt) >= 3.0 && contrast(T.control_edge, T.panel) >= 3.0, "control edges");
|
||||
assert!(contrast(T.accent, T.panel) >= 3.0, "accent on panel: {:.2}", contrast(T.accent, T.panel));
|
||||
|
||||
@@ -7,13 +7,16 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod app;
|
||||
mod autosave;
|
||||
mod dialogs;
|
||||
mod icons;
|
||||
mod keymap;
|
||||
mod menus;
|
||||
mod motion_editor;
|
||||
mod panels;
|
||||
mod pathtools;
|
||||
mod platform;
|
||||
mod plugins_ui;
|
||||
mod prefs;
|
||||
mod stage;
|
||||
mod theme;
|
||||
@@ -23,20 +26,22 @@ use anicraft_engine::Session;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The session to start with: the file given on the command line (through `file.open`, so
|
||||
/// `.fla` / `.xfl` import works the same as from the menu), else the sample.
|
||||
fn open_session(file: Option<&Path>) -> Session {
|
||||
let Some(p) = file else { return Session::new(anicraft_engine::doc::sample::demo()) };
|
||||
/// `.fla` / `.xfl` import works the same as from the menu), else the sample. Also the import
|
||||
/// report of an Animate document, for the status bar.
|
||||
fn open_session(file: Option<&Path>) -> (Session, Option<String>) {
|
||||
let Some(p) = file else { return (Session::new(anicraft_engine::doc::sample::demo()), None) };
|
||||
let mut s = Session::default();
|
||||
match s.execute("file.open", &serde_json::json!({"path": p.display().to_string()})) {
|
||||
Ok(v) => {
|
||||
if let Some(r) = v.get("report").and_then(|r| r.as_str()) {
|
||||
let report = v.get("report").and_then(|r| r.as_str()).map(str::to_string);
|
||||
if let Some(r) = &report {
|
||||
println!("{r}");
|
||||
}
|
||||
s
|
||||
(s, report)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("could not open {}: {e}; starting with the sample", p.display());
|
||||
Session::new(anicraft_engine::doc::sample::demo())
|
||||
(Session::new(anicraft_engine::doc::sample::demo()), None)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,13 +52,20 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option<PathBuf>, o
|
||||
renderer,
|
||||
..Default::default()
|
||||
};
|
||||
let session = open_session(file);
|
||||
// The embedded interface font joins the text library before anything lays text out:
|
||||
// opening an Animate document from the command line lays its text out right here.
|
||||
anicraft_engine::text::Fonts::register(theme::embedded_fonts());
|
||||
let (session, report) = open_session(file);
|
||||
eframe::run_native(
|
||||
"AniCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let mut a = app::App::new(cc, session, shot);
|
||||
a.open_panel(open.as_deref());
|
||||
// An imported document says what came across, as opening it from the menu does.
|
||||
if let Some(r) = report {
|
||||
a.status_ok(format!("{r} Save to keep it as an AniCraft document."));
|
||||
}
|
||||
Ok(Box::new(a))
|
||||
}),
|
||||
)
|
||||
@@ -78,7 +90,7 @@ fn main() -> eframe::Result {
|
||||
"--renderer" => renderer_arg = args.next(),
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open palette|shortcuts|lastscene|select|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|prefs|licenses|zoom]\n\
|
||||
"anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|prefs|licenses|zoom|recovery|plugins]\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\
|
||||
Headless use: anicraft-cli --help"
|
||||
|
||||
@@ -5,7 +5,8 @@ use crate::platform::{self, Os};
|
||||
use crate::theme::{Type, text};
|
||||
use anicraft_engine::{CommandSpec, commands};
|
||||
|
||||
const TOP_MENUS: [&str; 8] = ["File", "Edit", "View", "Insert", "Modify", "Control", "Window", "Help"];
|
||||
// Commands sits where Animate has it: after Modify, before Control.
|
||||
const TOP_MENUS: [&str; 9] = ["File", "Edit", "View", "Insert", "Modify", "Commands", "Control", "Window", "Help"];
|
||||
|
||||
pub fn bar(app: &mut App, ui: &mut egui::Ui) {
|
||||
let cmds = commands();
|
||||
@@ -102,6 +103,11 @@ fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option<bool>
|
||||
}
|
||||
|
||||
fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) {
|
||||
if top == "Commands" {
|
||||
// Installed plug-ins first (they change at run time), then the registry's items.
|
||||
crate::plugins_ui::menu(app, ui, cmds, item);
|
||||
return;
|
||||
}
|
||||
// Direct items first, then one submenu per "Top/Sub" path, in registry order.
|
||||
for spec in cmds.iter().filter(|c| c.menu == top) {
|
||||
item(app, ui, spec);
|
||||
@@ -181,6 +187,14 @@ fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpe
|
||||
}
|
||||
}
|
||||
"Window" => {
|
||||
use crate::app::BottomTab;
|
||||
if ui_item(ui, "Timeline", "", Some(app.bottom == BottomTab::Timeline)) {
|
||||
app.bottom = BottomTab::Timeline;
|
||||
}
|
||||
if ui_item(ui, "Motion Editor", "", Some(app.bottom == BottomTab::MotionEditor)) {
|
||||
app.bottom = BottomTab::MotionEditor;
|
||||
}
|
||||
ui.separator();
|
||||
if ui_item(ui, "Onion Skin", "", Some(app.onion)) {
|
||||
app.onion = !app.onion;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
//! Motion Editor (ADR 0016): the property curves of the motion tween at the playhead.
|
||||
//!
|
||||
//! It shares the timeline's dock (a tab beside it, as in Animate) and follows the active layer
|
||||
//! and the playhead. Left: the properties, with their value at the playhead (drag to key it)
|
||||
//! and a diamond that adds or removes a key there. Right: the selected property's curve over
|
||||
//! 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.
|
||||
|
||||
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 egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
/// Property list width (the timeline's layer column).
|
||||
const LIST_W: f32 = 252.0;
|
||||
const ROW_H: f32 = TARGET;
|
||||
const RULER_H: f32 = 24.0;
|
||||
const FOOTER_H: f32 = 38.0;
|
||||
/// Room inside the graph around the curve, in points.
|
||||
const PAD: f32 = 18.0;
|
||||
/// Pointer distance that grabs a key or a handle.
|
||||
const GRAB: f32 = 8.0;
|
||||
|
||||
/// An in-progress drag in the graph. The value range is frozen so the curve doesn't rescale
|
||||
/// under the pointer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum MeDrag {
|
||||
/// A key's value (`frame` is the key's offset in the span).
|
||||
Key { frame: u32, lo: f32, hi: f32 },
|
||||
/// Handle 1 or 2 of the segment starting at the key at `frame`.
|
||||
Handle { frame: u32, which: u8, lo: f32, hi: f32 },
|
||||
/// Scrubbing the playhead.
|
||||
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)> {
|
||||
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))
|
||||
}
|
||||
|
||||
/// A readable step for grid lines across `span` (1, 2 or 5 × 10ⁿ).
|
||||
fn nice_step(span: f32) -> f32 {
|
||||
let raw = (span / 4.0).max(1e-3);
|
||||
let p = 10f32.powf(raw.log10().floor());
|
||||
[1.0, 2.0, 5.0, 10.0].into_iter().map(|m| m * p).find(|s| *s >= raw).unwrap_or(10.0 * p)
|
||||
}
|
||||
|
||||
fn fmt(p: Property, v: f32) -> String {
|
||||
match p {
|
||||
Property::X | Property::Y => format!("{v:.1} {}", p.unit()),
|
||||
_ => format!("{v:.1}{}", p.unit()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value range the graph shows for `track` (or the flat base value): every sampled value,
|
||||
/// every key and every handle, with a margin.
|
||||
fn value_range(track: Option<&Track>, base: f32, frames: u32, p: Property) -> (f32, f32) {
|
||||
let (mut lo, mut hi) = (base, base);
|
||||
if let Some(t) = track {
|
||||
for f in 0..frames.max(1) {
|
||||
if let Some(v) = t.value_at(f as f32) {
|
||||
lo = lo.min(v);
|
||||
hi = hi.max(v);
|
||||
}
|
||||
}
|
||||
for (i, k) in t.keys.iter().enumerate() {
|
||||
lo = lo.min(k.value);
|
||||
hi = hi.max(k.value);
|
||||
if let Some(n) = t.keys.get(i + 1) {
|
||||
let (_, y1, _, y2) = k.ease.as_bezier();
|
||||
for y in [y1, y2] {
|
||||
let v = k.value + (n.value - k.value) * y;
|
||||
lo = lo.min(v);
|
||||
hi = hi.max(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let min_span = match p {
|
||||
Property::X | Property::Y => 20.0,
|
||||
_ => 10.0,
|
||||
};
|
||||
if hi - lo < min_span {
|
||||
let c = (hi + lo) * 0.5;
|
||||
lo = c - min_span * 0.5;
|
||||
hi = c + min_span * 0.5;
|
||||
}
|
||||
let m = (hi - lo) * 0.12;
|
||||
(lo - m, hi + m)
|
||||
}
|
||||
|
||||
pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let body = ui.available_rect_before_wrap();
|
||||
ui.allocate_rect(body, Sense::hover());
|
||||
let painter = ui.painter_at(body);
|
||||
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 {
|
||||
empty_state(app, ui, body);
|
||||
return;
|
||||
};
|
||||
let offset = app.s.frame.saturating_sub(start);
|
||||
let list = Rect::from_min_max(body.left_top(), pos2(body.left() + LIST_W, body.bottom() - FOOTER_H));
|
||||
let graph_full = Rect::from_min_max(pos2(list.right(), body.top()), pos2(body.right(), body.bottom() - FOOTER_H));
|
||||
let ruler = Rect::from_min_max(graph_full.left_top(), pos2(graph_full.right(), graph_full.top() + RULER_H));
|
||||
let graph = Rect::from_min_max(pos2(graph_full.left(), ruler.bottom()), graph_full.right_bottom());
|
||||
|
||||
// ---- property list ---------------------------------------------------------------------
|
||||
painter.rect_filled(Rect::from_min_max(list.left_top(), pos2(list.right(), list.top() + RULER_H)), 0.0, T.panel_alt);
|
||||
painter.text(pos2(list.left() + 10.0, list.top() + RULER_H * 0.5), Align2::LEFT_CENTER, "Property", font(Type::Heading), color(Type::Heading));
|
||||
painter.text(pos2(list.right() - 44.0, list.top() + RULER_H * 0.5), Align2::RIGHT_CENTER, format!("Frame {}", app.s.frame + 1), font(Type::DataSmall), color(Type::DataSmall));
|
||||
let now = m.props_at(&base, offset as f32);
|
||||
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();
|
||||
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);
|
||||
}
|
||||
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) {
|
||||
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;
|
||||
painter.rect_filled(row, 0.0, if selected { T.accent_dim } else if r % 2 == 0 { T.panel } else { T.panel_alt });
|
||||
let track = m.track(p);
|
||||
// Groups (Position, Transform, Colour effect) are set apart by a rule.
|
||||
if p.group() != last_group {
|
||||
if !last_group.is_empty() {
|
||||
painter.line_segment([row.left_top(), row.right_top()], Stroke::new(1.0, T.border));
|
||||
}
|
||||
last_group = p.group();
|
||||
}
|
||||
painter.text(pos2(row.left() + 12.0, row.center().y), Align2::LEFT_CENTER, p.label(), font(Type::Body), if track.is_some() { T.text } else { T.text_dim });
|
||||
if track.is_some() {
|
||||
painter.text(pos2(row.left() + 84.0, row.center().y), Align2::LEFT_CENTER, "keyed", font(Type::Caption), T.tween_motion);
|
||||
}
|
||||
let rr = ui.interact(row, ui.id().with(("me_row", p.key())), Sense::click());
|
||||
if rr.clicked() {
|
||||
app.me_prop = p;
|
||||
app.me_key = None;
|
||||
}
|
||||
// The value at the playhead: drag or type it to key the property there.
|
||||
let field = Rect::from_min_size(pos2(row.right() - 128.0, row.top() + 3.0), vec2(88.0, ROW_H - 6.0));
|
||||
let mut v = now.get(p);
|
||||
let range = p.range();
|
||||
let speed = if matches!(p, Property::X | Property::Y) { 1.0 } else { 0.5 };
|
||||
let suffix = if p.unit() == "px" { " px" } else { p.unit() };
|
||||
// In a child placed on the row, so the field never grows the dock.
|
||||
let mut cell = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center)));
|
||||
let r = with_type(&mut cell, Type::Data, |ui| ui.add_sized(vec2(field.width(), field.height()), egui::DragValue::new(&mut v).speed(speed).range(range).max_decimals(1).suffix(suffix)));
|
||||
if r.changed() {
|
||||
app.me_prop = p;
|
||||
app.s.begin_gesture("Property keyframe");
|
||||
app.run("motion.set_key", json!({"property": p.key(), "frame": app.s.frame, "value": v}));
|
||||
}
|
||||
// Key toggle: a filled diamond where this property has a key at the playhead.
|
||||
let keyed = track.is_some_and(|t| t.key_at(offset).is_some());
|
||||
let toggle = Rect::from_center_size(pos2(row.right() - 20.0, row.center().y), vec2(24.0, 24.0));
|
||||
let tr = ui.interact(toggle, ui.id().with(("me_key", p.key())), Sense::click());
|
||||
if tr.hovered() {
|
||||
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 { format!("Remove the {} keyframe at frame {}", p.label(), app.s.frame + 1) } else { format!("Add a {} keyframe at frame {}", p.label(), app.s.frame + 1) };
|
||||
if tr.on_hover_text(tip).clicked() {
|
||||
app.me_prop = p;
|
||||
if keyed {
|
||||
app.run("motion.remove_key", json!({"property": p.key(), "frame": app.s.frame}));
|
||||
} else {
|
||||
app.run("motion.set_key", json!({"property": p.key(), "frame": app.s.frame, "value": now.get(p)}));
|
||||
}
|
||||
}
|
||||
painter.line_segment([row.left_bottom(), row.right_bottom()], Stroke::new(1.0, T.separator));
|
||||
}
|
||||
painter.line_segment([pos2(list.right(), body.top()), pos2(list.right(), body.bottom())], Stroke::new(1.0, T.border));
|
||||
|
||||
// ---- graph -----------------------------------------------------------------------------
|
||||
let p = app.me_prop;
|
||||
let track = m.track(p);
|
||||
let (lo, hi) = match app.me_drag {
|
||||
Some(MeDrag::Key { lo, hi, .. } | MeDrag::Handle { lo, hi, .. }) => (lo, hi),
|
||||
_ => value_range(track, base.get(p), frames, p),
|
||||
};
|
||||
let last = frames.saturating_sub(1).max(1) as f32;
|
||||
// Wider on the left: the value labels sit there, clear of the first key.
|
||||
let inner = Rect::from_min_max(graph.min + vec2(PAD * 2.0, PAD * 0.75), graph.max - vec2(PAD, PAD * 0.75));
|
||||
let x_of = |f: f32| inner.left() + f / last * inner.width();
|
||||
let f_of = |x: f32| ((x - inner.left()) / inner.width().max(1.0) * last).clamp(0.0, last);
|
||||
let y_of = |v: f32| inner.bottom() - (v - lo) / (hi - lo).max(1e-6) * inner.height();
|
||||
let v_of = |y: f32| lo + (inner.bottom() - y) / inner.height().max(1.0) * (hi - lo);
|
||||
let gp = painter.with_clip_rect(graph_full);
|
||||
gp.rect_filled(ruler, 0.0, T.panel_alt);
|
||||
// Value grid with labels; frame ticks on the ruler.
|
||||
let step = nice_step(hi - lo);
|
||||
let mut v = (lo / step).ceil() * step;
|
||||
for _ in 0..64 {
|
||||
if v > hi {
|
||||
break;
|
||||
}
|
||||
let y = y_of(v);
|
||||
gp.line_segment([pos2(graph.left(), y), pos2(graph.right(), y)], Stroke::new(1.0, T.separator));
|
||||
gp.text(pos2(graph.left() + 4.0, y - 1.0), Align2::LEFT_BOTTOM, format!("{v:.0}"), font(Type::DataSmall), T.text_faint);
|
||||
v += step;
|
||||
}
|
||||
let px_per_frame = inner.width() / last;
|
||||
let fstep = [1u32, 2, 5, 10, 20, 50, 100, 200, 500, 1000].into_iter().find(|s| *s as f32 * px_per_frame >= 28.0).unwrap_or(5000);
|
||||
for f in 0..frames {
|
||||
let n = start + f + 1;
|
||||
let x = x_of(f as f32).round() + 0.5;
|
||||
if n % fstep == 0 || f == 0 {
|
||||
gp.line_segment([pos2(x, ruler.bottom() - 6.0), pos2(x, ruler.bottom())], Stroke::new(1.0, T.text_faint));
|
||||
gp.text(pos2(x, ruler.top() + 3.0), Align2::CENTER_TOP, n.to_string(), font(Type::DataSmall), color(Type::DataSmall));
|
||||
gp.line_segment([pos2(x, graph.top()), pos2(x, graph.bottom())], Stroke::new(1.0, T.separator));
|
||||
}
|
||||
}
|
||||
// The playhead.
|
||||
if app.s.frame >= start && app.s.frame < start + frames {
|
||||
let x = x_of(offset as f32).round() + 0.5;
|
||||
gp.line_segment([pos2(x, ruler.bottom()), pos2(x, graph.bottom())], Stroke::new(1.5, T.playhead));
|
||||
let label = (app.s.frame + 1).to_string();
|
||||
let w = painter.layout_no_wrap(label.clone(), font(Type::DataSmall), Color32::WHITE).rect.width();
|
||||
let head = Rect::from_center_size(pos2(x, ruler.center().y), vec2((w + 8.0).max(22.0), RULER_H - 4.0));
|
||||
gp.rect_filled(head, T.rc(), T.playhead);
|
||||
gp.text(head.center(), Align2::CENTER_CENTER, label, font(Type::DataSmall), Color32::WHITE);
|
||||
}
|
||||
// The curve: sampled every two points; flat at the object's own value when unkeyed.
|
||||
let mut pts = Vec::new();
|
||||
let mut x = inner.left();
|
||||
while x <= inner.right() + 0.5 {
|
||||
let f = f_of(x);
|
||||
let v = track.and_then(|t| t.value_at(f)).unwrap_or(base.get(p));
|
||||
pts.push(pos2(x, y_of(v)));
|
||||
x += 2.0;
|
||||
}
|
||||
gp.add(egui::Shape::line(pts, Stroke::new(2.0, if track.is_some() { T.tween_motion } else { T.text_faint })));
|
||||
gp.text(pos2(graph.right() - 8.0, graph.top() + 6.0), Align2::RIGHT_TOP, format!("{} · {}", p.label(), fmt(p, now.get(p))), font(Type::Data), color(Type::Data));
|
||||
if track.is_none() {
|
||||
gp.text(graph.center(), Align2::CENTER_CENTER, format!("{} has no keyframes: it stays {}. Click ◇ or drag its value to key it here.", p.label(), fmt(p, base.get(p))), font(Type::Caption), color(Type::Caption));
|
||||
}
|
||||
|
||||
// Keys and the selected segment's handles.
|
||||
let keys: Vec<(u32, f32, Easing)> = track.map(|t| t.keys.iter().filter(|k| k.frame < frames).map(|k| (k.frame, k.value, k.ease)).collect()).unwrap_or_default();
|
||||
// The selected key: the one picked, else the one starting the segment at the playhead.
|
||||
let sel_key = app.me_key.filter(|f| keys.iter().any(|k| k.0 == *f)).or_else(|| keys.iter().rev().find(|k| k.0 <= offset).map(|k| k.0));
|
||||
let handles: Option<[Pos2; 4]> = sel_key.and_then(|f| {
|
||||
let i = keys.iter().position(|k| k.0 == f)?;
|
||||
let (a, b) = (keys.get(i)?, track?.keys.get(i + 1)?);
|
||||
let (x1, y1, x2, y2) = a.2.as_bezier();
|
||||
let (f0, f1) = (a.0 as f32, b.frame as f32);
|
||||
let dv = handle_span(a.1, b.value, lo, hi);
|
||||
let at = |x: f32, y: f32| pos2(x_of(f0 + x * (f1 - f0)), y_of(a.1 + y * dv));
|
||||
Some([pos2(x_of(f0), y_of(a.1)), at(x1, y1), at(x2, y2), pos2(x_of(f1), y_of(b.value))])
|
||||
});
|
||||
if let Some([p0, p1, p2, p3]) = handles {
|
||||
gp.line_segment([p0, p1], Stroke::new(1.0, T.text_faint));
|
||||
gp.line_segment([p3, p2], Stroke::new(1.0, T.text_faint));
|
||||
for h in [p1, p2] {
|
||||
gp.circle_filled(h, 4.5, T.tween_shape);
|
||||
gp.circle_stroke(h, 4.5, Stroke::new(1.0, T.ink));
|
||||
}
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
// ---- graph interaction -------------------------------------------------------------------
|
||||
let gr = ui.interact(graph_full, ui.id().with("me_graph"), Sense::click_and_drag());
|
||||
let hover = gr.hover_pos();
|
||||
let near_key = |pt: Pos2| keys.iter().find(|k| pos2(x_of(k.0 as f32), y_of(k.1)).distance(pt) <= GRAB).map(|k| k.0);
|
||||
let near_handle = |pt: Pos2| handles.and_then(|h| [(1u8, h[1]), (2u8, h[2])].into_iter().find(|(_, q)| q.distance(pt) <= GRAB).map(|(w, _)| w));
|
||||
if app.me_drag.is_none()
|
||||
&& let Some(h) = hover
|
||||
{
|
||||
if near_handle(h).is_some() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
|
||||
} else if near_key(h).is_some() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
|
||||
}
|
||||
}
|
||||
let to_frame = |x: f32| start + f_of(x).round() as u32;
|
||||
if gr.drag_started()
|
||||
&& let Some(pt) = ui.input(|i| i.pointer.press_origin())
|
||||
{
|
||||
app.playing = false;
|
||||
app.me_drag = Some(match (near_handle(pt), sel_key, near_key(pt)) {
|
||||
(Some(which), Some(frame), _) => {
|
||||
app.s.begin_gesture("Property ease");
|
||||
MeDrag::Handle { frame, which, lo, hi }
|
||||
}
|
||||
(_, _, Some(frame)) => {
|
||||
app.me_key = Some(frame);
|
||||
app.s.begin_gesture("Property keyframe");
|
||||
app.run("timeline.goto", json!({"frame": start + frame}));
|
||||
MeDrag::Key { frame, lo, hi }
|
||||
}
|
||||
_ => MeDrag::Scrub,
|
||||
});
|
||||
}
|
||||
if gr.dragged()
|
||||
&& let Some(pt) = gr.interact_pointer_pos()
|
||||
{
|
||||
match app.me_drag {
|
||||
Some(MeDrag::Key { frame, .. }) => {
|
||||
let r = p.range();
|
||||
let v = v_of(pt.y).clamp(*r.start(), *r.end());
|
||||
app.run("motion.set_key", json!({"property": p.key(), "frame": start + frame, "value": v}));
|
||||
}
|
||||
Some(MeDrag::Handle { frame, which, .. }) => {
|
||||
if let Some(t) = track
|
||||
&& let Some(i) = t.key_at(frame)
|
||||
&& let (Some(a), Some(b)) = (t.keys.get(i), t.keys.get(i + 1))
|
||||
{
|
||||
let (mut x1, mut y1, mut x2, mut y2) = a.ease.as_bezier();
|
||||
let span = (b.frame - a.frame).max(1) as f32;
|
||||
let nx = ((f_of(pt.x) - a.frame as f32) / span).clamp(0.0, 1.0);
|
||||
let ny = ((v_of(pt.y) - a.value) / handle_span(a.value, b.value, lo, hi)).clamp(-5.0, 5.0);
|
||||
if which == 1 {
|
||||
(x1, y1) = (nx, ny);
|
||||
} else {
|
||||
(x2, y2) = (nx, ny);
|
||||
}
|
||||
app.run("motion.set_ease", json!({"property": p.key(), "frame": start + frame, "easing": {"bezier": [x1, y1, x2, y2]}}));
|
||||
}
|
||||
}
|
||||
Some(MeDrag::Scrub) => {
|
||||
let f = to_frame(pt.x);
|
||||
if f != app.s.frame {
|
||||
app.run("timeline.goto", json!({"frame": f}));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if gr.drag_stopped() {
|
||||
app.me_drag = None;
|
||||
}
|
||||
if gr.clicked()
|
||||
&& let Some(pt) = gr.interact_pointer_pos()
|
||||
{
|
||||
app.playing = false;
|
||||
match near_key(pt) {
|
||||
Some(f) => {
|
||||
app.me_key = Some(f);
|
||||
app.run("timeline.goto", json!({"frame": start + f}));
|
||||
}
|
||||
None => {
|
||||
app.me_key = None;
|
||||
app.run("timeline.goto", json!({"frame": to_frame(pt.x)}));
|
||||
}
|
||||
}
|
||||
}
|
||||
if gr.double_clicked()
|
||||
&& let Some(pt) = gr.interact_pointer_pos()
|
||||
&& near_key(pt).is_none()
|
||||
&& pt.y > ruler.bottom()
|
||||
{
|
||||
// A key on the curve where it is now (the motion doesn't change until it is dragged).
|
||||
let f = to_frame(pt.x);
|
||||
let v = track.and_then(|t| t.value_at((f - start) as f32)).unwrap_or(base.get(p));
|
||||
if app.run("motion.set_key", json!({"property": p.key(), "frame": f, "value": v})).is_some() {
|
||||
app.me_key = Some(f - start);
|
||||
}
|
||||
}
|
||||
gr.on_hover_text_at_pointer("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);
|
||||
}
|
||||
|
||||
/// 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).
|
||||
fn handle_span(v0: f32, v1: f32, lo: f32, hi: f32) -> f32 {
|
||||
let d = v1 - v0;
|
||||
if d.abs() > (hi - lo) * 1e-3 { d } else { (hi - lo) * 0.25 }
|
||||
}
|
||||
|
||||
fn diamond(p: &egui::Painter, c: Pos2, r: f32, fill: Color32, stroke: Stroke) {
|
||||
p.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)], fill, 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<u32>, start: u32) {
|
||||
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));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink2(vec2(10.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center)));
|
||||
let ui = &mut child;
|
||||
let p = app.me_prop;
|
||||
let seg = sel_key.zip(track).and_then(|(f, t)| t.key_at(f).filter(|i| *i + 1 < t.keys.len()).and_then(|i| t.keys.get(i)).map(|k| (f, k.ease)));
|
||||
ui.label(text(Type::Label, format!("{} ease", p.label())));
|
||||
match seg {
|
||||
Some((f, ease)) => {
|
||||
egui::ComboBox::from_id_salt("me_ease").width(160.0).selected_text(ease.label()).show_ui(ui, |ui| {
|
||||
for (name, e) in Easing::PRESETS {
|
||||
if ui.selectable_label(ease == e, name).clicked() {
|
||||
app.run("motion.set_ease", json!({"property": p.key(), "frame": start + f, "easing": crate::timeline::easing_param(e)}));
|
||||
}
|
||||
}
|
||||
});
|
||||
if ui.button("Same for all").on_hover_text("Give every property's segment at this frame this ease").clicked() {
|
||||
app.run("motion.set_ease", json!({"frame": start + f, "easing": crate::timeline::easing_param(ease)}));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.label(text(Type::Caption, "Pick a key that has another key after it"));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Remove Tween").on_hover_text("The object stays as it is on the span's first frame (Ctrl+Z to undo)").clicked() {
|
||||
app.run("timeline.remove_tween", json!({}));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(text(Type::Caption, "Moving the object on the stage inside the span adds keys here"));
|
||||
});
|
||||
}
|
||||
|
||||
/// No motion tween at the playhead: say how to get one.
|
||||
fn empty_state(app: &mut App, ui: &mut egui::Ui, body: Rect) {
|
||||
let k = app.s.active_layer().and_then(|l| l.keyframe_at(app.s.frame).map(|k| (!k.elements.is_empty(), k.motion.is_some())));
|
||||
let msg = match k {
|
||||
Some((true, _)) => "This span has no motion tween. Create one to animate its object property by property.",
|
||||
Some((false, _)) => "This span is empty. Draw or place an object, then create a motion tween.",
|
||||
None => "The playhead is on an empty frame of this layer.",
|
||||
};
|
||||
let r = Rect::from_center_size(body.center(), vec2(body.width().min(520.0), 90.0));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r).layout(egui::Layout::top_down(egui::Align::Center)));
|
||||
child.label(text(Type::Heading, "Motion Editor"));
|
||||
child.add_space(4.0);
|
||||
child.label(text(Type::Caption, msg));
|
||||
child.add_space(6.0);
|
||||
if k.is_some_and(|(has, _)| has) && child.button("Create Motion Tween").clicked() {
|
||||
app.run("timeline.create_motion_tween", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn grid_steps_are_round_numbers() {
|
||||
for (span, want) in [(4.0, 1.0), (10.0, 5.0), (100.0, 50.0), (360.0, 100.0), (0.0, 0.001)] {
|
||||
assert!((nice_step(span) - want).abs() < 1e-6, "{span}: {}", nice_step(span));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_view_holds_the_curve_its_keys_and_handles() {
|
||||
use anicraft_engine::doc::PropertyKey;
|
||||
let t = Track { property: Property::Y, keys: vec![PropertyKey { frame: 0, value: 0.0, ease: Easing::CubicBezier(0.3, 1.8, 0.7, 1.0) }, PropertyKey { frame: 10, value: 100.0, ease: Easing::Linear }] };
|
||||
let (lo, hi) = value_range(Some(&t), 0.0, 11, Property::Y);
|
||||
// The overshooting handle (180 % of the rise) is inside the view, with a margin.
|
||||
assert!(lo < 0.0 && hi > 180.0, "{lo} {hi}");
|
||||
// A flat property still gets a usable view around its value.
|
||||
let (lo, hi) = value_range(None, 50.0, 10, Property::Alpha);
|
||||
assert!(lo < 50.0 && hi > 50.0 && hi - lo >= 10.0);
|
||||
// Handles of a flat segment measure against a share of the view instead of zero.
|
||||
assert_eq!(handle_span(5.0, 5.0, 0.0, 100.0), 25.0);
|
||||
assert_eq!(handle_span(0.0, 40.0, 0.0, 100.0), 40.0);
|
||||
}
|
||||
}
|
||||