commit e3913afa36962979d7f9542a2a754de21113d948 Author: Tanish Manku Date: Thu Nov 5 23:54:05 2026 -0700 Initial commit v0.1.0 early alpha AniCraft 0.1.0 (early alpha): milestones M0 and M1. Contributors are credited in AUTHORS.md. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..ecedf48f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# Normalise line endings in the repository; check out with the platform's native endings. +* text=auto +*.rs text diff=rust +*.toml text +*.md text +*.json text +*.png binary +# shell hooks must keep LF endings or /bin/sh rejects them +scripts/git-hooks/* text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b037d9d3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# build output +/target/ + +# generated screenshots and exports (regenerate with --screenshot / anicraft-cli) +/shots/ +/frames/ +*.anicraft.tmp + +# editors and OS +.idea/ +.vscode/ +*.swp +.DS_Store +Thumbs.db diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..484e77ad --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,111 @@ +# AGENTS.md: guide for AI agents and contributors + +AniCraft is an open-source, native, clean-room 2D animation studio (Adobe Animate class), written +in **Rust only**. There is no Tauri, Electron or webview. The UI is egui/eframe. The product name +is written **AniCraft**; machine names are lowercase (`anicraft-*`). Read `docs/` first. + +## Workspace map + +```text +crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing +crates/doc L1 Document model, easing, timeline evaluation, sample scene +crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG) +crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009) +crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format +crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve +src/ L5 egui shell (app, menus, stage, timeline, panels, theme) +``` + +A crate depends only on lower layers. Nothing below `src/` may use egui, eframe or winit. + +## Standing rules (read `docs/product-principles.md`) + +* **Principal-engineer check.** For every proposal ask: "Is this how a principal engineer + would do it?" If not, use the better method or ask the project lead. Record hard-to-reverse + decisions as ADRs in `docs/adr/`. +* **Users are artists and creatives** (many coming from Adobe Animate). The product must be + professional, fast, reliable and easy, with smooth, predictable flow: common actions one + click or key away, shortcuts for power users, no modal interruptions for routine edits. +* **UI guidelines** (`docs/ui-guidelines.md`, ADR 0005): text goes through `theme::Type` + roles. Data (numbers, timecode, rulers, values, shortcuts, paths) is monospace; prose + (labels, menus, buttons, names, dialog text) is proportional. No raw font sizes or colours + outside `theme.rs` (enforced by `guidelines_tests`). Typefaces: Inter + JetBrains Mono via + `CRAFT_FONTS_DIR`, with egui defaults as fallback. +* **Cross-platform** (ADR 0006): macOS, Windows and Linux are first-class. OS-specific + behaviour lives only in `src/platform.rs` (shortcut labels with ⌘ on macOS, app menu, + window chrome, settings folder, native dialogs, GPU backend fallback). Shortcut text always + goes through `platform::shortcut_label`. +* **Edits are live**: anything that changes the document must show in the same frame (Auto + render mode). Never leave an edit waiting for the next input event. +* **Destructive actions** follow the tiers in ADR 0004: irreversible loss always confirms + (engine-enforced `"confirm": true`); large undoable deletions confirm by default; routine + edits rely on undo with a visible hint. + +## Golden rules + +1. **Never crash.** Non-test code never panics: no `unwrap`/`expect`/`panic!`/indexing on + input-derived values. Crates carry `#![deny(clippy::unwrap_used, …)]`. Commands validate params + and return `Err`. The `panic_hunt_every_command` test fuzzes every command and must stay green. +2. **Everything is a command.** New behaviour means a `CommandSpec` in `crates/engine/src/cmds_*.rs` + with id, label, menu path, shortcut, params doc and tests. Menus and shortcuts are generated + from the registry. Only view state (zoom, pan, tool, onion skin, playback) lives in the shell. +3. **Time is a function.** Never animate by mutating the document. Add behaviour to + `doc::evaluate` and keep it pure. +4. **The CPU renderer is the oracle.** Renderer changes come with analytic or golden tests. Any + future GPU renderer is tested against it. +5. **No unsafe** (`unsafe_code = "forbid"`). +6. **Clean room.** Learn behaviour from public docs and observation only. Never copy proprietary + code, presets, shaders or assets. +7. **Verify UI changes visually**: `cargo run -- --screenshot shots/now.png`, then look at the PNG. + +## Licensing and legal compliance (read `docs/legal/compliance.md`) + +* AniCraft is **MIT OR Apache-2.0**, like PhotoCraft (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). +* **Dependencies**: permissive only, from crates.io only. `deny.toml` is the policy, and + `cargo deny check licenses bans sources` must pass. Adding a crate with a new licence needs + a deliberate `deny.toml` change and a note in `compliance.md`. No copyleft, "non-commercial" + or source-available terms. +* **Assets**: every font, icon, image, sound or sample file gets a row in `ATTRIBUTION.md` + in the same change, with its licence text under `licenses/`. Never commit font files + (use the shared craft-fonts input). Never commit Adobe or other proprietary material. +* **Patents**: implement only from public papers, open specifications and permissively + licensed references; credit them in `ATTRIBUTION.md`. Never bundle encoders for + patent-pool codecs (H.264/HEVC/AAC); use royalty-free formats or a user-installed ffmpeg. +* **Trademarks**: Adobe, Animate and Flash only nominatively (docs, and the non-affiliation + disclaimer in legal notices), never in the product name, branding, feature UI or marketing. + +## Version control + +* Git. Remote `origin` = `https://github.com/storytold/AniCraft` (public). `main` is the + development branch; it begins with "Initial commit v0.1.0 early alpha", and contributors are + credited in `AUTHORS.md`. +* **Every change reaches `main` through a pull request** from a topic branch (`feat/…`, `fix/…`, + `docs/…`), with one roadmap step per PR, green on build, tests, clippy and `cargo deny`. + Never commit or push to `main` directly. `core.hooksPath` points at `scripts/git-hooks`: + `pre-commit` refuses commits on `main`, and `pre-push` refuses pushes to the remote `main`. + Run `git config core.hooksPath scripts/git-hooks` once per clone. +* Branches marked hidden in your local git config (`git config --add anicraft.hidden `) + never leave the machine: `pre-push` refuses them and anything built on them. +* 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. +* Never commit `target/`, screenshots (`shots/`), exports or `.anicraft` user files. + +## Build hygiene (disk first, then time; `docs/development.md` › Build footprint) + +* Use the **single shared `target/`**. No per-agent `CARGO_TARGET_DIR` copies (each is a + full build). +* Don't turn incremental compilation or full debug info back on in `Cargo.toml`. Do that + locally if you need a debugger. +* After profile or feature changes, run `cargo clean` once (with the app closed). + +## Before you finish + +```sh +cargo test +cargo clippy --all-targets -- -D warnings +cargo deny check licenses bans sources +cargo run -- --screenshot shots/now.png +``` + +Update `docs/roadmap.md` › Honest status when you move a capability. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md new file mode 100644 index 00000000..71b191dc --- /dev/null +++ b/ATTRIBUTION.md @@ -0,0 +1,68 @@ +# Attribution + +Every non-code asset AniCraft ships or embeds, and every published work our code follows +closely, with author, source and licence. AniCraft's own code and original assets are +MIT OR Apache-2.0 (see [`LICENSE-MIT`](LICENSE-MIT), [`LICENSE-APACHE`](LICENSE-APACHE) and +[`NOTICE`](NOTICE)). + +**Rule:** when you add an asset (font, icon, image, sound, sample file, data table) or base code +on a specific published implementation, add a row here *in the same change*. Third-party assets +must be permissively licensed and keep their licence file under [`licenses/`](licenses/). +Never commit proprietary material (Adobe or other vendors' icons, presets, sample files, fonts, +shaders or SDK code). + +## Bundled in the app + +| Item | Use | Author | Source | Licence | +|---|---|---|---|---| +| Ubuntu Light (via `epaint_default_fonts`) | UI proportional font | Canonical Ltd. / Dalton Maag | | Ubuntu Font Licence 1.0, [`licenses/fonts/UFL-1.0-Ubuntu-font.txt`](licenses/fonts/UFL-1.0-Ubuntu-font.txt) | +| Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | +| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) | +| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) | +| `assets/icons/anicraft-*.svg` (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-*` (25 files: tools, transport, layer toggles, section chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | (`icons/.svg`), copied unchanged from the PhotoCraft sibling project's set | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | +| 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 | + +### Optional build input: craft-fonts (not files in this repo) + +Builds made with `CRAFT_FONTS_DIR` (all official releases; ADR 0005) embed these from the shared +[storytold/craft-fonts](https://github.com/storytold/craft-fonts). No font file is committed +here. + +| Font (embedded at build time) | Use | Author | Licence | +|---|---|---|---| +| 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. + +## Algorithms and published techniques + +Our implementations are written from the public descriptions below. No third-party code was +copied. Code ported from the sibling project PhotoCraft (same project family and licence, MIT +OR Apache-2.0) is noted in the table. + +| Technique | Where | Reference | Notes | +|---|---|---|---| +| Signed-area coverage accumulation rasterizer | `crates/render/src/raster.rs` | Raph Levien, *font-rs* (2016), , Apache-2.0; also stb_truetype v2 (public domain) | Our implementation follows the published accumulate-and-prefix-sum approach. Credited here; Apache-2.0 includes a patent licence. | +| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | | +| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. | +| Cubic-Bézier easing (CSS model) | `crates/doc/src/easing.rs` | W3C CSS Easing Functions Level 1 | W3C Royalty-Free Patent Policy. | +| SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. | +| Marching-squares contour tracing (Paint Bucket regions) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. | +| Chamfer distance transform (3-4) and flood fill | `crates/engine/src/cmds_paint.rs` | G. Borgefors, *Distance transformations in digital images* (1986); public algorithms | Gap closing, and growing fills under their outlines. | +| ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs` | PKWARE APPNOTE.TXT (published ZIP specification); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries; no ZIP64 or encryption. | +| XFL document structure and shape edges | `crates/xfl/src/` | The publicly documented XFL package structure (`DOMDocument.xml`, `LIBRARY/*.xml`, edge strings) | Clean room: no Animate or third-party converter code (ADR 0009). | +| Full SVG path data and elliptical-arc to Bézier conversion | `crates/geom/src/svg.rs` | W3C SVG 1.1 §8.3 and Appendix F.6 (implementation notes) | W3C Royalty-Free Patent Policy. | +| 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. | +| 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 + +About 420 crates across all target platforms, all permissively licensed. Policy, audit command, +results and elected licences are in [`docs/legal/compliance.md`](docs/legal/compliance.md). The +generated inventory is [`docs/legal/third-party-inventory.txt`](docs/legal/third-party-inventory.txt). diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 00000000..edbac412 --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,6 @@ +# Authors + +People who have contributed to AniCraft. The repository starts from one initial commit +(`docs/release.md`), so the work before it is credited here. + +* Tanish Manku: project lead, product direction and design. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..bf65eea4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +## 0.1.0 (2026-11-05): early alpha + +The first version: milestones M0 (foundations) and M1 (authoring core) are complete. The +repository starts here with one commit; earlier work is credited in `AUTHORS.md`. + +* **Drawing**: Selection, Subselection, Free Transform, Pen, Pencil (smooth, straighten, ink), + Rectangle, Oval, PolyStar, Line, Paint Bucket (with gap closing), Ink Bottle, Hand and Zoom. + Also cut, copy and paste (in centre, in place), duplicate, arrange, rotate and flip, align + and distribute, convert to symbol and break apart. +* **Timeline**: layers (show, lock, outline), keyframes, blank keyframes, frame spans, classic + tweens with easing presets, labels, onion skin, looping playback. Frames can be selected + across layers; cut, copy and paste frames; drag keyframes and span ends. Timeline zoom and + scrolling. +* **Mask layers**: a mask reveals only its fill area of the layers under it, on the stage and in + every export. +* **Files**: `.anicraft` documents, PNG frames and sequences, animated GIF. Opens Animate + documents (`.fla`, `.xfl`), with a report of anything not yet supported. +* **Ease of use**: an editable keyboard shortcut map (F1), with the familiar animation + defaults. Also the command palette (Ctrl+K), right-click menus everywhere, confirmations only + before real loss, an unsaved-changes guard, Preferences, and macOS, Windows and Linux + conventions. +* **Engine**: every action is a command, scriptable headless through `anicraft-cli`. Undo is + cheap even on large files. The stage renders in tiles in the background, on a deterministic + CPU renderer. + +Not in this version: scenes, layer folders, motion and shape tweens, text, bitmaps, sound, +SVG/Lottie/video export, plug-ins and installers (milestones M2 to M8 in `docs/roadmap.md`). diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..02678c3f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,4133 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accesskit" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954" +dependencies = [ + "accesskit", + "accesskit_consumer 0.36.0", + "atspi-common", + "phf", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer 0.38.0", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21" +dependencies = [ + "accesskit", + "accesskit_consumer 0.35.0", + "hashbrown 0.16.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313" +dependencies = [ + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anicraft" +version = "0.1.0" +dependencies = [ + "anicraft-doc", + "anicraft-engine", + "anicraft-geom", + "anicraft-render", + "eframe", + "egui", + "fontdb", + "rfd", + "serde", + "serde_json", +] + +[[package]] +name = "anicraft-cli" +version = "0.1.0" +dependencies = [ + "anicraft-doc", + "anicraft-engine", + "anicraft-geom", + "anicraft-render", + "serde_json", +] + +[[package]] +name = "anicraft-doc" +version = "0.1.0" +dependencies = [ + "anicraft-geom", + "serde", + "serde_json", +] + +[[package]] +name = "anicraft-engine" +version = "0.1.0" +dependencies = [ + "anicraft-doc", + "anicraft-geom", + "anicraft-render", + "anicraft-xfl", + "gif", + "rayon", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "anicraft-geom" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "anicraft-render" +version = "0.1.0" +dependencies = [ + "anicraft-doc", + "anicraft-geom", + "png 0.17.16", + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "anicraft-xfl" +version = "0.1.0" +dependencies = [ + "anicraft-doc", + "anicraft-geom", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "x11rb", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.5", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.5", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.5", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.5", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.5", + "rustix 1.1.5", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "ecolor" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34" +dependencies = [ + "bytemuck", + "emath", +] + +[[package]] +name = "eframe" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ad41fac6e3149abb4866e93df37dbd33baa95db525c3368c944584e95a5dc2" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "egui-wgpu", + "egui-winit", + "egui_glow", + "glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "pollster 1.0.1", + "profiling", + "raw-window-handle", + "static_assertions", + "wasm-bindgen", + "web-sys", + "web-time", + "wgpu", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba" +dependencies = [ + "accesskit", + "ahash", + "bitflags 2.13.2", + "emath", + "epaint", + "itertools", + "log", + "nohash-hasher", + "profiling", + "smallvec", + "unicode-segmentation", + "web-sys", +] + +[[package]] +name = "egui-wgpu" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cef1f6d1bba40b09a4d0d62cb822b81030922cfbf65c5373398c3a3caafc5bd" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "epaint", + "log", + "profiling", + "thiserror 2.0.21", + "type-map", + "web-time", + "wgpu", + "winit", +] + +[[package]] +name = "egui-winit" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc" +dependencies = [ + "accesskit_winit", + "arboard", + "bytemuck", + "egui", + "log", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "objc2-ui-kit 0.3.2", + "profiling", + "raw-window-handle", + "smithay-clipboard", + "web-time", + "winit", +] + +[[package]] +name = "egui_glow" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "profiling", + "winit", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "emath" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "epaint" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3" +dependencies = [ + "ahash", + "bytemuck", + "ecolor", + "emath", + "epaint_default_fonts", + "font-types", + "harfrust", + "log", + "nohash-hasher", + "parking_lot", + "profiling", + "self_cell", + "skrifa", + "smallvec", + "unicode-general-category", + "unicode-segmentation", + "vello_cpu", +] + +[[package]] +name = "epaint_default_fonts" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "fearless_simd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glifo" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a" +dependencies = [ + "bytemuck", + "foldhash", + "hashbrown 0.17.1", + "log", + "peniko", + "skrifa", + "smallvec", + "vello_common", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[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 = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "pollster 0.4.0", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[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 3.0.9", +] + +[[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 = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.14.5", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vello_common" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "log", + "peniko", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "vello_common", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.5", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.5", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "smithay-client-toolkit 0.19.2", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..8c8306ec --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,100 @@ +[workspace] +resolver = "3" +members = [".", "crates/*"] +default-members = [".", "crates/*"] + +[workspace.package] +# 0.1.0 is the early alpha (release stage in src/app.rs, RELEASE_STAGE); see CHANGELOG.md +# and docs/release.md. +version = "0.1.0" +edition = "2024" +license = "MIT OR Apache-2.0" +# An application, not a library: not published to crates.io. +publish = false +repository = "https://github.com/storytold/AniCraft" +rust-version = "1.90" + +[workspace.dependencies] +anicraft-geom = { path = "crates/geom" } +anicraft-doc = { path = "crates/doc" } +anicraft-render = { path = "crates/render" } +anicraft-engine = { path = "crates/engine" } +anicraft-xfl = { path = "crates/xfl" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +rayon = "1" +png = "0.17" +gif = "0.14" +# wgpu is the primary renderer; glow (OpenGL) is the fallback for GPUs/VMs where wgpu fails. +# Default features off: we skip `links` (opening web links pulls in url/idna/ICU Unicode +# tables we don't use) and the web-only screen-reader shim. Same set as PhotoCraft, plus glow. +eframe = { version = "0.36", default-features = false, features = ["accesskit", "default_fonts", "wgpu", "glow", "wayland", "x11"] } +# Native file dialogs: Windows common dialogs, macOS NSOpenPanel, Linux XDG desktop portal. +rfd = "0.17" +# Lists and loads the OS's installed fonts for Preferences › Appearance (MIT). +# Without the `fontconfig` feature, Linux scans the standard font folders directly +# (/usr/share/fonts, /usr/local/share/fonts, ~/.local/share/fonts, ~/.fonts). +fontdb = { version = "0.23", default-features = false, features = ["std", "fs", "memmap"] } +egui = "0.36" + +[workspace.lints.rust] +unsafe_code = "forbid" + +[workspace.lints.clippy] +dbg_macro = "warn" +todo = "warn" + +[package] +name = "anicraft" +description = "AniCraft desktop app: egui shell over the AniCraft engine" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +default-run = "anicraft" + +[[bin]] +name = "anicraft" +path = "src/main.rs" + +[dependencies] +anicraft-geom.workspace = true +anicraft-doc.workspace = true +anicraft-render.workspace = true +anicraft-engine.workspace = true +eframe.workspace = true +egui.workspace = true +rfd.workspace = true +serde.workspace = true +fontdb.workspace = true +serde_json.workspace = true + +[lints] +workspace = true + +# ----- build profiles: biased for disk space, then time (docs/development.md › Build footprint) -- + +[profile.dev] +opt-level = 1 +# File:line in backtraces and panics, without full variable debug info (a fraction of the size; +# also keeps Windows PDBs under the LNK1140 limit). +debug = "line-tables-only" +# The incremental cache was ~3 GB for our crates; they rebuild from scratch in seconds. +incremental = false + +[profile.dev.package."*"] +# Dependencies: optimized once (fast app in debug builds), no debug info at all. +opt-level = 2 +debug = false + +[profile.dev.build-override] +# Build scripts and proc-macros: compile fast, no debug info. +opt-level = 0 +debug = false + +[profile.release] +lto = "thin" +codegen-units = 1 +strip = "debuginfo" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 00000000..f433b1a5 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 00000000..8ae0c638 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ArtCraft Team and the AniCraft contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..e67d58af --- /dev/null +++ b/NOTICE @@ -0,0 +1,33 @@ +AniCraft +Copyright (c) 2026 ArtCraft Team and the AniCraft contributors. +Licensed under the MIT License or the Apache License, Version 2.0, at your option +(LICENSE-MIT, LICENSE-APACHE). Contributions are accepted under the same terms; the Apache +License 2.0 includes an express patent licence from contributors (section 3). + +Trademarks + +Adobe, Adobe Animate and Flash are trademarks of Adobe Inc. AniCraft is an independent, +clean-room project. It is not affiliated with, endorsed by or derived from Adobe. Those names +appear only in documentation, to describe compatibility. The ArtCraft name and marks belong to +the ArtCraft Team and are not covered by the licences above. + +Third-party material + +This product bundles third-party material under its own licences. The per-item list (author, +source, licence) is in ATTRIBUTION.md, the dependency policy and audit are in +docs/legal/compliance.md, and the licence texts that must ship with the fonts are in licenses/. + +UI fonts, embedded through the egui crate `epaint_default_fonts`: + Ubuntu Light: Ubuntu Font Licence 1.0. See licenses/fonts/UFL-1.0-Ubuntu-font.txt. + Hack Regular: MIT, with Bitstream Vera licence portions. See licenses/fonts/LICENSE-Hack.txt. + Noto Emoji: SIL Open Font License 1.1. See licenses/fonts/OFL-1.1-NotoEmoji.txt. + emoji-icon-font: MIT. See licenses/fonts/LICENSE-emoji-icon-font.txt. + +Official builds also embed, from the shared craft-fonts build input (CRAFT_FONTS_DIR): + Inter Regular and JetBrains Mono Regular: SIL Open Font License 1.1. Their licence texts ship + with the package as OFL-Inter.txt and OFL-JetBrainsMono.txt. + +Rust crates (about 420 across all platforms) are permissively licensed (MIT, Apache-2.0, BSD, +ISC, Zlib, BSL-1.0, Unicode-3.0, Unlicense, 0BSD). Where a crate offers a copyleft alternative, +AniCraft uses it under its permissive licence. Binary releases ship the full licence texts of +all crates (see docs/legal/compliance.md, "Release checklist"). diff --git a/README.md b/README.md new file mode 100644 index 00000000..9010482d --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# AniCraft + +An open-source, native 2D vector animation studio in the class of Adobe Animate, written in +Rust. It's a clean-room implementation, part of the `{Function}Craft` family (PhotoCraft, +LightCraft, WordCraft, …). + +* **Solid architecture**: layered crates (geom → doc → render → engine → cli → shell). The + document is plain data, and the picture at a frame is a pure function `evaluate(doc, frame)`. +* **Own renderer**: a deterministic CPU oracle with analytic anti-aliasing (signed-area coverage + accumulation), non-zero/even-odd fills, gradients, round-join strokes and rayon row parallelism. +* **Headless first**: every action is an engine command. The UI, the CLI and the JSON-lines + agent channel all dispatch the same ids. +* **egui shell**: stage, tools, timeline (layers, keyframes, classic tweens with easing, onion + skin), properties and library. + +## Build and run + +```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 +``` + +## Headless / agents + +```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 -- 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 +``` + +The `serve` protocol takes one request per line, +`{"id":1,"cmd":"timeline.insert_keyframe","params":{"frame":10}}`, and answers +`{"id":1,"ok":true,"result":{…},"revision":7,"frame":0}`. Send `{"cmd":"quit"}` to stop. + +## Documents + +* [`docs/requirements.md`](docs/requirements.md): scope, functional and non-functional requirements, technology choices +* [`docs/architecture.md`](docs/architecture.md): philosophy, crate map, document model, renderer, engine, testing +* [`docs/roadmap.md`](docs/roadmap.md): honest status and milestones M0–M8 +* [`AGENTS.md`](AGENTS.md): rules for contributors and AI agents + +## License + +Licensed under either of [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE) at your option, +like the sibling app PhotoCraft. Third-party notices are in [`NOTICE`](NOTICE) and +[`ATTRIBUTION.md`](ATTRIBUTION.md). The dependency and asset compliance policy and audit +(`cargo deny`) are in [`docs/legal/compliance.md`](docs/legal/compliance.md). The sample +animation and all UI icons are original and generated in code. + +AniCraft is an independent clean-room project. It is not affiliated with or endorsed by Adobe. +Adobe, Animate and Flash are trademarks of Adobe Inc. diff --git a/assets/icons/LICENSE-lucide.txt b/assets/icons/LICENSE-lucide.txt new file mode 100644 index 00000000..718bb3f0 --- /dev/null +++ b/assets/icons/LICENSE-lucide.txt @@ -0,0 +1,43 @@ +ISC License + +Copyright (c) 2026 Lucide Icons and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--- + +The following Lucide icons are derived from the Feather project: + +airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out + +The MIT License (MIT) (for the icons listed above) + +Copyright (c) 2013-present Cole Bemis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/assets/icons/anicraft-align-bottom.svg b/assets/icons/anicraft-align-bottom.svg new file mode 100644 index 00000000..77dc3fba --- /dev/null +++ b/assets/icons/anicraft-align-bottom.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-align-hcenter.svg b/assets/icons/anicraft-align-hcenter.svg new file mode 100644 index 00000000..07406857 --- /dev/null +++ b/assets/icons/anicraft-align-hcenter.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-align-left.svg b/assets/icons/anicraft-align-left.svg new file mode 100644 index 00000000..8ef5bddb --- /dev/null +++ b/assets/icons/anicraft-align-left.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-align-right.svg b/assets/icons/anicraft-align-right.svg new file mode 100644 index 00000000..c2069a61 --- /dev/null +++ b/assets/icons/anicraft-align-right.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-align-top.svg b/assets/icons/anicraft-align-top.svg new file mode 100644 index 00000000..3f82bc21 --- /dev/null +++ b/assets/icons/anicraft-align-top.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-align-vcenter.svg b/assets/icons/anicraft-align-vcenter.svg new file mode 100644 index 00000000..3c7c5738 --- /dev/null +++ b/assets/icons/anicraft-align-vcenter.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-distribute-h.svg b/assets/icons/anicraft-distribute-h.svg new file mode 100644 index 00000000..57981d97 --- /dev/null +++ b/assets/icons/anicraft-distribute-h.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/anicraft-distribute-v.svg b/assets/icons/anicraft-distribute-v.svg new file mode 100644 index 00000000..c0a64d9e --- /dev/null +++ b/assets/icons/anicraft-distribute-v.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/anicraft-mask.svg b/assets/icons/anicraft-mask.svg new file mode 100644 index 00000000..40b49c65 --- /dev/null +++ b/assets/icons/anicraft-mask.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/icons/anicraft-masked.svg b/assets/icons/anicraft-masked.svg new file mode 100644 index 00000000..2bd9537e --- /dev/null +++ b/assets/icons/anicraft-masked.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/icons/chevron-down.svg b/assets/icons/chevron-down.svg new file mode 100644 index 00000000..e70d30b8 --- /dev/null +++ b/assets/icons/chevron-down.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/chevron-right.svg b/assets/icons/chevron-right.svg new file mode 100644 index 00000000..db62a0c2 --- /dev/null +++ b/assets/icons/chevron-right.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/chevrons-left.svg b/assets/icons/chevrons-left.svg new file mode 100644 index 00000000..94b37487 --- /dev/null +++ b/assets/icons/chevrons-left.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/chevrons-right.svg b/assets/icons/chevrons-right.svg new file mode 100644 index 00000000..0d2d8ec9 --- /dev/null +++ b/assets/icons/chevrons-right.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/circle.svg b/assets/icons/circle.svg new file mode 100644 index 00000000..1717bb4b --- /dev/null +++ b/assets/icons/circle.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/droplet.svg b/assets/icons/droplet.svg new file mode 100644 index 00000000..36aa334f --- /dev/null +++ b/assets/icons/droplet.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/eye-off.svg b/assets/icons/eye-off.svg new file mode 100644 index 00000000..0083aaa8 --- /dev/null +++ b/assets/icons/eye-off.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/eye.svg b/assets/icons/eye.svg new file mode 100644 index 00000000..e5e78706 --- /dev/null +++ b/assets/icons/eye.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/hand.svg b/assets/icons/hand.svg new file mode 100644 index 00000000..30af9046 --- /dev/null +++ b/assets/icons/hand.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/layers.svg b/assets/icons/layers.svg new file mode 100644 index 00000000..a3b69ae3 --- /dev/null +++ b/assets/icons/layers.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/assets/icons/lock-open.svg b/assets/icons/lock-open.svg new file mode 100644 index 00000000..b2367128 --- /dev/null +++ b/assets/icons/lock-open.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/lock.svg b/assets/icons/lock.svg new file mode 100644 index 00000000..b2b32d12 --- /dev/null +++ b/assets/icons/lock.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/mouse-pointer-2.svg b/assets/icons/mouse-pointer-2.svg new file mode 100644 index 00000000..b881f795 --- /dev/null +++ b/assets/icons/mouse-pointer-2.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/navigation.svg b/assets/icons/navigation.svg new file mode 100644 index 00000000..b2be022d --- /dev/null +++ b/assets/icons/navigation.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/paint-bucket.svg b/assets/icons/paint-bucket.svg new file mode 100644 index 00000000..f7997334 --- /dev/null +++ b/assets/icons/paint-bucket.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/pause.svg b/assets/icons/pause.svg new file mode 100644 index 00000000..9b8c5009 --- /dev/null +++ b/assets/icons/pause.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/pen-tool.svg b/assets/icons/pen-tool.svg new file mode 100644 index 00000000..738c6fec --- /dev/null +++ b/assets/icons/pen-tool.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/pencil.svg b/assets/icons/pencil.svg new file mode 100644 index 00000000..7384498e --- /dev/null +++ b/assets/icons/pencil.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/pentagon.svg b/assets/icons/pentagon.svg new file mode 100644 index 00000000..4cbc0830 --- /dev/null +++ b/assets/icons/pentagon.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/play.svg b/assets/icons/play.svg new file mode 100644 index 00000000..199743ed --- /dev/null +++ b/assets/icons/play.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/rectangle-horizontal.svg b/assets/icons/rectangle-horizontal.svg new file mode 100644 index 00000000..71d1275a --- /dev/null +++ b/assets/icons/rectangle-horizontal.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/rotate-cw.svg b/assets/icons/rotate-cw.svg new file mode 100644 index 00000000..6795f157 --- /dev/null +++ b/assets/icons/rotate-cw.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/scaling.svg b/assets/icons/scaling.svg new file mode 100644 index 00000000..6c10bcdd --- /dev/null +++ b/assets/icons/scaling.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/slash.svg b/assets/icons/slash.svg new file mode 100644 index 00000000..391dc6ad --- /dev/null +++ b/assets/icons/slash.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/zoom-in.svg b/assets/icons/zoom-in.svg new file mode 100644 index 00000000..11173c0e --- /dev/null +++ b/assets/icons/zoom-in.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/build.rs b/build.rs new file mode 100644 index 00000000..8180bf5b --- /dev/null +++ b/build.rs @@ -0,0 +1,83 @@ +//! Optional font build input (the Craft family convention, as in PhotoCraft). +//! +//! `CRAFT_FONTS_DIR= 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 +//! committed to this repository. Without the variable the app uses egui's bundled defaults, and +//! everything still works. + +use std::path::{Path, PathBuf}; + +/// Files we look for, and the generated constant each fills. +const FONTS: [(&str, &str); 2] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT")]; + +fn find(dir: &Path, name: &str, depth: u32) -> Option { + let entries = std::fs::read_dir(dir).ok()?; + let mut subdirs = Vec::new(); + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + subdirs.push(p); + } else if p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(name)) { + return Some(p); + } + } + if depth == 0 { + return None; + } + subdirs.iter().find_map(|d| find(d, name, depth - 1)) +} + +/// Where to look for the fonts when `CRAFT_FONTS_DIR` is not set: a `craft-fonts` checkout next +/// to this repository (or up to three folders above it), then a sibling Craft app that vendors +/// the same OFL files (PhotoCraft's `assets/fonts`). This makes ordinary local builds look like +/// releases without committing font files here. +fn discover() -> Option { + if let Some(d) = std::env::var_os("CRAFT_FONTS_DIR") { + return Some(PathBuf::from(d)); + } + let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR")?); + let mut dir = manifest.parent().map(Path::to_path_buf); + for _ in 0..4 { + let Some(d) = dir else { break }; + for candidate in [d.join("craft-fonts"), d.join("photocraft").join("assets").join("fonts")] { + if candidate.is_dir() { + return Some(candidate); + } + } + dir = d.parent().map(Path::to_path_buf); + } + None +} + +fn main() { + println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR"); + println!("cargo:rerun-if-changed=build.rs"); + let dir = discover(); + match &dir { + Some(d) => println!("cargo:rerun-if-changed={}", d.display()), + None => println!("cargo:warning=UI fonts: no craft-fonts found (set CRAFT_FONTS_DIR or clone storytold/craft-fonts next to the repo); using the built-in fallback fonts"), + } + let mut code = String::from("// Generated by build.rs (CRAFT_FONTS_DIR font input).\n"); + let mut total = 0u64; + for (file, constant) in FONTS { + let found = dir.as_deref().and_then(|d| find(d, file, 3)); + match found { + Some(p) => { + println!("cargo:rerun-if-changed={}", p.display()); + total += std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0); + code.push_str(&format!("pub const {constant}: Option<&[u8]> = Some(include_bytes!({:?}));\n", p.display().to_string())); + } + None => { + if dir.is_some() { + println!("cargo:warning=CRAFT_FONTS_DIR is set but {file} was not found; using the bundled default"); + } + code.push_str(&format!("pub const {constant}: Option<&[u8]> = None;\n")); + } + } + } + code.push_str(&format!("pub const CRAFT_FONT_BYTES: u64 = {total};\n")); + let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("fonts.rs"); + if let Err(e) = std::fs::write(&out, code) { + println!("cargo:warning=could not write {}: {e}", out.display()); + } +} diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 00000000..4b6c79f5 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,4 @@ +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true +allow-indexing-slicing-in-tests = true diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml new file mode 100644 index 00000000..cbd943a9 --- /dev/null +++ b/crates/cli/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "anicraft-cli" +description = "AniCraft L4: headless CLI and JSON-lines control channel for agents and pipelines" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[[bin]] +name = "anicraft-cli" +path = "src/main.rs" + +[lib] +path = "src/lib.rs" + +[dependencies] +anicraft-doc.workspace = true +anicraft-engine.workspace = true +anicraft-render.workspace = true +anicraft-geom.workspace = true +serde_json.workspace = true + +[lints] +workspace = true diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs new file mode 100644 index 00000000..12aa7c78 --- /dev/null +++ b/crates/cli/src/lib.rs @@ -0,0 +1,373 @@ +//! AniCraft headless front end: argument parsing and the JSON-lines `serve` loop. +//! Every operation goes through the engine's command registry. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use anicraft_engine::{Session, commands, format}; +use serde_json::{Value, json}; +use std::io::{BufRead, Write}; +use std::path::PathBuf; +use std::time::Instant; + +pub const USAGE: &str = "\ +AniCraft CLI — headless animation engine + +USAGE: + anicraft-cli info + anicraft-cli render --out [--frame N] [--scale S] + anicraft-cli render-seq --out-dir [--from A] [--to B] [--scale S] + anicraft-cli gif --out [--from A] [--to B] [--scale S] [--overwrite yes] + anicraft-cli commands + anicraft-cli run [--save ] + anicraft-cli exec [] [--save ] + anicraft-cli new --out [--width W] [--height H] [--fps F] + anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release) + anicraft-cli serve [file|--sample] JSON-lines on stdin/stdout: + {\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}} + +Frames on the command line are 1-based, as in the timeline."; + +/// Parsed flags: positional args plus `--key value` pairs. +pub struct Args { + pub positional: Vec, + pub flags: Vec<(String, String)>, +} + +impl Args { + pub fn parse(args: &[String]) -> Result { + let mut positional = Vec::new(); + let mut flags = Vec::new(); + let mut it = args.iter(); + while let Some(a) = it.next() { + if a == "--sample" { + positional.push(a.clone()); + } else if let Some(k) = a.strip_prefix("--") { + let v = it.next().ok_or_else(|| format!("flag --{k} needs a value"))?; + flags.push((k.to_string(), v.clone())); + } else { + positional.push(a.clone()); + } + } + Ok(Args { positional, flags }) + } + pub fn flag(&self, k: &str) -> Option<&str> { + self.flags.iter().rev().find(|(key, _)| key == k).map(|(_, v)| v.as_str()) + } + pub fn num(&self, k: &str) -> Result, String> { + self.flag(k).map(|v| v.parse::().map_err(|_| format!("--{k} expects a number, got '{v}'"))).transpose() + } +} + +/// Opens a session from a path or `--sample`. +pub fn open_session(src: Option<&str>) -> Result { + match src { + None => Ok(Session::default()), + Some("--sample") => Ok(Session::new(anicraft_doc::sample::demo())), + Some(p) => { + let doc = format::load(std::path::Path::new(p)).map_err(|e| format!("{p}: {e}"))?; + let mut s = Session::new(doc); + s.path = Some(PathBuf::from(p)); + Ok(s) + } + } +} + +fn exec(s: &mut Session, id: &str, params: &Value) -> Result { + s.execute(id, params).map_err(|e| format!("{id}: {e}")) +} + +fn one_based(a: &Args, k: &str) -> Result, String> { + match a.num::(k)? { + Some(0) => Err(format!("--{k} is 1-based; the first frame is 1")), + Some(n) => Ok(Some(n - 1)), + None => Ok(None), + } +} + +/// Runs the CLI; returns the text to print on success. +pub fn run(argv: &[String]) -> Result { + let Some((cmd, rest)) = argv.split_first() else { return Ok(USAGE.to_string()) }; + let a = Args::parse(rest)?; + let src = a.positional.first().map(String::as_str); + match cmd.as_str() { + "help" | "--help" | "-h" => Ok(USAGE.to_string()), + "commands" => { + let list: Vec = commands().iter().map(|c| c.to_json()).collect(); + 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")?))?; + 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 out = a.flag("out").ok_or("render needs --out ")?; + let mut p = json!({"path": out, "frame": one_based(&a, "frame")?.unwrap_or(0)}); + if let Some(sc) = a.num::("scale")? { + p["scale"] = json!(sc); + } + 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 dir = a.flag("out-dir").ok_or("render-seq needs --out-dir ")?; + let mut p = json!({"dir": dir}); + if let Some(f) = one_based(&a, "from")? { + p["from"] = json!(f); + } + if let Some(t) = one_based(&a, "to")? { + p["to"] = json!(t); + } + if let Some(sc) = a.num::("scale")? { + p["scale"] = json!(sc); + } + 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 out = a.flag("out").ok_or("gif needs --out ")?; + let mut p = json!({"path": out}); + if let Some(f) = one_based(&a, "from")? { + p["from"] = json!(f); + } + if let Some(t) = one_based(&a, "to")? { + p["to"] = json!(t); + } + if let Some(sc) = a.num::("scale")? { + p["scale"] = json!(sc); + } + if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") { + p["confirm"] = json!(true); + } + exec(&mut s, "file.export_gif", &p).map(|v| v.to_string()) + } + "new" => { + let mut s = Session::default(); + let out = a.flag("out").ok_or("new needs --out ")?; + let mut p = json!({}); + for k in ["width", "height"] { + if let Some(v) = a.num::(k)? { + p[k] = json!(v); + } + } + if let Some(v) = a.num::("fps")? { + p["fps"] = json!(v); + } + exec(&mut s, "file.new", &p)?; + 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 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}"))?, + None => json!({}), + }; + let v = exec(&mut s, id, ¶ms)?; + if let Some(out) = a.flag("save") { + exec(&mut s, "file.save", &json!({"path": out}))?; + } + Ok(v.to_string()) + } + "run" => { + let mut s = open_session(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. + let steps: Vec = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?; + let mut results = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let id = step.get("cmd").and_then(Value::as_str).ok_or_else(|| format!("step {}: missing \"cmd\"", i + 1))?; + let params = step.get("params").cloned().unwrap_or_else(|| json!({})); + results.push(exec(&mut s, id, ¶ms).map_err(|e| format!("step {}: {e}", i + 1))?); + } + if let Some(out) = a.flag("save") { + exec(&mut s, "file.save", &json!({"path": out}))?; + } + serde_json::to_string_pretty(&results).map_err(|e| e.to_string()) + } + "bench" => bench(&a), + "serve" => { + let mut s = open_session(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()) + } + other => Err(format!("unknown subcommand '{other}'\n\n{USAGE}")), + } +} + +fn avg_ms(n: u32, mut f: impl FnMut(u32)) -> f64 { + let t = Instant::now(); + for i in 0..n { + f(i); + } + t.elapsed().as_secs_f64() * 1000.0 / f64::from(n.max(1)) +} + +fn round(v: f64) -> f64 { + (v * 1000.0).round() / 1000.0 +} + +/// Performance probe on a generated stress document. Run in release for meaningful numbers: +/// `cargo run --release -p anicraft-cli -- bench`. +pub fn bench(a: &Args) -> Result { + use anicraft_doc::{evaluate, sample}; + use anicraft_engine::history::document_bytes; + use anicraft_render::{View, render}; + + let layers = a.num::("layers")?.unwrap_or(50); + let shapes = a.num::("shapes")?.unwrap_or(200); + let frames = a.num::("frames")?.unwrap_or(240); + let t = Instant::now(); + let doc = sample::stress(layers, shapes, frames); + let build_ms = t.elapsed().as_secs_f64() * 1000.0; + let instances: usize = doc.timeline.layers.iter().flat_map(|l| l.keyframes.iter()).map(|k| k.elements.len()).sum(); + + let mut json_text = String::new(); + let save_ms = avg_ms(1, |_| json_text = format::to_json(&doc).unwrap_or_default()); + let load_ms = avg_ms(1, |_| { + let _ = format::from_json(&json_text); + }); + + let eval_ms = avg_ms(48, |i| { + let _ = evaluate(&doc, (i * 5) % frames.max(1)); + }); + let view = View::stage(&doc, 1.0); + let mut drawn = 0; + let render_ms = avg_ms(12, |i| { + if let Ok((_, st)) = render(&evaluate(&doc, (i * 20) % frames.max(1)), &view) { + drawn = st.drawn; + } + }); + // 400% zoom on the stage centre: most shapes are off-screen and culled. + let zoomed = View { transform: anicraft_geom::Affine::translate(-2880.0, -1620.0).mul(&anicraft_geom::Affine::scale(4.0, 4.0)), ..view }; + let mut culled = 0; + let zoom_ms = avg_ms(12, |i| { + if let Ok((_, st)) = render(&evaluate(&doc, (i * 20) % frames.max(1)), &zoomed) { + culled = st.culled; + } + }); + let clone_us = avg_ms(1000, |_| { + let _ = doc.clone(); + }) * 1000.0; + + let mut s = Session::new(doc); + let _ = s.execute("layer.select", &json!({"index": 0})); + s.set_frame(7); + let first = s.visible_elements().first().map(|e| e.id.0); + if let Some(id) = first { + let _ = s.execute("element.select", &json!({"ids": [id]})); + } + let edit_ms = avg_ms(100, |_| { + let _ = s.execute("element.translate", &json!({"dx": 1, "dy": 0})); + }); + let steps = s.history().undo_len().max(1); + let per_step = s.history().bytes() / steps; + let undo_ms = avg_ms(50, |_| { + let _ = s.undo(); + }); + let hit_us = avg_ms(500, |i| { + let _ = s.hit_test(anicraft_geom::Vec2::new((i * 37 % 1920) as f32, (i * 53 % 1080) as f32), 2.0); + }) * 1000.0; + + let out = json!({ + "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)}, + "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, + "snapshot_clone_us": round(clone_us), + "edit_command_ms": round(edit_ms), "undo_bytes_per_step": per_step, "undo_ms": round(undo_ms), + "hit_test_us": round(hit_us), + "threads": std::thread::available_parallelism().map_or(1, |n| n.get()), + "build": if cfg!(debug_assertions) { "debug (use --release for real numbers)" } else { "release" }, + }); + serde_json::to_string_pretty(&out).map_err(|e| e.to_string()) +} + +/// Answers one JSON request. +pub fn handle_request(s: &mut Session, line: &str) -> Value { + // Windows shells often prefix piped UTF-8 with a byte-order mark. + let line = line.trim_start_matches('\u{feff}'); + let req: Value = match serde_json::from_str(line) { + Ok(v) => v, + Err(e) => return json!({"id": null, "ok": false, "error": format!("invalid JSON: {e}")}), + }; + let id = req.get("id").cloned().unwrap_or(Value::Null); + let Some(cmd) = req.get("cmd").and_then(Value::as_str) else { + return json!({"id": id, "ok": false, "error": "missing \"cmd\""}); + }; + let params = req.get("params").cloned().unwrap_or_else(|| json!({})); + let result = match cmd { + "commands" => Ok(Value::Array(commands().iter().map(|c| c.to_json()).collect())), + _ => s.execute(cmd, ¶ms).map_err(|e| e.to_string()), + }; + match result { + Ok(v) => json!({"id": id, "ok": true, "result": v, "revision": s.revision, "frame": s.frame}), + Err(e) => json!({"id": id, "ok": false, "error": e}), + } +} + +/// JSON-lines loop: one request per line, one response per line. Ends on EOF or `{"cmd":"quit"}`. +pub fn serve(s: &mut Session, input: R, out: &mut W) -> std::io::Result<()> { + writeln!(out, "{}", json!({"ready": true, "app": "AniCraft", "version": env!("CARGO_PKG_VERSION")}))?; + out.flush()?; + for line in input.lines() { + let line = line?; + if line.trim().is_empty() { + continue; + } + if line.contains("\"quit\"") && serde_json::from_str::(&line).ok().and_then(|v| v.get("cmd").cloned()) == Some(json!("quit")) { + writeln!(out, "{}", json!({"ok": true, "bye": true}))?; + break; + } + let resp = handle_request(s, &line); + writeln!(out, "{resp}")?; + out.flush()?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serve_round_trip() { + let mut s = Session::default(); + let input = b"\xef\xbb\xbf{\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":1,\"y\":1,\"w\":5,\"h\":5}}\nnot json\n{\"id\":3,\"cmd\":\"nope\"}\n{\"cmd\":\"quit\"}\n{\"id\":4,\"cmd\":\"edit.undo\"}\n"; + let mut out = Vec::new(); + serve(&mut s, &input[..], &mut out).unwrap(); + let lines: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines[0]["ready"], true); + assert_eq!(lines[1]["ok"], true); + assert_eq!(lines[2]["ok"], false); + assert_eq!(lines[3]["ok"], false); + assert_eq!(lines[4]["bye"], true); + assert_eq!(lines.len(), 5, "nothing runs after quit"); + assert_eq!(s.visible_elements().len(), 1); + } + + #[test] + fn render_sample_to_png() { + let dir = std::env::temp_dir().join(format!("anicraft-cli-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("f.png"); + let argv: Vec = ["render", "--sample", "--frame", "12", "--scale", "0.25", "--out", out.to_str().unwrap()].iter().map(|s| s.to_string()).collect(); + run(&argv).unwrap(); + let bytes = std::fs::read(&out).unwrap(); + assert_eq!(&bytes[1..4], b"PNG"); + assert!(run(&["render".into(), "--sample".into(), "--frame".into(), "0".into(), "--out".into(), "x.png".into()]).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn usage_and_errors() { + assert!(run(&[]).unwrap().contains("USAGE")); + assert!(run(&["bogus".into()]).is_err()); + assert!(run(&["info".into()]).is_err()); + assert!(run(&["commands".into()]).unwrap().contains("timeline.insert_keyframe")); + } +} diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs new file mode 100644 index 00000000..5505eaec --- /dev/null +++ b/crates/cli/src/main.rs @@ -0,0 +1,33 @@ +fn main() { + let argv: Vec = std::env::args().skip(1).collect(); + // `--screenshot` is a desktop-app feature: hand over to the `anicraft` binary next to us. + if argv.iter().any(|a| a == "--screenshot") { + std::process::exit(delegate_to_desktop(&argv)); + } + match anicraft_cli::run(&argv) { + Ok(out) => { + if !out.is_empty() { + println!("{out}"); + } + } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } + } +} + +fn delegate_to_desktop(argv: &[String]) -> i32 { + let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join(format!("anicraft{}", std::env::consts::EXE_SUFFIX)))); + let Some(exe) = exe.filter(|p| p.exists()) else { + eprintln!("error: --screenshot needs the AniCraft desktop app (`anicraft`) next to anicraft-cli; build it with `cargo build`"); + return 1; + }; + match std::process::Command::new(&exe).args(argv).status() { + Ok(s) => s.code().unwrap_or(1), + Err(e) => { + eprintln!("error: could not start {}: {e}", exe.display()); + 1 + } + } +} diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml new file mode 100644 index 00000000..e5672ab4 --- /dev/null +++ b/crates/doc/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "anicraft-doc" +description = "AniCraft L1: document model (stage, timeline, layers, keyframes, symbols) and timeline evaluation" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[dependencies] +anicraft-geom.workspace = true +serde = { workspace = true, features = ["rc"] } + +[dev-dependencies] +serde_json.workspace = true + +[lints] +workspace = true diff --git a/crates/doc/src/easing.rs b/crates/doc/src/easing.rs new file mode 100644 index 00000000..ffd1d8e0 --- /dev/null +++ b/crates/doc/src/easing.rs @@ -0,0 +1,178 @@ +//! Easing curves for tweens. + +use serde::{Deserialize, Serialize}; + +/// Maps linear tween progress `t ∈ [0, 1]` to eased progress. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub enum Easing { + #[default] + Linear, + QuadIn, + QuadOut, + QuadInOut, + CubicIn, + CubicOut, + CubicInOut, + /// The traditional single-slider ease: −100 (ease in) … 0 (linear) … +100 (ease out). + Classic(f32), + /// CSS-style cubic Bézier through (0,0), (x1,y1), (x2,y2), (1,1). + CubicBezier(f32, f32, f32, f32), +} + +impl Easing { + /// Presets shown in the UI, in menu order. + pub const PRESETS: [(&'static str, Easing); 8] = [ + ("Linear", Easing::Linear), + ("Ease in (quad)", Easing::QuadIn), + ("Ease out (quad)", Easing::QuadOut), + ("Ease in-out (quad)", Easing::QuadInOut), + ("Ease in (cubic)", Easing::CubicIn), + ("Ease out (cubic)", Easing::CubicOut), + ("Ease in-out (cubic)", Easing::CubicInOut), + ("Smooth (bezier)", Easing::CubicBezier(0.25, 0.1, 0.25, 1.0)), + ]; + + pub fn label(&self) -> String { + match self { + Easing::Classic(s) => format!("Classic {s:+.0}"), + Easing::CubicBezier(a, b, c, d) => { + Easing::PRESETS.iter().find(|(_, e)| e == self).map_or_else(|| format!("Bezier({a:.2}, {b:.2}, {c:.2}, {d:.2})"), |(n, _)| (*n).to_string()) + } + other => Easing::PRESETS.iter().find(|(_, e)| e == other).map_or("Custom", |(n, _)| n).to_string(), + } + } + + pub fn apply(&self, t: f32) -> f32 { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + match *self { + Easing::Linear => t, + Easing::QuadIn => t * t, + Easing::QuadOut => t * (2.0 - t), + Easing::QuadInOut => { + if t < 0.5 { + 2.0 * t * t + } else { + -1.0 + (4.0 - 2.0 * t) * t + } + } + Easing::CubicIn => t * t * t, + Easing::CubicOut => { + let u = t - 1.0; + u * u * u + 1.0 + } + Easing::CubicInOut => { + if t < 0.5 { + 4.0 * t * t * t + } else { + let u = 2.0 * t - 2.0; + 0.5 * u * u * u + 1.0 + } + } + Easing::Classic(strength) => { + // Quadratic Bézier with the middle control point moved by `strength`. + let s = if strength.is_finite() { strength.clamp(-100.0, 100.0) / 100.0 } else { 0.0 }; + let c = 0.5 + 0.5 * s; // y of control point at x = 0.5 + 2.0 * (1.0 - t) * t * c + t * t + } + Easing::CubicBezier(x1, y1, x2, y2) => cubic_bezier(t, x1, y1, x2, y2), + } + } +} + +fn cubic_bezier(x: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 { + if ![x1, y1, x2, y2].iter().all(|v| v.is_finite()) { + return x; + } + // x control points must stay in [0, 1] so x(t) is monotonic. + let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0)); + let bez = |t: f32, p1: f32, p2: f32| { + let mt = 1.0 - t; + 3.0 * mt * mt * t * p1 + 3.0 * mt * t * t * p2 + t * t * t + }; + let dbez = |t: f32, p1: f32, p2: f32| { + let mt = 1.0 - t; + 3.0 * mt * mt * p1 + 6.0 * mt * t * (p2 - p1) + 3.0 * t * t * (1.0 - p2) + }; + // Newton, then bisection as a fallback. + let mut t = x; + for _ in 0..8 { + let err = bez(t, x1, x2) - x; + if err.abs() < 1e-6 { + return bez(t, y1, y2); + } + let d = dbez(t, x1, x2); + if d.abs() < 1e-6 { + break; + } + t = (t - err / d).clamp(0.0, 1.0); + } + let (mut lo, mut hi) = (0.0f32, 1.0f32); + t = x; + for _ in 0..40 { + let v = bez(t, x1, x2); + if (v - x).abs() < 1e-6 { + break; + } + if v < x { + lo = t; + } else { + hi = t; + } + t = 0.5 * (lo + hi); + } + bez(t, y1, y2) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ALL: [Easing; 10] = [ + Easing::Linear, + Easing::QuadIn, + Easing::QuadOut, + Easing::QuadInOut, + Easing::CubicIn, + Easing::CubicOut, + Easing::CubicInOut, + Easing::Classic(-60.0), + Easing::Classic(100.0), + Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), + ]; + + #[test] + fn endpoints_fixed() { + for e in ALL { + assert!(e.apply(0.0).abs() < 1e-4, "{e:?}"); + assert!((e.apply(1.0) - 1.0).abs() < 1e-4, "{e:?}"); + } + } + + #[test] + fn monotonic() { + for e in ALL { + let mut prev = -1e-6; + for i in 0..=100 { + let v = e.apply(i as f32 / 100.0); + assert!(v >= prev - 1e-4, "{e:?} at {i}"); + prev = v; + } + } + } + + #[test] + fn hostile_input_is_clamped() { + assert_eq!(Easing::Linear.apply(f32::NAN), 0.0); + assert_eq!(Easing::QuadIn.apply(5.0), 1.0); + assert!(Easing::CubicBezier(f32::NAN, 0.0, 1.0, 1.0).apply(0.5).is_finite()); + assert!(Easing::Classic(f32::INFINITY).apply(0.5).is_finite()); + } + + #[test] + fn ease_in_is_slow_at_start() { + assert!(Easing::QuadIn.apply(0.25) < 0.25); + assert!(Easing::QuadOut.apply(0.25) > 0.25); + assert!(Easing::Classic(-100.0).apply(0.25) < 0.25); + assert!(Easing::Classic(100.0).apply(0.25) > 0.25); + } +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs new file mode 100644 index 00000000..d76b40ba --- /dev/null +++ b/crates/doc/src/eval.rs @@ -0,0 +1,186 @@ +//! Timeline evaluation: `(document, frame) -> DisplayList`. Pure, deterministic, no caching. + +use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, Timeline}; +use anicraft_geom::{Affine, FillRule, Path}; +use std::borrow::Cow; +use std::sync::Arc; + +/// Symbols nested deeper than this are not drawn (guards cyclic libraries). +pub const MAX_SYMBOL_DEPTH: usize = 32; + +/// One shape to draw, fully resolved to stage space. +#[derive(Clone, Debug)] +pub struct DisplayItem { + pub path: Arc, + /// Local → stage transform. + pub transform: Affine, + pub fill: Option, + pub stroke: Option, + pub fill_rule: FillRule, + pub color: ColorEffect, + /// The top-level layer and element this item came from (for picking). + pub layer: LayerId, + pub element: ElementId, + /// Outline-only display (layer outline mode). + pub outline: Option, + /// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]). + pub clip: Option, + /// Mask artwork: not drawn; its fill area (strokes and opacity ignored) forms this clip. + pub masks: Option, +} + +/// Back-to-front list of shapes. +#[derive(Clone, Debug, Default)] +pub struct DisplayList { + pub items: Vec, + /// One entry per clip: the enclosing clip it is intersected with. A parent always has a + /// lower index than its children. A clip with no mask artwork hides everything in it. + pub clip_parents: Vec>, +} + +impl DisplayList { + /// Whether stage point `p` lies inside clip `clip` (and every clip enclosing it): the test + /// that keeps masked-away parts of a shape from being picked. + pub fn clip_contains(&self, clip: u32, p: anicraft_geom::Vec2) -> bool { + let mut c = Some(clip); + for _ in 0..self.clip_parents.len() { + let Some(id) = c else { return true }; + if !self.items.iter().any(|i| i.masks == Some(id) && i.fill.is_some() && i.path.contains(p, &i.transform, i.fill_rule)) { + return false; + } + c = self.clip_parents.get(id as usize).copied().flatten().filter(|&q| q < id); + } + c.is_none() + } + + /// Appends `other`'s items (drawn on top), renumbering its clips. + pub fn append(&mut self, other: DisplayList) { + let base = self.clip_parents.len() as u32; + let shift = |c: Option| c.map(|c| c + base); + self.clip_parents.extend(other.clip_parents.into_iter().map(shift)); + self.items.extend(other.items.into_iter().map(|mut i| { + i.clip = shift(i.clip); + i.masks = shift(i.masks); + i + })); + } +} + +/// Evaluates the main timeline at `frame` (0-based). +pub fn evaluate(doc: &Document, frame: u32) -> DisplayList { + let mut out = DisplayList::default(); + let cx = Ctx { xf: Affine::IDENTITY, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None }; + eval_timeline(doc, &doc.timeline, frame, &cx, &mut out); + out +} + +/// Elements of `layer` as they appear at `frame`, with tweens applied, plus the start frame of +/// the covering keyframe. `None` when the frame is empty on this layer. +pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_, [Arc]>)> { + let idx = layer.keyframe_index_at(frame)?; + let kf = layer.keyframes.get(idx)?; + 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 { + return Some((kf.start, Cow::Borrowed(&kf.elements))); + } + let t = tween.easing.apply((frame - kf.start) as f32 / kf.duration.max(1) as f32); + let els = kf.elements.iter().enumerate().map(|(i, a)| next.elements.get(i).and_then(|b| interpolate(a, b, t)).map_or_else(|| a.clone(), Arc::new)).collect(); + Some((kf.start, Cow::Owned(els))) +} + +/// Interpolates two compatible elements; `None` when they cannot tween. +fn interpolate(a: &Element, b: &Element, t: f32) -> Option { + let kind = match (&a.kind, &b.kind) { + (ElementKind::Shape(sa), ElementKind::Shape(sb)) => { + let path = if Arc::ptr_eq(&sa.path, &sb.path) { sa.path.clone() } else { sa.path.lerp(&sb.path, t).map(Arc::new).unwrap_or_else(|| sa.path.clone()) }; + let fill = match (&sa.fill, &sb.fill) { + (Some(x), Some(y)) => Some(x.lerp(y, t)), + (x, _) => x.clone(), + }; + let stroke = match (sa.stroke, sb.stroke) { + (Some(x), Some(y)) => Some(Stroke { color: x.color.lerp(y.color, t), width: anicraft_geom::lerp(x.width, y.width, t) }), + (x, _) => x, + }; + ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule }) + } + (ElementKind::Symbol { symbol: s1, .. }, ElementKind::Symbol { symbol: s2, .. }) if s1 == s2 => a.kind.clone(), + _ => return None, + }; + let transform = a.transform.decompose().lerp(&b.transform.decompose(), t).compose(); + Some(Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, t), kind }) +} + +/// What a timeline is evaluated inside of. +#[derive(Clone, Copy)] +struct Ctx { + /// Local → stage transform and colour effect of the enclosing instance. + xf: Affine, + color: ColorEffect, + depth: usize, + /// The top-level layer and element everything inside belongs to (for picking). + root: Option<(LayerId, ElementId)>, + outline: Option, + /// The clip everything inside is drawn within. + clip: Option, + /// Set while evaluating mask artwork: everything inside forms this clip. + masks: Option, +} + +fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut DisplayList) { + if cx.depth > MAX_SYMBOL_DEPTH { + return; + } + // One clip per visible mask layer, nested in the enclosing clip. Inside mask artwork every + // layer is artwork, so masks there do not mask again. A hidden mask layer masks nothing. + let mut clips: Vec<(LayerId, u32)> = Vec::new(); + if cx.masks.is_none() { + for layer in tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible) { + clips.push((layer.id, out.clip_parents.len() as u32)); + out.clip_parents.push(cx.clip); + } + } + let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c); + for layer in tl.layers.iter().rev() { + if !layer.visible || layer.kind == LayerKind::Guide { + continue; + } + let (clip, masks) = match (cx.masks, layer.kind) { + (Some(_), _) => (cx.clip, cx.masks), + (None, LayerKind::Mask) => (cx.clip, clip_of(layer.id)), + (None, _) => (layer.parent.and_then(clip_of).or(cx.clip), None), + }; + let Some((kf_start, elements)) = evaluate_layer_elements(layer, frame) else { continue }; + let layer_outline = cx.outline.or(if layer.outline { Some(layer.color) } else { None }); + for el in elements.iter() { + let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id)); + let xf = cx.xf.mul(&el.transform); + let color = cx.color.concat(&el.color); + match &el.kind { + ElementKind::Shape(s) => out.items.push(DisplayItem { + path: s.path.clone(), + transform: xf, + fill: s.fill.clone(), + stroke: s.stroke, + fill_rule: s.fill_rule, + color, + layer: root_layer, + element: root_el, + outline: layer_outline, + clip, + masks, + }), + ElementKind::Symbol { symbol, loop_mode, first_frame } => { + let Some(sym) = doc.symbol(*symbol) else { continue }; + let local = loop_mode.local_frame(frame.saturating_sub(kf_start), *first_frame, sym.timeline.frame_count()); + let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks }; + eval_timeline(doc, &sym.timeline, local, &inner, out); + } + } + } + } +} + +#[cfg(test)] +#[path = "eval_tests.rs"] +mod tests; diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs new file mode 100644 index 00000000..fb66f8ef --- /dev/null +++ b/crates/doc/src/eval_tests.rs @@ -0,0 +1,200 @@ +use super::*; +use crate::{Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween}; + +fn shape_el(id: u64, x: f32) -> Element { + Element { + id: ElementId(id), + name: String::new(), + transform: Affine::translate(x, 0.0), + color: ColorEffect::default(), + kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK))), + } +} + +fn layer0(d: &mut Document) -> &mut Layer { + Arc::make_mut(&mut d.timeline.layers[0]) +} + +fn push(layer: &mut Layer, kf: usize, e: Element) { + layer.keyframe_mut(kf).unwrap().elements.push(Arc::new(e)); +} + +fn tween_doc(easing: Easing) -> Document { + let mut d = Document::default(); + let mut k0 = Keyframe::new(0, 10); + k0.elements.push(Arc::new(shape_el(10, 0.0))); + k0.tween = Some(Tween { easing }); + let mut k1 = Keyframe::new(10, 1); + k1.elements.push(Arc::new(shape_el(10, 100.0))); + layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + d +} + +#[test] +fn linear_tween_interpolates_translation() { + let d = tween_doc(Easing::Linear); + let x = |f| evaluate(&d, f).items[0].transform.translation().x; + assert_eq!(x(0), 0.0); + assert!((x(5) - 50.0).abs() < 1e-3); + assert_eq!(x(10), 100.0); +} + +#[test] +fn eased_tween_differs_from_linear() { + let d = tween_doc(Easing::QuadIn); + let x5 = evaluate(&d, 5).items[0].transform.translation().x; + assert!((x5 - 25.0).abs() < 1e-3); +} + +#[test] +fn static_frames_share_elements_with_the_document() { + let d = tween_doc(Easing::Linear); + let (_, els) = evaluate_layer_elements(&d.timeline.layers[0], 10).unwrap(); + assert!(matches!(els, Cow::Borrowed(_)), "a non-tweened frame must not copy elements"); +} + +#[test] +fn hidden_and_guide_layers_are_skipped() { + let mut d = tween_doc(Easing::Linear); + layer0(&mut d).visible = false; + assert!(evaluate(&d, 0).items.is_empty()); + layer0(&mut d).visible = true; + layer0(&mut d).kind = LayerKind::Guide; + assert!(evaluate(&d, 0).items.is_empty()); +} + +#[test] +fn nested_symbols_compose_transforms_and_cycles_terminate() { + let mut d = Document::default(); + let sid = SymbolId(99); + // A symbol that contains a shape and an instance of itself: a cycle. + let mut tl = Timeline::default(); + let mut layer = Layer::new(LayerId(50), "s"); + push(&mut layer, 0, shape_el(51, 0.0)); + push( + &mut layer, + 0, + Element { + id: ElementId(52), + name: String::new(), + transform: Affine::translate(1.0, 0.0), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0 }, + }, + ); + tl.layers.push(Arc::new(layer)); + d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, timeline: tl })); + push( + layer0(&mut d), + 0, + Element { + id: ElementId(60), + name: String::new(), + transform: Affine::translate(100.0, 0.0), + color: ColorEffect { alpha: 0.5, ..Default::default() }, + kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0 }, + }, + ); + let dl = evaluate(&d, 0); + assert_eq!(dl.items.len(), MAX_SYMBOL_DEPTH); + assert_eq!(dl.items[0].transform.translation().x, 100.0); + assert_eq!(dl.items[0].color.alpha, 0.5); + assert!(dl.items.iter().all(|i| i.element == ElementId(60))); +} + +/// Layers top to bottom: mask (id 1), masked (2), masked (3), plain (4). +fn mask_doc() -> Document { + let mut d = Document { timeline: Timeline::default(), ..Document::default() }; + for (id, kind, parent) in [(1, LayerKind::Mask, None), (2, LayerKind::Normal, Some(1)), (3, LayerKind::Normal, Some(1)), (4, LayerKind::Normal, None)] { + let mut l = Layer::new(LayerId(id), format!("L{id}")); + l.kind = kind; + l.parent = parent.map(LayerId); + push(&mut l, 0, shape_el(10 + id, 0.0)); + d.timeline.layers.push(Arc::new(l)); + } + d +} + +#[test] +fn mask_layers_clip_the_layers_they_mask() { + let d = mask_doc(); + let dl = evaluate(&d, 0); + assert_eq!(dl.clip_parents, vec![None]); + let by = |e: u64| dl.items.iter().find(|i| i.element == ElementId(e)).unwrap(); + assert_eq!((by(14).clip, by(14).masks), (None, None), "unmasked layer"); + assert_eq!((by(13).clip, by(12).clip), (Some(0), Some(0)), "masked layers"); + assert_eq!(by(11).masks, Some(0), "the mask layer's artwork forms the clip"); + // A hidden mask masks nothing; its layers draw normally. + let mut h = d.clone(); + Arc::make_mut(&mut h.timeline.layers[0]).visible = false; + let dl = evaluate(&h, 0); + assert!(dl.items.iter().all(|i| i.clip.is_none() && i.masks.is_none()) && dl.items.len() == 3); +} + +#[test] +fn masks_inside_symbols_nest_in_the_instance_clip() { + // The main timeline's masked layer holds an instance of a symbol that has its own mask. + let mut d = mask_doc(); + let sid = SymbolId(99); + d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, timeline: mask_doc().timeline })); + let inst = Element { + id: ElementId(60), + name: String::new(), + transform: Affine::IDENTITY, + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0 }, + }; + push(Arc::make_mut(&mut d.timeline.layers[1]), 0, inst); + let dl = evaluate(&d, 0); + assert_eq!(dl.clip_parents, vec![None, Some(0)]); + let inner: Vec<_> = dl.items.iter().filter(|i| i.element == ElementId(60)).map(|i| (i.clip, i.masks)).collect(); + // inside: unmasked layer keeps the outer clip; masked layers use the nested clip. + assert_eq!(inner, vec![(Some(0), None), (Some(1), None), (Some(1), None), (Some(0), Some(1))]); +} + +#[test] +fn appending_lists_renumbers_clips() { + let d = mask_doc(); + let mut a = evaluate(&d, 0); + a.append(evaluate(&d, 0)); + assert_eq!(a.clip_parents, vec![None, None]); + let second = &a.items[4..]; + assert!(second.iter().all(|i| i.clip.is_none_or(|c| c == 1) && i.masks.is_none_or(|c| c == 1))); + assert!(second.iter().any(|i| i.masks == Some(1))); +} + +#[test] +fn mask_links_must_stay_directly_under_their_mask() { + let mut d = mask_doc(); + d.timeline.repair_masks(); + assert_eq!(d.timeline.layers.iter().map(|l| l.parent).collect::>(), vec![None, Some(LayerId(1)), Some(LayerId(1)), None]); + assert_eq!(d.timeline.group_range(0), 0..3); + assert_eq!(d.timeline.mask_above(3), Some(LayerId(1)), "a layer under the group would join it"); + // The plain layer moved between the masked ones breaks the run: the lower one lets go. + d.timeline.layers.swap(2, 3); + d.timeline.repair_masks(); + assert_eq!(d.timeline.layers[3].parent, None); + assert_eq!(d.timeline.layers[1].parent, Some(LayerId(1))); + // A masked layer above its mask, or a mask that is no longer a mask, lets go too. + let mut e = mask_doc(); + e.timeline.layers.swap(0, 1); + e.timeline.repair_masks(); + assert_eq!(e.timeline.layers[0].parent, None); + assert_eq!(e.timeline.layers[2].parent, Some(LayerId(1)), "still directly under the mask"); + let mut f = mask_doc(); + Arc::make_mut(&mut f.timeline.layers[0]).kind = LayerKind::Normal; + f.sanitize(); + assert!(f.timeline.layers.iter().all(|l| l.parent.is_none())); +} + +#[test] +fn layer_order_is_back_to_front() { + let mut d = Document::default(); + push(layer0(&mut d), 0, shape_el(1, 0.0)); + let mut bottom = Layer::new(LayerId(7), "bottom"); + push(&mut bottom, 0, shape_el(2, 0.0)); + d.timeline.layers.push(Arc::new(bottom)); + let dl = evaluate(&d, 0); + assert_eq!(dl.items[0].element, ElementId(2)); + assert_eq!(dl.items[1].element, ElementId(1)); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs new file mode 100644 index 00000000..e9c782ce --- /dev/null +++ b/crates/doc/src/lib.rs @@ -0,0 +1,725 @@ +//! AniCraft document model (layer L1). +//! +//! A document is plain data. Time is a function: [`evaluate`] turns a document and a frame into +//! a flat [`DisplayList`], which renderers draw. Nothing here mutates during playback. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod easing; +mod eval; +pub mod path_table; +pub mod sample; + +pub use easing::Easing; +pub use eval::{DisplayItem, DisplayList, MAX_SYMBOL_DEPTH, evaluate, evaluate_layer_elements}; + +use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +/// Straight-alpha sRGB colour, components in `0..=1`. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Rgba { + pub r: f32, + pub g: f32, + pub b: f32, + pub a: f32, +} + +impl Rgba { + pub const BLACK: Rgba = Rgba::new(0.0, 0.0, 0.0, 1.0); + pub const WHITE: Rgba = Rgba::new(1.0, 1.0, 1.0, 1.0); + pub const TRANSPARENT: Rgba = Rgba::new(0.0, 0.0, 0.0, 0.0); + + pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self { + Rgba { r, g, b, a } + } + /// From `0xRRGGBB`. + pub fn hex(rgb: u32) -> Self { + Rgba::new(((rgb >> 16) & 0xff) as f32 / 255.0, ((rgb >> 8) & 0xff) as f32 / 255.0, (rgb & 0xff) as f32 / 255.0, 1.0) + } + pub fn with_alpha(self, a: f32) -> Self { + Rgba { a, ..self } + } + pub fn lerp(self, o: Rgba, t: f32) -> Rgba { + use anicraft_geom::lerp; + Rgba::new(lerp(self.r, o.r, t), lerp(self.g, o.g, t), lerp(self.b, o.b, t), lerp(self.a, o.a, t)) + } + /// Clamped to `0..=1`, NaN mapped to 0. + pub fn sanitized(self) -> Rgba { + let c = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + Rgba::new(c(self.r), c(self.g), c(self.b), c(self.a)) + } + pub fn to_hex(self) -> String { + let s = self.sanitized(); + let b = |v: f32| (v * 255.0).round() as u8; + format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b)) + } + /// Parses `#rrggbb`, `rrggbb` or `#rrggbbaa`. + pub fn parse_hex(s: &str) -> Option { + let h = s.trim().trim_start_matches('#'); + if !h.is_ascii() || (h.len() != 6 && h.len() != 8) { + return None; + } + let byte = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| v as f32 / 255.0); + let a = if h.len() == 8 { byte(6)? } else { 1.0 }; + Some(Rgba::new(byte(0)?, byte(2)?, byte(4)?, a)) + } +} + +/// A gradient colour stop. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct GradientStop { + pub offset: f32, + pub color: Rgba, +} + +/// How a region is painted. Gradient geometry is in the element's local space. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum Paint { + Solid(Rgba), + Linear { start: Vec2, end: Vec2, stops: Vec }, + Radial { center: Vec2, radius: f32, stops: Vec }, +} + +impl Paint { + /// A representative colour (first stop for gradients) for swatches and the properties panel. + pub fn primary_color(&self) -> Rgba { + match self { + Paint::Solid(c) => *c, + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => stops.first().map_or(Rgba::BLACK, |s| s.color), + } + } + + pub fn lerp(&self, o: &Paint, t: f32) -> Paint { + let lerp_stops = |a: &[GradientStop], b: &[GradientStop]| -> Option> { + (a.len() == b.len()).then(|| { + a.iter().zip(b).map(|(x, y)| GradientStop { offset: anicraft_geom::lerp(x.offset, y.offset, t), color: x.color.lerp(y.color, t) }).collect() + }) + }; + match (self, o) { + (Paint::Solid(a), Paint::Solid(b)) => Paint::Solid(a.lerp(*b, t)), + (Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => match lerp_stops(a, b) { + Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops }, + None => self.clone(), + }, + (Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => match lerp_stops(a, b) { + Some(stops) => Paint::Radial { center: c0.lerp(*c1, t), radius: anicraft_geom::lerp(*r0, *r1, t), stops }, + None => self.clone(), + }, + _ => self.clone(), + } + } +} + +/// Stroke style. M0: round joins and caps. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Stroke { + pub color: Rgba, + pub width: f32, +} + +/// `Arc` equality that short-circuits on shared pointers. Unchanged subtrees of two document +/// versions share their `Arc`s, so comparing versions costs O(changed), not O(document). +pub fn arc_eq(a: &Arc, b: &Arc) -> bool { + Arc::ptr_eq(a, b) || **a == **b +} + +/// [`arc_eq`] over slices. +pub fn arcs_eq(a: &[Arc], b: &[Arc]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| arc_eq(x, y)) +} + +/// Vector shape content. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Shape { + #[serde(with = "path_table")] + pub path: Arc, + #[serde(default)] + pub fill: Option, + #[serde(default)] + pub stroke: Option, + #[serde(default)] + pub fill_rule: FillRule, +} + +impl PartialEq for Shape { + fn eq(&self, o: &Shape) -> bool { + arc_eq(&self.path, &o.path) && self.fill == o.fill && self.stroke == o.stroke && self.fill_rule == o.fill_rule + } +} + +impl Shape { + pub fn filled(path: Path, fill: Paint) -> Shape { + Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero } + } + pub fn with_stroke(mut self, color: Rgba, width: f32) -> Shape { + self.stroke = Some(Stroke { color, width }); + self + } +} + +/// How a graphic symbol instance picks its internal frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum LoopMode { + #[default] + Loop, + PlayOnce, + SingleFrame, +} + +impl LoopMode { + /// Local frame for `offset` frames into the instance's span. + pub fn local_frame(&self, offset: u32, first: u32, len: u32) -> u32 { + let len = len.max(1); + match self { + LoopMode::Loop => first.saturating_add(offset) % len, + LoopMode::PlayOnce => first.saturating_add(offset).min(len - 1), + LoopMode::SingleFrame => first.min(len - 1), + } + } +} + +/// Unique id of a symbol in the library. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct SymbolId(pub u64); + +/// Unique id of an element instance within a document. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct ElementId(pub u64); + +/// Unique id of a layer within a document. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct LayerId(pub u64); + +/// What an element draws. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum ElementKind { + Shape(Shape), + Symbol { + symbol: SymbolId, + #[serde(default)] + loop_mode: LoopMode, + #[serde(default)] + first_frame: u32, + }, +} + +/// Colour effect applied to an element and everything inside it. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ColorEffect { + /// Alpha multiplier `0..=1`. + pub alpha: f32, + /// Tint colour mixed in by `tint_amount`. + pub tint: Rgba, + pub tint_amount: f32, +} + +impl Default for ColorEffect { + fn default() -> Self { + ColorEffect { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0 } + } +} + +impl ColorEffect { + /// Effect of `inner` nested inside `self`. + pub fn concat(&self, inner: &ColorEffect) -> ColorEffect { + // Tints compose by keeping the stronger one; alpha multiplies. + let (tint, amount) = if inner.tint_amount >= self.tint_amount { (inner.tint, inner.tint_amount) } else { (self.tint, self.tint_amount) }; + ColorEffect { alpha: self.alpha * inner.alpha, tint, tint_amount: amount } + } + pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect { + ColorEffect { + alpha: anicraft_geom::lerp(self.alpha, o.alpha, t), + tint: self.tint.lerp(o.tint, t), + tint_amount: anicraft_geom::lerp(self.tint_amount, o.tint_amount, t), + } + } + pub fn apply(&self, c: Rgba) -> Rgba { + let k = self.tint_amount.clamp(0.0, 1.0); + let mut out = c.lerp(self.tint.with_alpha(c.a), k); + out.a = c.a * self.alpha.clamp(0.0, 1.0); + out + } +} + +/// An instance on a keyframe. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Element { + pub id: ElementId, + #[serde(default)] + pub name: String, + #[serde(default)] + pub transform: Affine, + #[serde(default)] + pub color: ColorEffect, + pub kind: ElementKind, +} + +impl Element { + /// Local-space bounds (control-point bounds for shapes, `None` for symbols). + pub fn local_bounds(&self, doc: &Document) -> Rect { + element_bounds(doc, self, &Affine::IDENTITY, 0) + } + /// Bounds in the parent's space. + pub fn bounds(&self, doc: &Document) -> Rect { + element_bounds(doc, self, &self.transform, 0) + } +} + +fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize) -> Rect { + if depth > MAX_SYMBOL_DEPTH { + return Rect::EMPTY; + } + match &el.kind { + ElementKind::Shape(s) => { + let pad = s.stroke.map_or(0.0, |st| st.width * 0.5); + s.path.bounds().inflate(pad).transformed(xf) + } + ElementKind::Symbol { symbol, .. } => { + let Some(sym) = doc.symbol(*symbol) else { return Rect::EMPTY }; + let mut r = Rect::EMPTY; + for layer in &sym.timeline.layers { + if let Some(kf) = layer.keyframes.first() { + for child in &kf.elements { + let m = xf.mul(&child.transform); + r = r.union(&element_bounds(doc, child, &m, depth + 1)); + } + } + } + r + } + } +} + +/// A tween from a keyframe to the next one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Tween { + #[serde(default)] + pub easing: Easing, +} + +/// A keyframe and the span of frames it covers. +/// +/// Elements are `Arc`-shared: copying a keyframe (F6), taking an undo snapshot or handing the +/// document to the render thread shares them, and editing one element clones only that element +/// (`Arc::make_mut`), never its siblings. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Keyframe { + /// First frame (0-based). + pub start: u32, + /// Number of frames covered, at least 1. + pub duration: u32, + #[serde(default)] + pub elements: Vec>, + #[serde(default)] + pub tween: Option, + #[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) + } +} + +impl Keyframe { + pub fn new(start: u32, duration: u32) -> Self { + Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: 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> { + self.elements.iter_mut().filter(|e| pick(e.id)).map(Arc::make_mut).collect() + } + pub fn end(&self) -> u32 { + self.start.saturating_add(self.duration.max(1)) + } + pub fn covers(&self, frame: u32) -> bool { + frame >= self.start && frame < self.end() + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum LayerKind { + #[default] + Normal, + /// Authoring aid; never rendered in output. + Guide, + /// Its fills are not drawn: they reveal the layers masked by it (see [`Layer::parent`]). + Mask, +} + +/// A timeline layer. Keyframes are `Arc`-shared (see [`Keyframe`]). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Layer { + pub id: LayerId, + pub name: String, + #[serde(default)] + pub kind: LayerKind, + /// The mask layer this layer is masked by. Masked layers sit directly under their mask, in + /// one unbroken run ([`Timeline::repair_masks`] keeps it so); any other link is dropped. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, + #[serde(default = "yes")] + pub visible: bool, + #[serde(default)] + pub locked: bool, + #[serde(default)] + pub outline: bool, + #[serde(default = "default_layer_color")] + pub color: Rgba, + #[serde(default)] + pub keyframes: Vec>, +} + +impl PartialEq for Layer { + fn eq(&self, o: &Layer) -> bool { + self.id == o.id + && self.name == o.name + && self.kind == o.kind + && self.parent == o.parent + && self.visible == o.visible + && self.locked == o.locked + && self.outline == o.outline + && self.color == o.color + && arcs_eq(&self.keyframes, &o.keyframes) + } +} + +fn yes() -> bool { + true +} +fn default_layer_color() -> Rgba { + Rgba::hex(0x4fa3ff) +} + +impl Layer { + pub fn new(id: LayerId, name: impl Into) -> Self { + Layer { + id, + name: name.into(), + kind: LayerKind::Normal, + parent: None, + visible: true, + locked: false, + outline: false, + color: default_layer_color(), + keyframes: vec![Arc::new(Keyframe::new(0, 1))], + } + } + /// Mutable keyframe `i` (copy-on-write: clones it only if it is shared). + pub fn keyframe_mut(&mut self, i: usize) -> Option<&mut Keyframe> { + self.keyframes.get_mut(i).map(Arc::make_mut) + } + /// Index of the keyframe whose span covers `frame`. + pub fn keyframe_index_at(&self, frame: u32) -> Option { + // keyframes are sorted by start: binary search on start, then check the span. + let idx = self.keyframes.partition_point(|k| k.start <= frame); + let i = idx.checked_sub(1)?; + self.keyframes.get(i).filter(|k| k.covers(frame)).map(|_| i) + } + pub fn keyframe_at(&self, frame: u32) -> Option<&Keyframe> { + self.keyframe_index_at(frame).and_then(|i| self.keyframes.get(i)).map(|k| &**k) + } + /// Index of the keyframe starting exactly at `frame`. + pub fn keyframe_starting_at(&self, frame: u32) -> Option { + self.keyframes.iter().position(|k| k.start == frame) + } + /// One past the last frame with content. + pub fn end_frame(&self) -> u32 { + self.keyframes.last().map_or(0, |k| k.end()) + } + /// 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) { + if !self.keyframes.is_sorted_by_key(|k| k.start) { + self.keyframes.sort_by_key(|k| k.start); + } + self.keyframes.dedup_by_key(|k| k.start); + let n = self.keyframes.len(); + for i in 0..n { + let next_start = self.keyframes.get(i + 1).map(|k| k.start); + let Some(k) = self.keyframes.get(i) else { continue }; + let mut want = k.duration.max(1); + if let Some(ns) = next_start { + want = want.min(ns.saturating_sub(k.start)).max(1); + } + if want != k.duration + && let Some(k) = self.keyframe_mut(i) + { + k.duration = want; + } + } + } +} + +/// An ordered stack of layers. Index 0 is the top layer. Layers are `Arc`-shared. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct Timeline { + pub layers: Vec>, +} + +impl PartialEq for Timeline { + fn eq(&self, o: &Timeline) -> bool { + arcs_eq(&self.layers, &o.layers) + } +} + +impl Timeline { + /// Number of frames (at least 1). + pub fn frame_count(&self) -> u32 { + self.layers.iter().map(|l| l.end_frame()).max().unwrap_or(1).max(1) + } + pub fn layer(&self, id: LayerId) -> Option<&Layer> { + self.layers.iter().find(|l| l.id == id).map(|l| &**l) + } + /// Mutable layer (copy-on-write). + pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> { + self.layers.iter_mut().find(|l| l.id == id).map(Arc::make_mut) + } + + /// The mask that a layer placed at `index` would join: the mask directly above it, or the + /// mask of the masked layer directly above it. + pub fn mask_above(&self, index: usize) -> Option { + let above = self.layers.get(index.checked_sub(1)?)?; + match above.kind { + LayerKind::Mask => Some(above.id), + _ => above.parent, + } + } + + /// Indices `i..j` of the layer at `i` plus, for a mask layer, the masked layers under it. + pub fn group_range(&self, i: usize) -> std::ops::Range { + let Some(l) = self.layers.get(i) else { return i..i }; + let mut j = i + 1; + if l.kind == LayerKind::Mask { + while self.layers.get(j).is_some_and(|m| m.parent == Some(l.id)) { + j += 1; + } + } + i..j + } + + /// Drops mask links that no longer hold: a masked layer must be a normal layer directly + /// under its mask layer or under another layer masked by it. Touches only layers that change. + pub fn repair_masks(&mut self) { + for i in 0..self.layers.len() { + let Some(l) = self.layers.get(i) else { continue }; + let Some(p) = l.parent else { continue }; + // (Layers above are already repaired, so `mask_above` sees valid links.) + let holds = l.kind == LayerKind::Normal && self.mask_above(i) == Some(p); + if !holds && let Some(l) = self.layers.get_mut(i) + { + Arc::make_mut(l).parent = None; + } + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SymbolKind { + #[default] + Graphic, + MovieClip, + Button, +} + +/// A reusable symbol in the library. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Symbol { + // (PartialEq is fast: `Timeline` compares its layers by pointer first.) + pub id: SymbolId, + pub name: String, + #[serde(default)] + pub kind: SymbolKind, + pub timeline: Timeline, +} + +/// Stage settings. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Stage { + pub width: u32, + pub height: u32, + pub fps: f32, + pub background: Rgba, +} + +impl Default for Stage { + fn default() -> Self { + Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE } + } +} + +/// Largest stage edge accepted from files and commands. +pub const MAX_STAGE_EDGE: u32 = 16_384; + +/// A whole AniCraft document: a persistent (structurally shared) tree. +/// +/// `clone()` is O(layers + symbols) pointer copies, which makes undo snapshots and render-thread +/// hand-off cheap, and `==` costs O(changed) because shared subtrees compare by pointer. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Document { + #[serde(default)] + pub stage: Stage, + #[serde(default)] + pub timeline: Timeline, + #[serde(default)] + pub library: Vec>, + /// Next free id for layers, elements and symbols. + #[serde(default = "first_id")] + pub next_id: u64, +} + +fn first_id() -> u64 { + 1 +} + +impl PartialEq for Document { + fn eq(&self, o: &Document) -> bool { + self.stage == o.stage && self.next_id == o.next_id && self.timeline == o.timeline && arcs_eq(&self.library, &o.library) + } +} + +impl Default for Document { + fn default() -> Self { + let mut d = Document { stage: Stage::default(), timeline: Timeline::default(), library: Vec::new(), next_id: 1 }; + let id = LayerId(d.alloc_id()); + d.timeline.layers.push(Arc::new(Layer::new(id, "Layer 1"))); + d + } +} + +impl Document { + /// A fresh id, unique within this document. + pub fn alloc_id(&mut self) -> u64 { + let id = self.next_id.max(1); + self.next_id = id.saturating_add(1); + id + } + pub fn symbol(&self, id: SymbolId) -> Option<&Symbol> { + self.library.iter().find(|s| s.id == id).map(|s| &**s) + } + pub fn frame_count(&self) -> u32 { + self.timeline.frame_count() + } + /// Repairs a loaded document: ids, sizes and keyframe order. + pub fn sanitize(&mut self) { + let s = &mut self.stage; + s.width = s.width.clamp(1, MAX_STAGE_EDGE); + s.height = s.height.clamp(1, MAX_STAGE_EDGE); + if !s.fps.is_finite() || s.fps <= 0.0 { + s.fps = 24.0; + } + s.fps = s.fps.clamp(1.0, 240.0); + s.background = s.background.sanitized(); + let mut max_id = 0u64; + let scan = |l: &Layer, max_id: &mut u64| { + *max_id = (*max_id).max(l.id.0); + for k in &l.keyframes { + for e in &k.elements { + *max_id = (*max_id).max(e.id.0); + } + } + }; + for l in &mut self.timeline.layers { + Arc::make_mut(l).normalize(); + scan(l, &mut max_id); + } + self.timeline.repair_masks(); + for sym in &mut self.library { + max_id = max_id.max(sym.id.0); + let tl = &mut Arc::make_mut(sym).timeline; + for l in &mut tl.layers { + Arc::make_mut(l).normalize(); + scan(l, &mut max_id); + } + tl.repair_masks(); + } + self.next_id = self.next_id.max(max_id.saturating_add(1)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keyframe_lookup() { + let mut l = Layer::new(LayerId(1), "a"); + l.keyframes = [Keyframe::new(0, 5), Keyframe::new(5, 3), Keyframe::new(10, 2)].map(Arc::new).to_vec(); + assert_eq!(l.keyframe_index_at(0), Some(0)); + assert_eq!(l.keyframe_index_at(4), Some(0)); + assert_eq!(l.keyframe_index_at(7), Some(1)); + assert_eq!(l.keyframe_index_at(8), None); // gap + assert_eq!(l.keyframe_index_at(11), Some(2)); + assert_eq!(l.keyframe_index_at(12), None); + assert_eq!(l.end_frame(), 12); + } + + #[test] + fn normalize_removes_overlap() { + let mut l = Layer::new(LayerId(1), "a"); + l.keyframes = [Keyframe::new(4, 10), Keyframe::new(0, 100)].map(Arc::new).to_vec(); + l.normalize(); + assert_eq!(l.keyframes[0].start, 0); + assert_eq!(l.keyframes[0].duration, 4); + assert_eq!(l.keyframes[1].duration, 10); + } + + #[test] + fn loop_modes() { + assert_eq!(LoopMode::Loop.local_frame(7, 0, 5), 2); + assert_eq!(LoopMode::PlayOnce.local_frame(7, 0, 5), 4); + assert_eq!(LoopMode::SingleFrame.local_frame(7, 3, 5), 3); + assert_eq!(LoopMode::Loop.local_frame(u32::MAX, u32::MAX, 0), 0); + } + + #[test] + fn hex_roundtrip() { + let c = Rgba::parse_hex("#ff8000").unwrap(); + assert_eq!(c.to_hex(), "#ff8000"); + assert!(Rgba::parse_hex("zz").is_none()); + assert!(Rgba::parse_hex("ééé").is_none()); + } + + #[test] + fn clones_share_structure_and_edits_copy_only_their_path() { + let a = sample::demo(); + let mut b = a.clone(); + assert!(a.timeline.layers.iter().zip(&b.timeline.layers).all(|(x, y)| Arc::ptr_eq(x, y))); + // Edit one element on the top layer. + let layer = Arc::make_mut(&mut b.timeline.layers[0]); + let kf = layer.keyframe_mut(1).unwrap(); + Arc::make_mut(&mut kf.elements[0]).name = "edited".into(); + assert!(!Arc::ptr_eq(&a.timeline.layers[0], &b.timeline.layers[0])); + // siblings stay shared + assert!(Arc::ptr_eq(&a.timeline.layers[0].keyframes[0], &b.timeline.layers[0].keyframes[0])); + assert!(a.timeline.layers[1..].iter().zip(&b.timeline.layers[1..]).all(|(x, y)| Arc::ptr_eq(x, y))); + assert!(a.library.iter().zip(&b.library).all(|(x, y)| Arc::ptr_eq(x, y))); + assert_ne!(a, b); + // Equal content in fresh allocations still compares equal. + let c: Document = serde_json::from_str(&serde_json::to_string(&a).unwrap()).unwrap(); + assert_eq!(a, c); + } + + #[test] + fn normalize_does_not_unshare_valid_keyframes() { + let a = sample::demo(); + let mut b = a.clone(); + let layer = Arc::make_mut(&mut b.timeline.layers[0]); + layer.normalize(); + assert!(a.timeline.layers[0].keyframes.iter().zip(&layer.keyframes).all(|(x, y)| Arc::ptr_eq(x, y))); + } + + #[test] + fn sanitize_repairs_hostile_document() { + let mut d = Document::default(); + d.stage.width = 0; + d.stage.fps = f32::NAN; + d.next_id = 0; + d.sanitize(); + assert_eq!(d.stage.width, 1); + assert_eq!(d.stage.fps, 24.0); + assert!(d.next_id > d.timeline.layers[0].id.0); + } +} diff --git a/crates/doc/src/path_table.rs b/crates/doc/src/path_table.rs new file mode 100644 index 00000000..ced3d99f --- /dev/null +++ b/crates/doc/src/path_table.rs @@ -0,0 +1,104 @@ +//! Path de-duplication for serialization. +//! +//! In memory, a shape tweened across many keyframes shares one `Arc`. Serialized naively, +//! every keyframe would repeat the path. Inside [`write_with_paths`], each shared path is written +//! once to a table (built by [`build_table`]) and shapes refer to it by index. Inside a +//! [`begin_read`] scope the references resolve back to shared `Arc`s, so loading restores the +//! sharing (and its memory savings) too. +//! Outside those scopes, paths serialize inline, so documents embedded in other JSON still work. + +use crate::{Document, ElementKind}; +use anicraft_geom::Path; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::Arc; + +enum Ctx { + Write { index: HashMap, paths: Vec> }, + Read { paths: Vec> }, +} + +thread_local! { + static CTX: RefCell> = const { RefCell::new(None) }; +} + +/// Clears the context even if serialization unwinds. +struct Guard; +impl Drop for Guard { + fn drop(&mut self) { + CTX.with(|c| c.replace(None)); + } +} + +/// Every distinct path of `doc` (main timeline and library), in first-use order. Walking the +/// tree up front lets a writer emit the table *before* the document, so readers can stream. +pub fn build_table(doc: &Document) -> Vec> { + let mut seen: HashMap = HashMap::new(); + let mut out = Vec::new(); + let timelines = std::iter::once(&doc.timeline).chain(doc.library.iter().map(|s| &s.timeline)); + for tl in timelines { + for layer in &tl.layers { + for k in &layer.keyframes { + for e in &k.elements { + if let ElementKind::Shape(s) = &e.kind + && seen.insert(Arc::as_ptr(&s.path) as usize, ()).is_none() + { + out.push(s.path.clone()); + } + } + } + } + } + out +} + +/// Runs `f` (which serializes a document) with shapes referring to `paths` by index. +pub fn write_with_paths(paths: &[Arc], f: impl FnOnce() -> R) -> R { + let index = paths.iter().enumerate().map(|(i, p)| (Arc::as_ptr(p) as usize, i as u32)).collect(); + CTX.with(|c| c.replace(Some(Ctx::Write { index, paths: paths.to_vec() }))); + let _guard = Guard; + f() +} + +/// Scope in which deserialized path references resolve against a table. Clears on drop. +pub struct ReadScope(Guard); + +/// Makes `paths` available to path references until the returned scope is dropped. +pub fn begin_read(paths: Vec>) -> ReadScope { + CTX.with(|c| c.replace(Some(Ctx::Read { paths }))); + ReadScope(Guard) +} + +pub fn serialize(p: &Arc, s: S) -> Result { + let idx = CTX.with(|c| match &mut *c.borrow_mut() { + Some(Ctx::Write { index, paths }) => { + let key = Arc::as_ptr(p) as usize; + Some(*index.entry(key).or_insert_with(|| { + paths.push(p.clone()); + (paths.len() - 1) as u32 + })) + } + _ => None, + }); + match idx { + Some(i) => s.serialize_u32(i), + None => p.serialize(s), + } +} + +pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Repr { + Ref(u32), + Inline(Path), + } + match Repr::deserialize(d)? { + Repr::Inline(p) => Ok(Arc::new(p)), + Repr::Ref(i) => CTX.with(|c| match &*c.borrow() { + Some(Ctx::Read { paths }) => paths.get(i as usize).cloned().ok_or_else(|| serde::de::Error::custom(format!("path reference {i} is out of range"))), + _ => Err(serde::de::Error::custom("path reference outside a path table")), + }), + } +} diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs new file mode 100644 index 00000000..b21561ec --- /dev/null +++ b/crates/doc/src/sample.rs @@ -0,0 +1,225 @@ +//! Generated documents: the demo scene (first launch, tests, `anicraft-cli --sample`) and a +//! deterministic stress document for benchmarks. All artwork is simple generated geometry +//! (no third-party assets). + +use crate::{ + ColorEffect, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LoopMode, Paint, Rgba, Shape, Stage, Symbol, + SymbolId, SymbolKind, Timeline, Tween, +}; +use anicraft_geom::{Affine, Decomposed, Path, Vec2}; +use std::sync::Arc; + +fn stops(cs: &[(f32, u32)]) -> Vec { + cs.iter().map(|&(offset, c)| GradientStop { offset, color: Rgba::hex(c) }).collect() +} + +fn el(doc: &mut Document, name: &str, transform: Affine, kind: ElementKind) -> Arc { + Arc::new(Element { id: ElementId(doc.alloc_id()), name: name.into(), transform, color: ColorEffect::default(), kind }) +} + +fn instance(symbol: SymbolId) -> ElementKind { + ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0 } +} + +fn pose(tx: f32, ty: f32, sx: f32, sy: f32, rotation_deg: f32) -> Affine { + Decomposed { tx, ty, sx, sy, rotation: rotation_deg.to_radians(), skew: 0.0 }.compose() +} + +fn layer(id: u64, name: &str, color: u32, keyframes: Vec) -> Arc { + let mut l = Layer::new(LayerId(id), name); + l.color = Rgba::hex(color); + l.keyframes = keyframes.into_iter().map(Arc::new).collect(); + Arc::new(l) +} + +fn key(start: u32, duration: u32, elements: Vec>, tween: Option) -> Keyframe { + let mut k = Keyframe::new(start, duration); + k.elements = elements; + k.tween = tween.map(|easing| Tween { easing }); + k +} + +/// Builds the demo document: a bouncing ball, a spinning star, a pulsing sun over hills. +pub fn demo() -> Document { + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, timeline: Timeline::default(), library: Vec::new(), next_id: 1 }; + let (w, h) = (1280.0, 720.0); + + // --- library ------------------------------------------------------------------------- + let ball_id = SymbolId(d.alloc_id()); + let ball_shape = Shape::filled( + Path::ellipse(0.0, 0.0, 48.0, 48.0), + Paint::Radial { center: Vec2::new(-16.0, -18.0), radius: 70.0, stops: stops(&[(0.0, 0xfff1c4), (0.35, 0xff8a3d), (1.0, 0xb3261e)]) }, + ) + .with_stroke(Rgba::hex(0x5a1410), 3.0); + let ball_el = el(&mut d, "ball body", Affine::IDENTITY, ElementKind::Shape(ball_shape)); + let ball_layer = layer(d.alloc_id(), "body", 0x4fa3ff, vec![key(0, 1, vec![ball_el], None)]); + d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![ball_layer] } })); + + let star_id = SymbolId(d.alloc_id()); + let star_shape = Shape::filled(Path::star(0.0, 0.0, 60.0, 26.0, 5), Paint::Solid(Rgba::hex(0xfff6a8))).with_stroke(Rgba::hex(0xe0a400), 2.5); + let star_el_id = ElementId(d.alloc_id()); // same id across keyframes: one instance over time + let star_keys = [0.0f32, 120.0, 240.0, 360.0] + .into_iter() + .enumerate() + .map(|(i, deg)| { + let e = Element { id: star_el_id, name: "star".into(), transform: pose(0.0, 0.0, 1.0, 1.0, deg), color: ColorEffect::default(), kind: ElementKind::Shape(star_shape.clone()) }; + key(i as u32 * 8, if i == 3 { 1 } else { 8 }, vec![Arc::new(e)], (i < 3).then_some(Easing::Linear)) + }) + .collect(); + let star_layer = layer(d.alloc_id(), "spin", 0x4fa3ff, star_keys); + d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![star_layer] } })); + + // --- main timeline (index 0 = top) --------------------------------------------------- + const LEN: u32 = 48; + + // Ball: bounces across the stage with squash at each impact. + let ball_layer_id = d.alloc_id(); + let ball_inst = ElementId(d.alloc_id()); + let poses = [ + (0u32, (200.0, 260.0, 1.0, 1.0), Easing::QuadIn), + (12, (480.0, 572.0, 1.25, 0.78), Easing::QuadOut), + (24, (760.0, 270.0, 0.95, 1.05), Easing::QuadIn), + (36, (1010.0, 572.0, 1.25, 0.78), Easing::QuadOut), + (47, (1160.0, 330.0, 1.0, 1.0), Easing::Linear), + ]; + let ball_keys = poses + .iter() + .enumerate() + .map(|(i, &(start, (x, y, sx, sy), easing))| { + let next = poses.get(i + 1).map_or(LEN, |p| p.0); + let e = Element { id: ball_inst, name: "ball".into(), transform: pose(x, y, sx, sy, 0.0), color: ColorEffect::default(), kind: instance(ball_id) }; + key(start, next - start, vec![Arc::new(e)], (i + 1 < poses.len()).then_some(easing)) + }) + .collect(); + let ball = layer(ball_layer_id, "Ball", 0xff6b4a, ball_keys); + + // Star: a nested, self-animating graphic symbol. + let star_layer_id = d.alloc_id(); + let star_el = el(&mut d, "star", pose(640.0, 110.0, 0.7, 0.7, 0.0), instance(star_id)); + let star = layer(star_layer_id, "Star", 0xffd54a, vec![key(0, LEN, vec![star_el], None)]); + + // Sun: pulses with an ease in-out. + let sun_layer_id = d.alloc_id(); + let sun_inst = ElementId(d.alloc_id()); + let sun_shape = Shape::filled(Path::ellipse(0.0, 0.0, 90.0, 90.0), Paint::Radial { center: Vec2::ZERO, radius: 90.0, stops: stops(&[(0.0, 0xfffbe0), (0.6, 0xffd36b), (1.0, 0xffa94d)]) }); + let sun_keys = [(0u32, 24u32, 1.0f32), (24, 23, 1.15), (47, 1, 1.0)] + .into_iter() + .enumerate() + .map(|(i, (start, dur, s))| { + let e = Element { id: sun_inst, name: "sun".into(), transform: pose(1040.0, 150.0, s, s, 0.0), color: ColorEffect::default(), kind: ElementKind::Shape(sun_shape.clone()) }; + key(start, dur, vec![Arc::new(e)], (i < 2).then_some(Easing::QuadInOut)) + }) + .collect(); + let sun = layer(sun_layer_id, "Sun", 0xffa726, sun_keys); + + // Hills and ground. + let hills_id = d.alloc_id(); + let mut hill_els = Vec::new(); + for (name, path, c) in [ + ("far hill", Path::ellipse(330.0, 700.0, 520.0, 220.0), 0x4f8f6a), + ("near hill", Path::ellipse(1010.0, 730.0, 560.0, 230.0), 0x3d7a58), + ("ground", Path::rect(0.0, 620.0, w, h - 620.0), 0x2f6247), + ] { + hill_els.push(el(&mut d, name, Affine::IDENTITY, ElementKind::Shape(Shape::filled(path, Paint::Solid(Rgba::hex(c)))))); + } + let hills = layer(hills_id, "Hills", 0x66bb6a, vec![key(0, LEN, hill_els, None)]); + + // Sky. + let sky_id = d.alloc_id(); + let sky_el = el( + &mut d, + "sky", + Affine::IDENTITY, + ElementKind::Shape(Shape::filled( + Path::rect(0.0, 0.0, w, h), + Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(0.0, h), stops: stops(&[(0.0, 0x27407a), (0.55, 0x8a79c9), (1.0, 0xf7b98b)]) }, + )), + ); + let mut sky = layer(sky_id, "Sky", 0x7e57c2, vec![key(0, LEN, vec![sky_el], None)]); + Arc::make_mut(&mut sky).locked = true; + + d.timeline.layers = vec![ball, star, sun, hills, sky]; + d +} + +/// Deterministic stress document for benchmarks and scaling tests: `layers` layers with +/// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens. +/// Every element keeps one `Arc` across its keyframes, as a real tweened shape does. +pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document { + let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, timeline: Timeline::default(), library: Vec::new(), next_id: 1 }; + let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000)); + let mut seed = 0x2545_f491_u32; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + (seed as f32) / (u32::MAX as f32) + }; + for li in 0..layers { + let lid = d.alloc_id(); + let els: Vec<(ElementId, Arc, Paint, f32, f32)> = (0..shapes) + .map(|si| { + let r = 6.0 + rnd() * 40.0; + let path = match si % 3 { + 0 => Path::ellipse(0.0, 0.0, r, r * (0.5 + rnd())), + 1 => Path::star(0.0, 0.0, r, r * 0.45, 5), + _ => Path::rounded_rect(-r, -r * 0.6, r * 2.0, r * 1.2, r * 0.2), + }; + let c = Rgba::new(rnd(), rnd(), rnd(), 0.6 + 0.4 * rnd()); + (ElementId(d.alloc_id()), Arc::new(path), Paint::Solid(c), rnd() * 1920.0, rnd() * 1080.0) + }) + .collect(); + let mut keys = Vec::new(); + let mut start = 0; + while start < frames { + let dur = 12.min(frames - start); + let phase = start as f32 * 0.05; + let elements = els + .iter() + .map(|(id, path, fill, x, y)| { + let dx = (phase + x * 0.01).sin() * 60.0; + let dy = (phase + y * 0.01).cos() * 40.0; + Arc::new(Element { + id: *id, + name: String::new(), + transform: pose(x + dx, y + dy, 1.0, 1.0, phase * 20.0), + color: ColorEffect::default(), + kind: ElementKind::Shape(Shape { path: path.clone(), fill: Some(fill.clone()), stroke: None, fill_rule: Default::default() }), + }) + }) + .collect(); + keys.push(key(start, dur, elements, (start + dur < frames).then_some(Easing::QuadInOut))); + start += dur; + } + d.timeline.layers.push(layer(lid, &format!("Layer {}", li + 1), 0x4fa3ff, keys)); + } + d +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn demo_is_consistent() { + let mut d = demo(); + assert_eq!(d.frame_count(), 48); + let before = d.clone(); + d.sanitize(); + assert_eq!(d.timeline, before.timeline, "demo must already satisfy invariants"); + let items = crate::evaluate(&d, 10).items.len(); + assert!(items >= 7, "{items}"); + } + + #[test] + fn stress_shape() { + let d = stress(3, 50, 30); + assert_eq!(d.timeline.layers.len(), 3); + assert_eq!(d.frame_count(), 30); + assert_eq!(crate::evaluate(&d, 7).items.len(), 150); + // paths are shared across keyframes + let l = &d.timeline.layers[0]; + let (ElementKind::Shape(a), ElementKind::Shape(b)) = (&l.keyframes[0].elements[0].kind, &l.keyframes[1].elements[0].kind) else { panic!() }; + assert!(Arc::ptr_eq(&a.path, &b.path)); + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml new file mode 100644 index 00000000..e214e00b --- /dev/null +++ b/crates/engine/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "anicraft-engine" +description = "AniCraft L3: session, undo history, command registry and the .anicraft file format" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[dependencies] +anicraft-geom.workspace = true +anicraft-doc.workspace = true +anicraft-render.workspace = true +anicraft-xfl.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +rayon.workspace = true +gif.workspace = true + +[lints] +workspace = true diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs new file mode 100644 index 00000000..d45f8749 --- /dev/null +++ b/crates/engine/src/cmds_draw.rs @@ -0,0 +1,492 @@ +//! Drawing, selection, element and symbol commands. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_geom::{Affine, Decomposed, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("draw.rect", "Rectangle", "", None, "{x, y, w, h, radius?, fill?, stroke?, stroke_width?}", true, draw_rect as crate::RunFn), + c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?}", true, draw_ellipse), + c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?}", true, draw_star), + c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?}", true, draw_line), + c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all), + c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| { + s.selection.clear(); + Ok(json!({"selected": 0})) + }), + c("edit.delete", "Clear", "Edit", Some("Delete"), "{}", true, delete), + c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?}", true, duplicate), + c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool}", false, select), + c("element.pick", "Select at Point", "", None, "{x, y, add?: bool}", false, pick), + c("element.translate", "Move", "", None, "{dx, dy}", true, translate), + c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, set_transform), + c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, set_fill), + c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?}", true, set_stroke), + c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, set_alpha), + c("element.rename", "Instance Name", "", None, "{name}", true, rename), + c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{}", true, |s, _| arrange(s, true)), + c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{}", true, |s, _| arrange_step(s, true)), + c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{}", true, |s, _| arrange_step(s, false)), + c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{}", true, |s, _| arrange(s, false)), + c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?}", true, convert_to_symbol), + c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, break_apart), + c("library.place", "Place Instance", "", None, "{symbol, x?, y?}", true, place), + ] +} + +// ----- drawing ---------------------------------------------------------------------------- + +/// Max path size accepted from params (extent in stage units). +pub(crate) const MAX_EXTENT: f32 = 1_000_000.0; + +pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option, Option)> { + let fill = if !closed || p.get("fill").is_some_and(Value::is_null) { + None + } else { + match opt_color(p, "fill")? { + Some(c) => Some(Paint::Solid(c)), + None => s.style.use_fill.then_some(Paint::Solid(s.style.fill)), + } + }; + let width = match opt_f32(p, "stroke_width")? { + Some(w) if (0.0..=1000.0).contains(&w) => w, + Some(_) => return Err(EngineError::Param("param 'stroke_width' must be in 0..=1000".into())), + None => s.style.stroke_width, + }; + let stroke = if p.get("stroke").is_some_and(Value::is_null) || width <= 0.0 { + None + } else { + match opt_color(p, "stroke")? { + Some(c) => Some(Stroke { color: c, width }), + None => (s.style.use_stroke || !closed).then_some(Stroke { color: s.style.stroke, width }), + } + }; + if fill.is_none() && stroke.is_none() { + return Err(EngineError::Param("shape would be invisible: give it a fill or a stroke".into())); + } + Ok((fill, stroke)) +} + +fn rect_params(p: &Value) -> Result<(f32, f32, f32, f32)> { + let (x, y, w, h) = (f32_req(p, "x")?, f32_req(p, "y")?, f32_req(p, "w")?, f32_req(p, "h")?); + if w.abs() < 0.5 || h.abs() < 0.5 { + return Err(EngineError::Param("shape is too small (width and height must be at least 0.5)".into())); + } + if w.abs() > MAX_EXTENT || h.abs() > MAX_EXTENT { + return Err(EngineError::Param("shape is too large".into())); + } + // normalise negative sizes (dragging up/left) + Ok((x.min(x + w), y.min(y + h), w.abs(), h.abs())) +} + +/// Adds a shape whose local origin is its centre, placed with a translation. +pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, fill: Option, stroke: Option) -> Result { + let id = ElementId(s.doc.alloc_id()); + let el = Element { + id, + name: String::new(), + transform: Affine::translate(origin.x, origin.y), + color: ColorEffect::default(), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default() }), + }; + let kf = s.editable_keyframe()?; + if kf.elements.len() >= 100_000 { + return Err(EngineError::State("too many elements on this keyframe".into())); + } + kf.elements.push(Arc::new(el)); + s.selection = vec![id]; + Ok(json!({"element": id.0, "kind": name})) +} + +fn draw_rect(s: &mut Session, p: &Value) -> Result { + let (x, y, w, h) = rect_params(p)?; + let r = opt_f32(p, "radius")?.unwrap_or(0.0).max(0.0); + let (fill, stroke) = style(s, p, true)?; + add_shape(s, "rect", Path::rounded_rect(-w / 2.0, -h / 2.0, w, h, r), Vec2::new(x + w / 2.0, y + h / 2.0), fill, stroke) +} + +fn draw_ellipse(s: &mut Session, p: &Value) -> Result { + let (x, y, w, h) = rect_params(p)?; + let (fill, stroke) = style(s, p, true)?; + add_shape(s, "ellipse", Path::ellipse(0.0, 0.0, w / 2.0, h / 2.0), Vec2::new(x + w / 2.0, y + h / 2.0), fill, stroke) +} + +fn draw_star(s: &mut Session, p: &Value) -> Result { + let (cx, cy, outer) = (f32_req(p, "cx")?, f32_req(p, "cy")?, f32_req(p, "outer")?); + if !(0.5..=MAX_EXTENT).contains(&outer) { + return Err(EngineError::Param("param 'outer' must be between 0.5 and 1,000,000".into())); + } + let inner = opt_f32(p, "inner")?.unwrap_or(outer * 0.5).clamp(0.0, MAX_EXTENT); + let points = opt_u32(p, "points")?.unwrap_or(5); + if !(3..=64).contains(&points) { + return Err(EngineError::Param("param 'points' must be between 3 and 64".into())); + } + let (fill, stroke) = style(s, p, true)?; + add_shape(s, "star", Path::star(0.0, 0.0, outer, inner, points), Vec2::new(cx, cy), fill, stroke) +} + +fn draw_line(s: &mut Session, p: &Value) -> Result { + let a = Vec2::new(f32_req(p, "x0")?, f32_req(p, "y0")?); + let b = Vec2::new(f32_req(p, "x1")?, f32_req(p, "y1")?); + if a.distance(b) < 0.5 { + return Err(EngineError::Param("line is too short".into())); + } + let (_, stroke) = style(s, p, false)?; + let c = (a + b) * 0.5; + add_shape(s, "line", Path::line(a - c, b - c), c, None, stroke) +} + +// ----- selection -------------------------------------------------------------------------- + +fn select_all(s: &mut Session, _: &Value) -> Result { + s.selection = s.visible_elements().iter().map(|e| e.id).collect(); + Ok(json!({"selected": s.selection.len()})) +} + +fn select(s: &mut Session, p: &Value) -> Result { + let ids = opt_u64_list(p, "ids")?.ok_or_else(|| EngineError::Param("param 'ids' is required".into()))?; + let add = opt_bool(p, "add")?.unwrap_or(false); + let present: Vec = s.visible_elements().iter().map(|e| e.id).collect(); + if !add { + s.selection.clear(); + } + for id in ids.into_iter().map(ElementId) { + if !present.contains(&id) { + return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0))); + } + if !s.selection.contains(&id) { + s.selection.push(id); + } + } + Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>()})) +} + +fn pick(s: &mut Session, p: &Value) -> Result { + let pt = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let add = opt_bool(p, "add")?.unwrap_or(false); + match s.hit_test(pt, 2.0) { + Some((layer, el)) => { + if layer != s.layer { + s.layer = layer; + s.selection.clear(); + } + if add { + if let Some(i) = s.selection.iter().position(|e| *e == el) { + s.selection.remove(i); + } else { + s.selection.push(el); + } + } else if !s.selection.contains(&el) { + s.selection = vec![el]; + } + Ok(json!({"layer": layer.0, "element": el.0})) + } + None => { + if !add { + s.selection.clear(); + } + Ok(json!({"element": null})) + } + } +} + +// ----- element edits ---------------------------------------------------------------------- + +fn translate(s: &mut Session, p: &Value) -> Result { + let (dx, dy) = (f32_req(p, "dx")?, f32_req(p, "dy")?); + let els = s.selected_elements_mut()?; + let n = els.len(); + for e in els { + e.transform = Affine::translate(dx, dy).mul(&e.transform); + } + Ok(json!({"moved": n})) +} + +fn set_transform(s: &mut Session, p: &Value) -> Result { + let x = opt_f32(p, "x")?; + let y = opt_f32(p, "y")?; + let sx = opt_f32(p, "sx")?; + let sy = opt_f32(p, "sy")?; + let rot = opt_f32(p, "rotation")?; + for v in [sx, sy].into_iter().flatten() { + if v.abs() < 1e-3 || v.abs() > 1000.0 { + return Err(EngineError::Param("scale must be between 0.001 and 1000 in magnitude".into())); + } + } + let els = s.selected_elements_mut()?; + for e in els { + let mut d: Decomposed = e.transform.decompose(); + if let Some(v) = x { + d.tx = v; + } + if let Some(v) = y { + d.ty = v; + } + if let Some(v) = sx { + d.sx = v; + } + if let Some(v) = sy { + d.sy = v; + } + if let Some(v) = rot { + d.rotation = v.to_radians(); + } + e.transform = d.compose(); + } + Ok(json!({"ok": true})) +} + +fn shapes_mut(s: &mut Session) -> Result> { + let shapes: Vec<&mut Shape> = s + .selected_elements_mut()? + .into_iter() + .filter_map(|e| match &mut e.kind { + ElementKind::Shape(sh) => Some(sh), + ElementKind::Symbol { .. } => None, + }) + .collect(); + if shapes.is_empty() { + return Err(EngineError::State("the selection has no shapes (symbol instances use alpha/tint)".into())); + } + Ok(shapes) +} + +fn set_fill(s: &mut Session, p: &Value) -> Result { + let fill = if p.get("color").is_some_and(Value::is_null) { + None + } else { + Some(Paint::Solid(opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' is required".into()))?)) + }; + for sh in shapes_mut(s)? { + sh.fill = fill.clone(); + } + Ok(json!({"ok": true})) +} + +fn set_stroke(s: &mut Session, p: &Value) -> Result { + let remove = p.get("color").is_some_and(Value::is_null); + let color = opt_color(p, "color")?; + let width = opt_f32(p, "width")?; + if width.is_some_and(|w| !(0.0..=1000.0).contains(&w)) { + return Err(EngineError::Param("param 'width' must be in 0..=1000".into())); + } + let default = s.style; + for sh in shapes_mut(s)? { + if remove { + sh.stroke = None; + continue; + } + let mut st = sh.stroke.unwrap_or(Stroke { color: default.stroke, width: default.stroke_width }); + if let Some(c) = color { + st.color = c; + } + if let Some(w) = width { + st.width = w; + } + sh.stroke = (st.width > 0.0).then_some(st); + } + Ok(json!({"ok": true})) +} + +fn set_alpha(s: &mut Session, p: &Value) -> Result { + let a = f32_req(p, "alpha")?; + if !(0.0..=1.0).contains(&a) { + return Err(EngineError::Param("param 'alpha' must be between 0 and 1".into())); + } + for e in s.selected_elements_mut()? { + e.color.alpha = a; + } + Ok(json!({"alpha": a})) +} + +fn rename(s: &mut Session, p: &Value) -> Result { + let name: String = str_req(p, "name")?.chars().take(128).collect(); + for e in s.selected_elements_mut()? { + e.name = name.clone(); + } + Ok(json!({"name": name})) +} + +pub(crate) fn delete(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let kf = s.editable_keyframe()?; + let before = kf.elements.len(); + kf.elements.retain(|e| !sel.contains(&e.id)); + let n = before - kf.elements.len(); + s.selection.clear(); + Ok(json!({"deleted": n})) +} + +fn duplicate(s: &mut Session, p: &Value) -> Result { + let dx = opt_f32(p, "dx")?.unwrap_or(10.0); + let dy = opt_f32(p, "dy")?.unwrap_or(10.0); + let sel = s.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let copies: Vec = s.editable_keyframe()?.elements.iter().filter(|e| sel.contains(&e.id)).map(|e| (**e).clone()).collect(); + let mut new_ids = Vec::new(); + let mut out = Vec::new(); + for mut e in copies { + e.id = ElementId(s.doc.alloc_id()); + e.transform = Affine::translate(dx, dy).mul(&e.transform); + new_ids.push(e.id); + out.push(Arc::new(e)); + } + s.editable_keyframe()?.elements.extend(out); + s.selection = new_ids.clone(); + Ok(json!({"created": new_ids.iter().map(|e| e.0).collect::>()})) +} + +fn arrange(s: &mut Session, front: bool) -> Result { + let sel = s.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let kf = s.editable_keyframe()?; + let (picked, rest): (Vec>, Vec>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id)); + kf.elements = if front { rest.into_iter().chain(picked).collect() } else { picked.into_iter().chain(rest).collect() }; + Ok(json!({"ok": true})) +} + +/// Bring Forward / Send Backward: each selected element swaps with the unselected neighbour +/// above (or below) it; a selected block moves as one, keeping its order. +fn arrange_step(s: &mut Session, forward: bool) -> Result { + let sel = s.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let kf = s.editable_keyframe()?; + let n = kf.elements.len(); + let picked = |els: &Vec>, i: usize| els.get(i).is_some_and(|e| sel.contains(&e.id)); + if forward { + // From the top down, so a selected element never jumps over another selected one. + for i in (0..n.saturating_sub(1)).rev() { + if picked(&kf.elements, i) && !picked(&kf.elements, i + 1) { + kf.elements.swap(i, i + 1); + } + } + } else { + for i in 1..n { + if picked(&kf.elements, i) && !picked(&kf.elements, i - 1) { + kf.elements.swap(i, i - 1); + } + } + } + Ok(json!({"ok": true})) +} + +// ----- symbols ---------------------------------------------------------------------------- + +fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { + let sel = s.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("select something to convert".into())); + } + let n = s.doc.library.len() + 1; + let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}")); + let bounds = s.selection_bounds(); + let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; + let sym_id = SymbolId(s.doc.alloc_id()); + let layer_id = LayerId(s.doc.alloc_id()); + let inst_id = ElementId(s.doc.alloc_id()); + let kf = s.editable_keyframe()?; + let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len()); + let (picked, rest): (Vec>, Vec>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id)); + // Children are stored relative to the registration point (the selection centre). + let to_local = Affine::translate(-center.x, -center.y); + let children: Vec> = picked + .into_iter() + .map(|e| { + let mut e = Arc::unwrap_or_clone(e); + e.transform = to_local.mul(&e.transform); + Arc::new(e) + }) + .collect(); + let instance = Element { + id: inst_id, + name: String::new(), + transform: Affine::translate(center.x, center.y), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::Loop, first_frame: 0 }, + }; + let mut elements = rest; + elements.insert(first_pos.min(elements.len()), Arc::new(instance)); + kf.elements = elements; + let mut layer = Layer::new(layer_id, "Layer 1"); + if let Some(k) = layer.keyframe_mut(0) { + k.elements = children; + } + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + s.selection = vec![inst_id]; + Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name})) +} + +fn break_apart(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let library = s.doc.library.clone(); + let mut fresh_ids = Vec::new(); + let kf_elements: Vec> = s.editable_keyframe()?.elements.clone(); + let mut out = Vec::new(); + for e in kf_elements { + let ElementKind::Symbol { symbol, .. } = &e.kind else { + out.push(e); + continue; + }; + if !sel.contains(&e.id) { + out.push(e); + continue; + } + let Some(sym) = library.iter().find(|x| x.id == *symbol) else { + out.push(e); + continue; + }; + for layer in sym.timeline.layers.iter().rev() { + for child in layer.keyframes.first().map(|k| k.elements.as_slice()).unwrap_or(&[]) { + let mut c = (**child).clone(); + c.id = ElementId(s.doc.alloc_id()); + c.transform = e.transform.mul(&child.transform); + c.color = e.color.concat(&child.color); + fresh_ids.push(c.id); + out.push(Arc::new(c)); + } + } + } + if fresh_ids.is_empty() { + return Err(EngineError::State("the selection has no symbol instances to break apart".into())); + } + s.editable_keyframe()?.elements = out; + s.selection = fresh_ids.clone(); + Ok(json!({"created": fresh_ids.len()})) +} + +fn place(s: &mut Session, p: &Value) -> Result { + let sym = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?); + if s.doc.symbol(sym).is_none() { + return Err(EngineError::State(format!("no symbol with id {}", sym.0))); + } + let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0); + let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0); + let id = ElementId(s.doc.alloc_id()); + let el = Element { + id, + name: String::new(), + transform: Affine::translate(x, y), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0 }, + }; + s.editable_keyframe()?.elements.push(Arc::new(el)); + s.selection = vec![id]; + Ok(json!({"element": id.0})) +} diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs new file mode 100644 index 00000000..c1c4d2b6 --- /dev/null +++ b/crates/engine/src/cmds_file.rs @@ -0,0 +1,246 @@ +//! File, edit-history and document commands. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, format}; +use anicraft_doc::{Document, MAX_STAGE_EDGE, Stage, sample}; +use anicraft_render::{View, render}; +use rayon::prelude::*; +use serde_json::{Value, json}; +use std::path::PathBuf; + +pub fn specs() -> Vec { + vec![ + CommandSpec { id: "file.new", label: "New", menu: "File", shortcut: Some("Ctrl+N"), params: "{width?, height?, fps?}", mutates: false, run: new_doc }, + CommandSpec { id: "file.new_sample", label: "New from Sample", menu: "File", shortcut: None, params: "{}", mutates: false, run: new_sample }, + CommandSpec { id: "file.open", label: "Open…", menu: "File", shortcut: Some("Ctrl+O"), params: "{path}", mutates: false, run: open }, + CommandSpec { id: "file.save", label: "Save", menu: "File", shortcut: Some("Ctrl+S"), params: "{path?, confirm?}", mutates: false, run: save }, + CommandSpec { + id: "file.save_as", + label: "Save As…", + menu: "File", + shortcut: Some("Ctrl+Shift+S"), + params: "{path, confirm?}", + mutates: false, + run: |s, p| { + str_req(p, "path")?; + save(s, p) + }, + }, + CommandSpec { id: "file.export_png", label: "Export Frame as PNG…", menu: "File/Export", shortcut: None, params: "{path, frame?, scale?}", mutates: false, run: export_png }, + CommandSpec { + id: "file.export_png_sequence", + label: "Export PNG Sequence…", + menu: "File/Export", + shortcut: None, + params: "{dir, from?, to?, scale?}", + mutates: false, + run: export_sequence, + }, + CommandSpec { + id: "file.export_gif", + label: "Export Animated GIF…", + menu: "File/Export", + shortcut: None, + params: "{path, from?, to?, scale?, loop?, confirm?}", + mutates: false, + run: export_gif, + }, + CommandSpec { id: "edit.undo", label: "Undo", menu: "Edit", shortcut: Some("Ctrl+Z"), params: "{}", mutates: false, run: |s, _| s.undo() }, + CommandSpec { id: "edit.redo", label: "Redo", menu: "Edit", shortcut: Some("Ctrl+Y"), params: "{}", mutates: false, run: |s, _| s.redo() }, + CommandSpec { + id: "doc.set_stage", + label: "Document Settings", + menu: "Modify", + shortcut: None, + params: "{width?, height?, fps?, background?: \"#rrggbb\"}", + mutates: true, + run: set_stage, + }, + CommandSpec { id: "doc.info", label: "Document Info", menu: "", shortcut: None, params: "{}", mutates: false, run: |s, _| Ok(s.info()) }, + ] +} + +fn stage_edge(p: &Value, key: &str, default: u32) -> Result { + match opt_u32(p, key)? { + None => Ok(default), + Some(v) if (1..=MAX_STAGE_EDGE).contains(&v) => Ok(v), + Some(_) => Err(EngineError::Param(format!("param '{key}' must be between 1 and {MAX_STAGE_EDGE}"))), + } +} + +fn fps(p: &Value, default: f32) -> Result { + match opt_f32(p, "fps")? { + None => Ok(default), + Some(f) if (1.0..=240.0).contains(&f) => Ok(f), + Some(_) => Err(EngineError::Param("param 'fps' must be between 1 and 240".into())), + } +} + +fn new_doc(s: &mut Session, p: &Value) -> Result { + let d = Stage::default(); + let mut doc = Document::default(); + doc.stage.width = stage_edge(p, "width", d.width)?; + doc.stage.height = stage_edge(p, "height", d.height)?; + doc.stage.fps = fps(p, d.fps)?; + s.replace_document(doc, None); + Ok(s.info()) +} + +fn new_sample(s: &mut Session, _: &Value) -> Result { + s.replace_document(sample::demo(), None); + Ok(json!({"frames": s.frame_count()})) +} + +/// Whether `path` is an Animate document: a `.fla` archive, an `.xfl` file or an XFL folder. +pub fn is_animate(path: &std::path::Path) -> bool { + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + matches!(ext.as_deref(), Some("fla" | "xfl")) || (path.is_dir() && path.join("DOMDocument.xml").is_file()) +} + +fn open(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + if is_animate(&path) { + // Imported, not adopted: the document is untitled, so Save asks for a new .anicraft + // name and never writes over the Animate file. + let (doc, report) = anicraft_xfl::import_path(&path).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; + s.replace_document(doc, None); + let mut info = s.info(); + info["imported"] = json!(path.display().to_string()); + info["report"] = json!(report.summary()); + info["skipped"] = json!(report.skipped); + return Ok(info); + } + let doc = format::load(&path)?; + s.replace_document(doc, Some(path)); + Ok(s.info()) +} + +fn save(s: &mut Session, p: &Value) -> Result { + let path = match opt_str(p, "path")? { + Some(x) => PathBuf::from(x), + None => s.path.clone().ok_or_else(|| EngineError::Param("no file name yet: pass {\"path\": …}".into()))?, + }; + format::save(&s.doc, &path)?; + s.path = Some(path.clone()); + s.mark_saved(); + Ok(json!({"saved": path.display().to_string()})) +} + +fn scale_param(p: &Value) -> Result { + match opt_f32(p, "scale")? { + None => Ok(1.0), + Some(v) if v > 0.0 && v <= 8.0 => Ok(v), + Some(_) => Err(EngineError::Param("param 'scale' must be in (0, 8]".into())), + } +} + +/// Renders a frame of the session's document to PNG bytes. +pub fn render_png(doc: &Document, frame: u32, scale: f32) -> Result> { + let dl = anicraft_doc::evaluate(doc, frame); + let (pm, _) = render(&dl, &View::stage(doc, scale))?; + Ok(pm.encode_png()?) +} + +fn export_png(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); + let bytes = render_png(&s.doc, frame, scale_param(p)?)?; + std::fs::write(&path, &bytes)?; + Ok(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame})) +} + +fn export_sequence(s: &mut Session, p: &Value) -> Result { + let dir = PathBuf::from(str_req(p, "dir")?); + let last = s.frame_count().saturating_sub(1); + let from = opt_u32(p, "from")?.unwrap_or(0).min(last); + let to = opt_u32(p, "to")?.unwrap_or(last).min(last); + if to < from { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + let scale = scale_param(p)?; + std::fs::create_dir_all(&dir)?; + // Frames are independent: render and encode them in parallel (each render is itself + // row-parallel; rayon balances both levels). Output is identical to a serial export. + let doc = &s.doc; + let files: Vec = (from..=to) + .into_par_iter() + .map(|f| { + let path = dir.join(format!("frame_{:05}.png", f + 1)); + std::fs::write(&path, render_png(doc, f, scale)?)?; + Ok(path.display().to_string()) + }) + .collect::>>()?; + Ok(json!({"frames": files.len(), "dir": dir.display().to_string()})) +} + +/// Largest GIF we produce (frames × pixels), keeping memory and time bounded. +const MAX_GIF_PIXELS: u64 = 600 * 1280 * 720; + +/// Per-frame delays in 1/100 s that add up to the exact running time (error carried forward), +/// never below 2 cs (browsers slow down shorter delays). +pub fn gif_delays(frames: usize, fps: f32) -> Vec { + let fps = if fps.is_finite() && fps > 0.0 { fps } else { 24.0 }; + (0..frames) + .map(|i| { + let t0 = (i as f64 * 100.0 / f64::from(fps)).round(); + let t1 = ((i + 1) as f64 * 100.0 / f64::from(fps)).round(); + ((t1 - t0) as u16).max(2) + }) + .collect() +} + +fn export_gif(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + let last = s.frame_count().saturating_sub(1); + let from = opt_u32(p, "from")?.unwrap_or(0).min(last); + let to = opt_u32(p, "to")?.unwrap_or(last).min(last); + if to < from { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + let scale = scale_param(p)?; + let looping = opt_bool(p, "loop")?.unwrap_or(true); + let view = View::stage(&s.doc, scale); + let (w, h) = (u16::try_from(view.width), u16::try_from(view.height)); + let (Ok(w), Ok(h)) = (w, h) else { return Err(EngineError::Param("GIF frames are limited to 65535 px per side".into())) }; + let n = (to - from + 1) as u64; + if n * u64::from(w) * u64::from(h) > MAX_GIF_PIXELS { + return Err(EngineError::Param(format!("that GIF would be too large ({n} frames at {w}×{h}); lower 'scale' or the frame range"))); + } + // Render and colour-quantize frames in parallel; encode in order. + let doc = &s.doc; + let delays = gif_delays(n as usize, doc.stage.fps); + let frames: Vec> = (from..to.saturating_add(1)) + .into_par_iter() + .zip(delays.into_par_iter()) + .map(|(f, delay)| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + let mut rgba = pm.to_rgba8(); + let mut frame = gif::Frame::from_rgba_speed(w, h, &mut rgba, 10); + frame.delay = delay; + Ok(frame) + }) + .collect::>>()?; + let mut bytes = Vec::new(); + { + let mut enc = gif::Encoder::new(&mut bytes, w, h, &[]).map_err(|e| EngineError::Format(e.to_string()))?; + if looping { + enc.set_repeat(gif::Repeat::Infinite).map_err(|e| EngineError::Format(e.to_string()))?; + } + for fr in &frames { + enc.write_frame(fr).map_err(|e| EngineError::Format(e.to_string()))?; + } + } + std::fs::write(&path, &bytes)?; + Ok(json!({"written": path.display().to_string(), "frames": n, "bytes": bytes.len(), "width": w, "height": h})) +} + +fn set_stage(s: &mut Session, p: &Value) -> Result { + let cur = s.doc.stage; + s.doc.stage.width = stage_edge(p, "width", cur.width)?; + s.doc.stage.height = stage_edge(p, "height", cur.height)?; + s.doc.stage.fps = fps(p, cur.fps)?; + if let Some(c) = opt_color(p, "background")? { + s.doc.stage.background = c; + } + Ok(json!({"width": s.doc.stage.width, "height": s.doc.stage.height, "fps": s.doc.stage.fps, "background": s.doc.stage.background.to_hex()})) +} diff --git a/crates/engine/src/cmds_frames.rs b/crates/engine/src/cmds_frames.rs new file mode 100644 index 00000000..690130f9 --- /dev/null +++ b/crates/engine/src/cmds_frames.rs @@ -0,0 +1,159 @@ +//! Copy, cut and paste frames (Edit › Timeline). +//! +//! Design notes (principal engineer / senior designer review): +//! * Frames have their own clipboard, separate from copied artwork, as in Animate: copying +//! frames never replaces copied shapes, and the reverse. +//! * A copy is cut exactly at the selection edges by splitting a scratch copy of the layer with +//! the same keyframe logic as F6, so a span that starts before the selection, or is +//! mid-tween, comes out as it looks there. +//! * Paste inserts (later frames move right), which is what Animate's Paste Frames does and so +//! what its users expect. Several copied layers land on the target layer and the ones below +//! it; missing layers are created. Pasted elements get fresh ids, mapped consistently within +//! one paste so tweens between pasted keys still pair up, and symbols they need come along +//! (also from another document). + +use crate::cmds_modify::{collect_symbols, import_symbols}; +use crate::cmds_timeline::{count_param, insert_keyframe_at, remove_frame, shift_after, target, target_layers}; +use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session}; +use anicraft_doc::{Element, ElementId, Keyframe, Layer, LayerId, Symbol}; +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("timeline.cut_frames", "Cut Frames", "Edit/Timeline", Some("Ctrl+Alt+X"), "{layer? | layers?: [..], frame?, count?}", true, cut_frames as crate::RunFn), + c("timeline.copy_frames", "Copy Frames", "Edit/Timeline", Some("Ctrl+Alt+C"), "{layer? | layers?: [..], frame?, count?}", false, copy_frames), + c("timeline.paste_frames", "Paste Frames", "Edit/Timeline", Some("Ctrl+Alt+V"), "{layer?, frame?} (top layer and first frame; default: active layer, playhead)", true, paste_frames), + ] +} + +/// One copied layer's frames; keyframe starts are relative to the first copied frame. +#[derive(Clone, Debug)] +pub struct FrameSlice { + pub name: String, + pub keys: Vec>, +} + +/// Copied frames: one slice per layer (top to bottom), `count` frames wide. +#[derive(Clone, Debug, Default)] +pub struct FrameClipboard { + pub layers: Vec, + pub count: u32, + pub symbols: Vec>, +} + +impl FrameClipboard { + pub fn is_empty(&self) -> bool { + self.layers.iter().all(|l| l.keys.is_empty()) + } +} + +/// The keyframes covering `frame..frame + count` of `layer`, cut at both edges. +fn slice(layer: &Layer, frame: u32, count: u32) -> Result>> { + let end = layer.end_frame(); + if frame >= end { + return Ok(Vec::new()); + } + let stop = frame.saturating_add(count).min(end); + let mut l = layer.clone(); + if l.keyframe_index_at(frame).is_some() { + insert_keyframe_at(&mut l, frame, true)?; + } + if stop < end && l.keyframe_index_at(stop).is_some() { + insert_keyframe_at(&mut l, stop, true)?; + } + Ok(l.keyframes + .iter() + .filter(|k| k.start >= frame && k.start < stop) + .map(|k| { + let mut k = (**k).clone(); + k.duration = k.duration.min(stop - k.start); + k.start -= frame; + Arc::new(k) + }) + .collect()) +} + +fn copy_frames(s: &mut Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + let count = count_param(p)?; + let mut ids = target_layers(s, p)?; + // Top to bottom, whatever order the params gave. + let order: Vec = s.doc.timeline.layers.iter().map(|l| l.id).collect(); + ids.sort_by_key(|id| order.iter().position(|o| o == id)); + let mut layers = Vec::with_capacity(ids.len()); + for id in ids { + let l = s.doc.timeline.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + layers.push(FrameSlice { name: l.name.clone(), keys: slice(l, frame, count)? }); + } + let clip = FrameClipboard { layers, count, symbols: Vec::new() }; + if clip.is_empty() { + return Err(EngineError::State("no frames there to copy".into())); + } + let elements: Vec = clip.layers.iter().flat_map(|l| l.keys.iter().flat_map(|k| k.elements.iter().map(|e| (**e).clone()))).collect(); + let symbols = collect_symbols(s, &elements); + let n = clip.layers.len(); + s.frame_clipboard = FrameClipboard { symbols, ..clip }; + Ok(json!({"copied": count, "layers": n})) +} + +fn cut_frames(s: &mut Session, p: &Value) -> Result { + copy_frames(s, p)?; + remove_frame(s, p)?; + Ok(json!({"cut": s.frame_clipboard.count, "layers": s.frame_clipboard.layers.len()})) +} + +fn paste_frames(s: &mut Session, p: &Value) -> Result { + if s.frame_clipboard.is_empty() { + return Err(EngineError::State("no frames have been copied".into())); + } + let (top, frame) = target(s, p)?; + let top = top.unwrap_or(s.layer); + let clip = s.frame_clipboard.clone(); + if frame.saturating_add(clip.count) > MAX_FRAME || s.doc.frame_count().saturating_add(clip.count) > MAX_FRAME { + return Err(EngineError::State("the timeline would grow past its maximum length".into())); + } + let mut row = s.doc.timeline.layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?; + import_symbols(s, &clip.symbols); + let mut remap: HashMap = HashMap::new(); + let mut pasted = Vec::new(); + for sl in &clip.layers { + // Missing layers below are created, named after the copied ones. + if s.doc.timeline.layers.get(row).is_none() { + if s.doc.timeline.layers.len() >= 1000 { + return Err(EngineError::State("too many layers (limit 1000)".into())); + } + let id = LayerId(s.doc.alloc_id()); + let mut l = Layer::new(id, sl.name.clone()); + if !sl.keys.is_empty() { + // The pasted keys are its frames (no stray blank frame at 1). + l.keyframes.clear(); + } + s.doc.timeline.layers.push(Arc::new(l)); + } + let mut keys = Vec::with_capacity(sl.keys.len()); + for k in &sl.keys { + let mut k = (**k).clone(); + k.start += frame; + for e in &mut k.elements { + let old = e.id; + let new = *remap.entry(old).or_insert_with(|| ElementId(s.doc.alloc_id())); + Arc::make_mut(e).id = new; + } + keys.push(Arc::new(k)); + } + let Some(layer) = s.doc.timeline.layers.get_mut(row).map(Arc::make_mut) else { continue }; + if layer.keyframe_index_at(frame).is_some() { + insert_keyframe_at(layer, frame, true)?; + } + shift_after(layer, frame, i64::from(clip.count)); + layer.keyframes.extend(keys); + layer.normalize(); + pasted.push(layer.id.0); + row += 1; + } + s.selection.clear(); + Ok(json!({"pasted": clip.count, "layers": pasted})) +} diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs new file mode 100644 index 00000000..4ee22600 --- /dev/null +++ b/crates/engine/src/cmds_modify.rs @@ -0,0 +1,306 @@ +//! Clipboard (cut/copy/paste), transforms (free transform, rotate 90°, flip) and alignment. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind, Symbol, SymbolId}; +use anicraft_geom::{Affine, Rect, Vec2}; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("edit.cut", "Cut", "Edit", Some("Ctrl+X"), "{}", true, cut as crate::RunFn), + c("edit.copy", "Copy", "Edit", Some("Ctrl+C"), "{}", false, copy), + c("edit.paste", "Paste in Center", "Edit", Some("Ctrl+V"), "{x?, y?} (centre of the pasted artwork; default: offset 10 px)", true, paste), + c("edit.paste_in_place", "Paste in Place", "Edit", Some("Ctrl+Shift+V"), "{}", true, paste_in_place), + c("modify.transform", "Transform", "", None, "{a, b, c, d, e, f} affine applied in stage space (free transform)", true, transform), + c("modify.rotate_cw", "Rotate 90° CW", "Modify/Transform", Some("Ctrl+Shift+9"), "{}", true, |s, _| about_center(s, Affine::rotate(std::f32::consts::FRAC_PI_2))), + c("modify.rotate_ccw", "Rotate 90° CCW", "Modify/Transform", Some("Ctrl+Shift+7"), "{}", true, |s, _| about_center(s, Affine::rotate(-std::f32::consts::FRAC_PI_2))), + c("modify.flip_h", "Flip Horizontal", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(-1.0, 1.0))), + c("modify.flip_v", "Flip Vertical", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(1.0, -1.0))), + c("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, remove_transform), + c("align.left", "Left", "Modify/Align", Some("Ctrl+Alt+1"), "{to_stage?}", true, |s, p| align(s, p, Edge::Left)), + c("align.hcenter", "Horizontal Center", "Modify/Align", Some("Ctrl+Alt+2"), "{to_stage?}", true, |s, p| align(s, p, Edge::HCenter)), + c("align.right", "Right", "Modify/Align", Some("Ctrl+Alt+3"), "{to_stage?}", true, |s, p| align(s, p, Edge::Right)), + c("align.top", "Top", "Modify/Align", Some("Ctrl+Alt+4"), "{to_stage?}", true, |s, p| align(s, p, Edge::Top)), + c("align.vcenter", "Vertical Center", "Modify/Align", Some("Ctrl+Alt+5"), "{to_stage?}", true, |s, p| align(s, p, Edge::VCenter)), + c("align.bottom", "Bottom", "Modify/Align", Some("Ctrl+Alt+6"), "{to_stage?}", true, |s, p| align(s, p, Edge::Bottom)), + c("align.distribute_h", "Distribute Horizontal Centers", "Modify/Align", None, "{}", true, |s, _| distribute(s, true)), + c("align.distribute_v", "Distribute Vertical Centers", "Modify/Align", None, "{}", true, |s, _| distribute(s, false)), + ] +} + +// ----- clipboard -------------------------------------------------------------------------------- + +/// Copied artwork: elements as they look at the playhead, plus every symbol they need, so a +/// paste into another document is complete. +#[derive(Clone, Default)] +pub struct Clipboard { + pub elements: Vec, + pub symbols: Vec>, +} + +impl Clipboard { + pub fn is_empty(&self) -> bool { + self.elements.is_empty() + } +} + +fn symbol_refs(e: &Element) -> Option { + match &e.kind { + ElementKind::Symbol { symbol, .. } => Some(*symbol), + ElementKind::Shape(_) => None, + } +} + +/// Symbols reachable from `roots` (bounded walk; libraries may be cyclic). +pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec> { + let mut seen: HashSet = HashSet::new(); + let mut stack: Vec = roots.iter().filter_map(symbol_refs).collect(); + let mut out = Vec::new(); + while let Some(id) = stack.pop() { + if !seen.insert(id) || seen.len() > 10_000 { + continue; + } + let Some(sym) = s.doc.library.iter().find(|x| x.id == id) else { continue }; + for l in &sym.timeline.layers { + for k in &l.keyframes { + stack.extend(k.elements.iter().filter_map(|e| symbol_refs(e))); + } + } + out.push(sym.clone()); + } + out +} + +fn copy(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + // What you see is what you copy: the evaluated state at the playhead (tweens applied). + let elements: Vec = s.visible_elements().iter().filter(|e| sel.contains(&e.id)).map(|e| (**e).clone()).collect(); + let symbols = collect_symbols(s, &elements); + let n = elements.len(); + s.clipboard = Clipboard { elements, symbols }; + Ok(json!({"copied": n})) +} + +fn cut(s: &mut Session, p: &Value) -> Result { + copy(s, p)?; + crate::cmds_draw::delete(s, p)?; + Ok(json!({"cut": s.clipboard.elements.len()})) +} + +fn clipboard_bounds(s: &Session) -> Rect { + s.clipboard.elements.iter().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e))) +} + +fn clip_element_bounds(s: &Session, e: &Element) -> Rect { + // Symbols may come from another document: look them up in the clipboard first. + let mut doc = s.doc.clone(); + for sym in &s.clipboard.symbols { + if doc.symbol(sym.id).is_none() { + doc.library.push(sym.clone()); + } + } + e.bounds(&doc) +} + +fn paste_with(s: &mut Session, offset: Vec2) -> Result { + if s.clipboard.is_empty() { + return Err(EngineError::State("the clipboard is empty".into())); + } + import_symbols(s, &s.clipboard.symbols.clone()); + let mut fresh = Vec::new(); + let mut out = Vec::new(); + for e in s.clipboard.elements.clone() { + let mut e = e; + e.id = ElementId(s.doc.alloc_id()); + e.transform = Affine::translate(offset.x, offset.y).mul(&e.transform); + fresh.push(e.id); + out.push(Arc::new(e)); + } + let kf = s.editable_keyframe()?; + if kf.elements.len() + out.len() > 100_000 { + return Err(EngineError::State("too many elements on this keyframe".into())); + } + kf.elements.extend(out); + s.selection = fresh.clone(); + Ok(json!({"pasted": fresh.iter().map(|e| e.0).collect::>()})) +} + +/// Adds the symbols this document lacks (from a clipboard, maybe another document's) and +/// moves the id counter past every id they use, so new ids stay unique. +pub(crate) fn import_symbols(s: &mut Session, symbols: &[Arc]) { + let mut max_id = 0u64; + for sym in symbols.iter().cloned() { + if s.doc.symbol(sym.id).is_none() { + max_id = max_id.max(sym.id.0); + for l in &sym.timeline.layers { + max_id = max_id.max(l.id.0); + for k in &l.keyframes { + for e in &k.elements { + max_id = max_id.max(e.id.0); + } + } + } + s.doc.library.push(sym); + } + } + s.doc.next_id = s.doc.next_id.max(max_id.saturating_add(1)); +} + +fn paste(s: &mut Session, p: &Value) -> Result { + let offset = match (opt_f32(p, "x")?, opt_f32(p, "y")?) { + (Some(x), Some(y)) => { + let b = clipboard_bounds(s); + if b.is_empty() { Vec2::new(10.0, 10.0) } else { Vec2::new(x, y) - b.center() } + } + _ => Vec2::new(10.0, 10.0), + }; + paste_with(s, offset) +} + +fn paste_in_place(s: &mut Session, _: &Value) -> Result { + paste_with(s, Vec2::ZERO) +} + +// ----- transforms ------------------------------------------------------------------------------- + +/// Applies `m` (stage space) to every selected element: `t' = m · t`. +pub(crate) fn apply(s: &mut Session, m: &Affine) -> Result { + if !m.is_finite() || m.determinant().abs() < 1e-8 { + return Err(EngineError::Param("the transform is degenerate (it would collapse the artwork)".into())); + } + let els = s.selected_elements_mut()?; + let n = els.len(); + for e in els { + let t = m.mul(&e.transform); + let d = t.decompose(); + if !t.is_finite() || d.sx.abs() > 10_000.0 || d.sy.abs() > 10_000.0 || d.sx.abs() < 1e-4 || d.sy.abs() < 1e-4 { + return Err(EngineError::Param("the transform would make an element too large or too small".into())); + } + e.transform = t; + } + Ok(n) +} + +fn transform(s: &mut Session, p: &Value) -> Result { + let m = Affine { m: [f32_req(p, "a")?, f32_req(p, "b")?, f32_req(p, "c")?, f32_req(p, "d")?, f32_req(p, "e")?, f32_req(p, "f")?] }; + let n = apply(s, &m)?; + Ok(json!({"transformed": n})) +} + +/// `m` applied about the centre of the selection's bounds. +/// Remove Transform: scale, rotation and skew go back to none; each element keeps its +/// position (registration point). +fn remove_transform(s: &mut Session, _: &Value) -> Result { + let els = s.selected_elements_mut()?; + let n = els.len(); + for e in els { + let t = e.transform.translation(); + e.transform = Affine::translate(t.x, t.y); + } + Ok(json!({"reset": n})) +} + +fn about_center(s: &mut Session, m: Affine) -> Result { + let b = s.selection_bounds(); + if b.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let c = b.center(); + let full = Affine::translate(c.x, c.y).mul(&m).mul(&Affine::translate(-c.x, -c.y)); + let n = apply(s, &full)?; + Ok(json!({"transformed": n})) +} + +// ----- align ------------------------------------------------------------------------------------ + +#[derive(Clone, Copy)] +enum Edge { + Left, + HCenter, + Right, + Top, + VCenter, + Bottom, +} + +fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(ElementId, Vec2)> { + bounds + .iter() + .map(|(id, b)| { + let d = match edge { + Edge::Left => Vec2::new(target.min.x - b.min.x, 0.0), + Edge::HCenter => Vec2::new(target.center().x - b.center().x, 0.0), + Edge::Right => Vec2::new(target.max.x - b.max.x, 0.0), + Edge::Top => Vec2::new(0.0, target.min.y - b.min.y), + Edge::VCenter => Vec2::new(0.0, target.center().y - b.center().y), + Edge::Bottom => Vec2::new(0.0, target.max.y - b.max.y), + }; + (*id, d) + }) + .collect() +} + +fn translate_each(s: &mut Session, moves: &[(ElementId, Vec2)]) -> Result { + let kf = s.editable_keyframe()?; + let mut n = 0; + for (id, d) in moves { + if d.x == 0.0 && d.y == 0.0 { + continue; // untouched elements stay shared with the undo snapshot + } + for e in kf.elements_mut_where(|e| e == *id) { + e.transform = Affine::translate(d.x, d.y).mul(&e.transform); + n += 1; + } + } + Ok(n) +} + +fn selected_bounds(s: &Session) -> Vec<(ElementId, Rect)> { + s.selection.iter().map(|id| (*id, s.element_bounds(*id))).filter(|(_, b)| !b.is_empty()).collect() +} + +fn align(s: &mut Session, p: &Value, edge: Edge) -> Result { + let bounds = selected_bounds(s); + if bounds.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + // One element aligns to the stage (there is nothing else to align it with). + let to_stage = opt_bool(p, "to_stage")?.unwrap_or(bounds.len() == 1); + let target = if to_stage { + Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32) + } else { + bounds.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)) + }; + let moves = moves_for(&bounds, target, edge); + let n = translate_each(s, &moves)?; + Ok(json!({"moved": n, "to_stage": to_stage})) +} + +fn distribute(s: &mut Session, horizontal: bool) -> Result { + let mut bounds = selected_bounds(s); + if bounds.len() < 3 { + return Err(EngineError::State("select at least three elements to distribute".into())); + } + let key = |b: &Rect| if horizontal { b.center().x } else { b.center().y }; + bounds.sort_by(|a, b| key(&a.1).total_cmp(&key(&b.1))); + let (Some(first), Some(last)) = (bounds.first(), bounds.last()) else { return Ok(json!({"moved": 0})) }; + let (a, z) = (key(&first.1), key(&last.1)); + let step = (z - a) / (bounds.len() - 1) as f32; + let moves: Vec<(ElementId, Vec2)> = bounds + .iter() + .enumerate() + .map(|(i, (id, b))| { + let d = a + step * i as f32 - key(b); + (*id, if horizontal { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) }) + }) + .collect(); + let n = translate_each(s, &moves)?; + Ok(json!({"moved": n})) +} diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs new file mode 100644 index 00000000..c364f229 --- /dev/null +++ b/crates/engine/src/cmds_paint.rs @@ -0,0 +1,279 @@ +//! Paint Bucket and Ink Bottle. +//! +//! AniCraft shapes are independent objects (like object drawing), so a fill for an area +//! enclosed by several shapes has to be found, not looked up: +//! +//! 1. Click on a filled shape: it is recoloured. +//! 2. Otherwise the active layer at the playhead is rasterized into a "wall" mask with the +//! renderer's own coverage rasterizer (fills and stroke outlines), walls are thickened by the +//! gap size so small openings close, and the area is flood-filled from the click. +//! 3. An area that reaches the edge of the artwork is not enclosed: nothing is added and the +//! message suggests a larger gap. +//! 4. The region is grown back under the walls (so no hairline shows between fill and line), +//! traced into closed contours (`geom::trace`), fitted with curves (`geom::fit_curve`) and +//! added as a fill-only shape at the bottom of the layer, below the lines that bound it. +//! +//! The grid is at most `MAX_GRID` cells on its long side (cell size grows for big artwork), so +//! the cost is bounded whatever the document. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ColorEffect, DisplayItem, Element, ElementId, ElementKind, Paint, Shape, Stroke}; +use anicraft_geom::trace::contours; +use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2, fit_curve}; +use anicraft_render::raster::{Coverage, IRect}; +use anicraft_render::stroke::stroke_polygons; +use serde_json::{Value, json}; +use std::collections::VecDeque; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("paint.bucket", "Paint Bucket", "", None, "{x, y, color?, gap? (stage units: how wide an opening still counts as closed)}", true, bucket as crate::RunFn), + c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?}", true, ink), + ] +} + +/// Longest side of the flood-fill grid, in cells. +const MAX_GRID: f32 = 1400.0; + +/// Items of the active layer at the playhead, back to front. +fn layer_items(s: &Session) -> Vec { + s.display_list().items.iter().filter(|i| i.layer == s.layer && i.outline.is_none()).cloned().collect() +} + +/// Topmost item of the active layer under `p`: `(element, inside its fill)`. +fn pick(items: &[DisplayItem], p: Vec2, slop: f32) -> Option<(ElementId, bool)> { + items.iter().rev().find_map(|it| { + let hw = it.stroke.map_or(0.0, |s| s.width * 0.5 * it.transform.mean_scale()); + if !it.path.bounds().transformed(&it.transform).inflate(hw + slop).contains(p) { + return None; + } + let inside = it.fill.is_some() && it.path.contains(p, &it.transform, it.fill_rule); + (inside || it.path.distance_to_edge(p, &it.transform) <= hw + slop).then_some((it.element, inside)) + }) +} + +fn element_shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> { + let kf = s.editable_keyframe()?; + let el = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State("that shape is not on the active layer at this frame".into()))?; + match &mut el.kind { + ElementKind::Shape(sh) => Ok(sh), + ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances keep their own colours; break it apart (Ctrl+B) or edit the symbol to paint it".into())), + } +} + +fn bucket(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let color = opt_color(p, "color")?.unwrap_or(s.style.fill); + let gap = opt_f32(p, "gap")?.unwrap_or(0.0); + if !(0.0..=1000.0).contains(&gap) { + return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into())); + } + let items = layer_items(s); + // 1. On a fill: recolour it. + if let Some((id, true)) = pick(&items, at, 0.0) { + element_shape_mut(s, id)?.fill = Some(Paint::Solid(color)); + return Ok(json!({"recolored": id.0})); + } + // 2. Find the enclosed area. + let Some(path) = enclosed_region(&items, at, gap)? else { + return Err(EngineError::State("this area isn't closed. Close the outline, or choose a larger gap size".into())); + }; + let c = path.bounds().center(); + let local = path.transformed(&Affine::translate(-c.x, -c.y)); + let id = ElementId(s.doc.alloc_id()); + let el = Element { + id, + name: String::new(), + transform: Affine::translate(c.x, c.y), + color: ColorEffect::default(), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(Paint::Solid(color)), stroke: None, fill_rule: FillRule::EvenOdd }), + }; + let kf = s.editable_keyframe()?; + if kf.elements.len() >= 100_000 { + return Err(EngineError::State("too many elements on this keyframe".into())); + } + // Under everything on the layer, so the lines that bound it stay on top. + kf.elements.insert(0, Arc::new(el)); + Ok(json!({"element": id.0})) +} + +/// Grid over stage space: origin and cell size. +struct Grid { + origin: Vec2, + cell: f32, +} + +impl Grid { + fn to_px(&self) -> Affine { + Affine::scale(1.0 / self.cell, 1.0 / self.cell).mul(&Affine::translate(-self.origin.x, -self.origin.y)) + } +} + +/// The area around `at` enclosed by the layer's artwork, as a stage-space path; `None` when it +/// is not enclosed (or there is no artwork around it). +fn enclosed_region(items: &[DisplayItem], at: Vec2, gap: f32) -> Result> { + let mut bounds = Rect::EMPTY; + for it in items { + let pad = it.stroke.map_or(0.0, |s| s.width * 0.5 * it.transform.mean_scale()); + bounds = bounds.union(&it.path.bounds().inflate(pad).transformed(&it.transform)); + } + if bounds.is_empty() || !bounds.contains(at) || !(bounds.min.is_finite() && bounds.max.is_finite()) { + return Ok(None); + } + let extent = bounds.width().max(bounds.height()); + let cell = (extent / MAX_GRID).max(0.5); + // One free cell of margin all round: anything that reaches it is outside. + let origin = bounds.min - Vec2::new(cell, cell); + let w = (bounds.width() / cell).ceil() as usize + 3; + let h = (bounds.height() / cell).ceil() as usize + 3; + let g = Grid { origin, cell }; + let m = g.to_px(); + let mut wall = vec![0.0f32; w * h]; + let mut row = Vec::new(); + for it in items { + let to_px = m.mul(&it.transform); + let mut polys: Vec<(Vec>, FillRule)> = Vec::new(); + let lines = it.path.flatten(&to_px, 0.2); + if it.fill.is_some() { + polys.push((lines.iter().map(|l| l.points.clone()).collect(), it.fill_rule)); + } + if let Some(st) = it.stroke { + let hw = (st.width * 0.5 * it.transform.mean_scale() / cell).max(0.5); + polys.push((stroke_polygons(&lines, hw), FillRule::NonZero)); + } + for (pp, rule) in polys { + let mut bb = Rect::EMPTY; + for q in pp.iter().flatten() { + bb.include(*q); + } + if bb.is_empty() { + continue; + } + let ir = IRect { x0: (bb.min.x.floor() as i32).max(0), y0: (bb.min.y.floor() as i32).max(0), x1: (bb.max.x.ceil() as i32 + 1).min(w as i32), y1: (bb.max.y.ceil() as i32 + 1).min(h as i32) }; + if ir.is_empty() { + continue; + } + let mut cov = Coverage::new(ir); + for poly in &pp { + cov.add_polygon(poly); + } + row.resize(ir.width(), 0.0); + for y in 0..ir.height() { + cov.resolve_row(y, rule, &mut row); + let base = (ir.y0 as usize + y) * w + ir.x0 as usize; + for (x, v) in row.iter().enumerate() { + if let Some(cellv) = wall.get_mut(base + x) { + *cellv = cellv.max(*v); + } + } + } + } + } + // Any coverage is a wall, so hairlines cannot leak; then close gaps. + let mut blocked: Vec = wall.iter().map(|v| *v > 0.02).collect(); + let gap_cells = gap / cell * 0.5; + if gap_cells > 0.0 { + let d = distance(&blocked, w, h); + for (b, dv) in blocked.iter_mut().zip(&d) { + *b = *dv <= gap_cells; + } + } + // Flood fill from the click. + let cx = ((at.x - origin.x) / cell) as usize; + let cy = ((at.y - origin.y) / cell) as usize; + let start = cy * w + cx; + if blocked.get(start).copied().unwrap_or(true) { + return Ok(None); + } + let mut region = vec![false; w * h]; + let mut q = VecDeque::from([start]); + if let Some(r) = region.get_mut(start) { + *r = true; + } + while let Some(i) = q.pop_front() { + let (x, y) = (i % w, i / w); + if x == 0 || y == 0 || x + 1 >= w || y + 1 >= h { + // Reached the margin: open to the outside. + return Ok(None); + } + for n in [i - 1, i + 1, i - w, i + w] { + if !blocked.get(n).copied().unwrap_or(true) && !region.get(n).copied().unwrap_or(true) { + if let Some(r) = region.get_mut(n) { + *r = true; + } + q.push_back(n); + } + } + } + // Grow back: free cells up to the closed gap (the wall thickening took them), and cells + // under a line a little further, so the fill tucks under its outline. Never into open space + // beyond a line. + let d = distance(®ion, w, h); + let mask: Vec = d + .iter() + .zip(&wall) + .map(|(dv, wv)| { + let under_line = *wv > 0.02; + let keep = *dv == 0.0 || (!under_line && *dv <= gap_cells) || (under_line && *dv <= gap_cells + 1.5); + if keep { 1.0 } else { 0.0 } + }) + .collect(); + let loops = contours(&mask, w, h); + if loops.is_empty() { + return Ok(None); + } + let mut path = Path::new(); + for lp in loops { + let pts: Vec = lp.iter().map(|q| origin + *q * cell).collect(); + let part = fit_curve(&pts, (cell * 0.6).max(0.25), cell * 3.0, true); + path.cmds.extend(part.cmds); + } + Ok((!path.is_empty()).then_some(path)) +} + +/// Distance in cells from each cell to the nearest `true` cell (two-pass 3-4 chamfer, ≈ 2 % +/// from Euclidean). +fn distance(src: &[bool], w: usize, h: usize) -> Vec { + const FAR: f32 = 1e9; + let mut d: Vec = src.iter().map(|b| if *b { 0.0 } else { FAR }).collect(); + let (a, b) = (1.0f32, 4.0f32 / 3.0); + let at = |d: &Vec, x: isize, y: isize| -> f32 { + if x < 0 || y < 0 || x as usize >= w || y as usize >= h { FAR } else { d.get(y as usize * w + x as usize).copied().unwrap_or(FAR) } + }; + for y in 0..h as isize { + for x in 0..w as isize { + let i = y as usize * w + x as usize; + let v = d.get(i).copied().unwrap_or(FAR).min(at(&d, x - 1, y) + a).min(at(&d, x, y - 1) + a).min(at(&d, x - 1, y - 1) + b).min(at(&d, x + 1, y - 1) + b); + if let Some(c) = d.get_mut(i) { + *c = v; + } + } + } + for y in (0..h as isize).rev() { + for x in (0..w as isize).rev() { + let i = y as usize * w + x as usize; + let v = d.get(i).copied().unwrap_or(FAR).min(at(&d, x + 1, y) + a).min(at(&d, x, y + 1) + a).min(at(&d, x + 1, y + 1) + b).min(at(&d, x - 1, y + 1) + b); + if let Some(c) = d.get_mut(i) { + *c = v; + } + } + } + d +} + +fn ink(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let color = opt_color(p, "color")?.unwrap_or(s.style.stroke); + let width = opt_f32(p, "width")?.unwrap_or(s.style.stroke_width.max(1.0)); + if !(0.1..=1000.0).contains(&width) { + return Err(EngineError::Param("param 'width' must be between 0.1 and 1000".into())); + } + let slop = opt_f32(p, "slop")?.unwrap_or(3.0).clamp(0.0, 100.0); + let items = layer_items(s); + let (id, _) = pick(&items, at, slop).ok_or_else(|| EngineError::State("click a shape to give it this stroke".into()))?; + element_shape_mut(s, id)?.stroke = Some(Stroke { color, width }); + Ok(json!({"element": id.0})) +} diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs new file mode 100644 index 00000000..80cf2a69 --- /dev/null +++ b/crates/engine/src/cmds_path.rs @@ -0,0 +1,222 @@ +//! Path drawing (Pen, Pencil) and point editing (Subselection). +//! +//! Points are addressed as `(cmd, slot)` on the shape's path in its local space: slot 0 is the +//! anchor a command ends on, 1 and 2 its control points (`anicraft_geom::edit`). A closed +//! subpath's start is one anchor even though the path stores it twice; commands accept either +//! copy. Deltas and positions in params are in stage space. + +use crate::cmds_draw::{MAX_EXTENT, add_shape, style}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind, Shape}; +use anicraft_geom::edit::{ANCHOR, polyline_path, simplify}; +use anicraft_geom::{Affine, Path, PathCmd, Vec2, fit_curve}; +use serde_json::{Value, json}; +use std::collections::BTreeSet; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("draw.path", "Pen Path", "", None, "{d: SVG path data (stage space), fill?, stroke?, stroke_width?}", true, draw_path as crate::RunFn), + c( + "draw.freehand", + "Pencil Stroke", + "", + None, + "{points: [[x, y], ..], mode?: \"smooth\"|\"straighten\"|\"ink\", tolerance? (stage units), closed?, stroke?, stroke_width?}", + true, + draw_freehand, + ), + c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy}", true, move_points), + c("path.add_point", "Add Anchor Point", "", None, "{id, x, y, slop?}", true, add_point), + c("path.delete_points", "Delete Anchor Points", "", None, "{id, cmds: [..]}", true, delete_points), + c("path.convert_point", "Convert Anchor Point", "", None, "{id, cmd, smooth: bool}", true, convert_point), + ] +} + +/// Most commands one path may have (keeps one edit's cost bounded). +const MAX_CMDS: usize = 100_000; + +fn check_path(path: &Path) -> Result<()> { + if path.cmds.len() > MAX_CMDS { + return Err(EngineError::Param(format!("path has more than {MAX_CMDS} commands"))); + } + if path.anchors().len() < 2 { + return Err(EngineError::Param("a path needs at least two points".into())); + } + let b = path.bounds(); + if !(b.min.is_finite() && b.max.is_finite()) || b.width() > MAX_EXTENT || b.height() > MAX_EXTENT { + return Err(EngineError::Param("path is too large".into())); + } + if b.width().max(b.height()) < 0.5 { + return Err(EngineError::Param("path is too small".into())); + } + Ok(()) +} + +/// Adds a stage-space path as a shape whose local origin is its bounds centre. +fn add_path(s: &mut Session, kind: &str, mut path: Path, p: &Value) -> Result { + check_path(&path)?; + path.close_explicitly(); + let closed = path.cmds.iter().any(|c| matches!(c, PathCmd::Close)); + let (fill, stroke) = style(s, p, closed)?; + let c = path.bounds().center(); + let local = path.transformed(&Affine::translate(-c.x, -c.y)); + add_shape(s, kind, local, c, fill, stroke) +} + +fn draw_path(s: &mut Session, p: &Value) -> Result { + let d = str_req(p, "d")?; + if d.len() > 4_000_000 { + return Err(EngineError::Param("param 'd' is too long".into())); + } + let path = Path::from_svg(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; + add_path(s, "path", path, p) +} + +fn points_param(p: &Value, key: &str) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be a list of [x, y] pairs")); + let list = p.get(key).and_then(Value::as_array).ok_or_else(bad)?; + if list.len() > MAX_CMDS { + return Err(EngineError::Param(format!("param '{key}' has more than {MAX_CMDS} points"))); + } + list.iter() + .map(|v| { + let xy = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?; + let n = |i: usize| xy.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite()).ok_or_else(bad); + Ok(Vec2::new(n(0)?, n(1)?)) + }) + .collect() +} + +/// Pencil: "smooth" fits curves, "straighten" keeps the stroke's main straight runs, "ink" +/// follows the hand closely with short straight segments. +fn draw_freehand(s: &mut Session, p: &Value) -> Result { + let pts = points_param(p, "points")?; + let tol = opt_f32(p, "tolerance")?.unwrap_or(1.5); + if !(0.01..=1000.0).contains(&tol) { + return Err(EngineError::Param("param 'tolerance' must be between 0.01 and 1000".into())); + } + let closed = opt_bool(p, "closed")?.unwrap_or(false); + let path = match opt_str(p, "mode")?.unwrap_or("smooth") { + "smooth" => fit_curve(&pts, tol, tol * 2.0, closed), + "straighten" => polyline_path(&simplify(&pts, tol * 4.0), closed), + "ink" => polyline_path(&simplify(&pts, tol * 0.35), closed), + other => return Err(EngineError::Param(format!("unknown pencil mode '{other}' (smooth, straighten or ink)"))), + }; + // A pencil stroke is a line: no fill unless it was closed and a fill was asked for. + let mut style_params = p.clone(); + if !(closed && p.get("fill").is_some()) { + style_params["fill"] = Value::Null; + } + add_path(s, "pencil", path, &style_params) +} + +// ----- point editing ---------------------------------------------------------------------- + +/// The shape element `id` in the editable keyframe (copy-on-write), with its transform. +fn shape_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Shape, Affine)> { + let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); + if !s.visible_elements().iter().any(|e| e.id == id) { + return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0))); + } + let kf = s.editable_keyframe()?; + let el: &mut Element = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?; + let m = el.transform; + match &mut el.kind { + ElementKind::Shape(sh) => Ok((sh, m)), + ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances have no points to edit (double-click to edit the symbol)".into())), + } +} + +fn index_list(p: &Value, key: &str) -> Result> { + let v = opt_u64_list(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required")))?; + Ok(v.into_iter().map(|i| usize::try_from(i).unwrap_or(usize::MAX)).collect()) +} + +fn move_points(s: &mut Session, p: &Value) -> Result { + let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); + let bad = || EngineError::Param("param 'points' must be a list of [cmd, slot] pairs".into()); + let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?; + let mut wanted = Vec::with_capacity(list.len().min(MAX_CMDS)); + for v in list.iter().take(MAX_CMDS) { + let pair = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?; + let cmd = pair.first().and_then(Value::as_u64).ok_or_else(bad)?; + let slot = pair.get(1).and_then(Value::as_u64).filter(|s| *s <= 2).ok_or_else(bad)?; + wanted.push((usize::try_from(cmd).unwrap_or(usize::MAX), slot as u8)); + } + let (sh, m) = shape_mut(s, p)?; + let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?; + let local = inv.apply_vector(d); + if !local.is_finite() { + return Err(EngineError::Param("the move is too large".into())); + } + let path = Arc::make_mut(&mut sh.path); + // Anchors bring their handles and their twin at a closed start; each point moves once. + let mut set = BTreeSet::new(); + for (cmd, slot) in wanted { + if path.point(cmd, slot).is_none() { + return Err(EngineError::Param(format!("no point ({cmd}, {slot}) on this path"))); + } + if slot == ANCHOR { + set.extend(path.anchor_group(cmd)); + } else { + set.insert((cmd, slot)); + } + } + for &(cmd, slot) in &set { + if let Some(q) = path.point(cmd, slot) { + path.set_point(cmd, slot, q + local); + } + } + check_path(path)?; + Ok(json!({"moved": set.len()})) +} + +fn add_point(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 1000.0); + let (sh, m) = shape_mut(s, p)?; + let path = Arc::make_mut(&mut sh.path); + path.close_explicitly(); + let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the path has no segments".into()))?; + if dist > slop { + return Err(EngineError::State("no segment there".into())); + } + if path.cmds.len() >= MAX_CMDS || !path.split_segment(cmd, t) { + return Err(EngineError::State("cannot add a point there".into())); + } + Ok(json!({"cmd": cmd})) +} + +fn delete_points(s: &mut Session, p: &Value) -> Result { + let cmds = index_list(p, "cmds")?; + let (sh, _) = shape_mut(s, p)?; + let path = Arc::make_mut(&mut sh.path); + // Highest first, so earlier indices stay valid; twins collapse onto one anchor. + let order: BTreeSet = cmds.iter().map(|&c| path.canonical_anchor(c)).collect(); + let mut removed = 0; + for cmd in order.into_iter().rev() { + if path.remove_anchor(cmd) { + removed += 1; + } + } + if removed == 0 { + return Err(EngineError::State("a path keeps at least two points (delete the shape instead)".into())); + } + Ok(json!({"deleted": removed})) +} + +fn convert_point(s: &mut Session, p: &Value) -> Result { + let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?; + let cmd = usize::try_from(cmd).unwrap_or(usize::MAX); + let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?; + let (sh, _) = shape_mut(s, p)?; + let path = Arc::make_mut(&mut sh.path); + if path.point(cmd, ANCHOR).is_none() { + return Err(EngineError::Param(format!("no anchor {cmd} on this path"))); + } + let changed = if smooth { path.make_smooth(cmd) } else { path.make_corner(cmd) }; + Ok(json!({"changed": changed})) +} diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs new file mode 100644 index 00000000..3b4bc58a --- /dev/null +++ b/crates/engine/src/cmds_timeline.rs @@ -0,0 +1,632 @@ +//! Timeline and layer commands. + +use crate::params::*; +use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session}; +use anicraft_doc::{Keyframe, Layer, LayerId, LayerKind, Tween, evaluate_layer_elements}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("timeline.insert_frame", "Frame", "Insert/Timeline", Some("F5"), "{layer? | layers?: [..], frame?, count?}", true, insert_frame as crate::RunFn), + c("timeline.remove_frame", "Remove Frame", "Insert/Timeline", Some("Shift+F5"), "{layer? | layers?: [..], frame?, count?}", true, remove_frame), + c("timeline.insert_keyframe", "Keyframe", "Insert/Timeline", Some("F6"), "{layer? | layers?: [..], frame?}", true, insert_keyframe), + 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_tween", "Create Classic Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_tween), + c("timeline.remove_tween", "Remove Tween", "Insert", None, "{layer?, frame?}", true, remove_tween), + c("timeline.set_easing", "Set Tween Easing", "", None, "{easing, layer?, frame?}", true, set_easing), + c("timeline.set_label", "Frame Label", "", None, "{label, layer?, frame?}", true, set_label), + c("timeline.goto", "Go to Frame", "", None, "{frame}", false, goto), + c("timeline.next_frame", "Next Frame", "Control", Some("."), "{}", false, |s, _| step(s, 1)), + c("timeline.prev_frame", "Previous Frame", "Control", Some(","), "{}", false, |s, _| step(s, -1)), + c("timeline.first_frame", "Go to First Frame", "Control", Some("Home"), "{}", false, |s, _| { + s.set_frame(0); + Ok(json!({"frame": 0})) + }), + c("timeline.last_frame", "Go to Last Frame", "Control", Some("End"), "{}", false, |s, _| { + let f = s.frame_count().saturating_sub(1); + s.set_frame(f); + Ok(json!({"frame": f})) + }), + c("layer.new", "New Layer", "Insert/Timeline", None, "{name?}", true, new_layer), + c("layer.delete", "Delete Layer", "Modify/Timeline", None, "{layer?}", true, delete_layer), + c("layer.rename", "Rename Layer", "", None, "{name, layer?}", true, rename_layer), + c("layer.toggle_visible", "Show/Hide Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.visible = !l.visible)), + c("layer.toggle_lock", "Lock/Unlock Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.locked = !l.locked)), + c("layer.toggle_outline", "Outline Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.outline = !l.outline)), + c("layer.select", "Select Layer", "", None, "{layer: id} or {index}", false, select_layer), + c("layer.move_up", "Move Layer Up", "Modify/Timeline", None, "{layer?}", true, |s, p| move_layer(s, p, -1)), + c("layer.move_down", "Move Layer Down", "Modify/Timeline", None, "{layer?}", true, |s, p| move_layer(s, p, 1)), + c("layer.toggle_mask", "Mask", "Modify/Timeline", None, "{layer?}", true, toggle_mask), + c("layer.set_type", "Layer Type", "", None, "{type: normal|mask|masked|guide, layer?}", true, set_layer_type), + ] +} + +/// The mask command: turns a layer into a mask over the normal layer directly under it, or a +/// mask back into a normal layer (its masked layers become normal too). +fn toggle_mask(s: &mut Session, p: &Value) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + let is_mask = s.doc.timeline.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask; + let ty = if is_mask { "normal" } else { "mask" }; + set_type(s, id, ty)?; + if !is_mask { + let tl = &mut s.doc.timeline; + if let Some(i) = tl.layers.iter().position(|l| l.id == id) + && let Some(below) = tl.layers.get_mut(i + 1) + && below.kind == LayerKind::Normal + && below.parent.is_none() + { + Arc::make_mut(below).parent = Some(id); + } + } + Ok(layer_type_json(s, id)) +} + +fn set_layer_type(s: &mut Session, p: &Value) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + set_type(s, id, str_req(p, "type")?)?; + Ok(layer_type_json(s, id)) +} + +fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { + let tl = &mut s.doc.timeline; + let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let (kind, parent) = match ty { + "normal" => (LayerKind::Normal, None), + "mask" => (LayerKind::Mask, None), + "guide" => (LayerKind::Guide, None), + "masked" => { + let m = tl.mask_above(i).ok_or_else(|| EngineError::State("only a layer directly under a mask layer (or its masked layers) can be masked".into()))?; + (LayerKind::Normal, Some(m)) + } + other => return Err(EngineError::Param(format!("unknown layer type '{other}' (normal, mask, masked or guide)"))), + }; + let l = tl.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + l.kind = kind; + l.parent = parent; + tl.repair_masks(); + Ok(()) +} + +fn layer_type_json(s: &Session, id: LayerId) -> Value { + let Some(l) = s.doc.timeline.layer(id) else { return json!({}) }; + let ty = match (l.kind, l.parent) { + (LayerKind::Mask, _) => "mask", + (LayerKind::Guide, _) => "guide", + (LayerKind::Normal, Some(_)) => "masked", + (LayerKind::Normal, None) => "normal", + }; + json!({"layer": id.0, "type": ty, "masked_by": l.parent.map(|p| p.0)}) +} + +pub(crate) fn target(s: &Session, p: &Value) -> Result<(Option, u32)> { + let layer = opt_u64(p, "layer")?.map(LayerId); + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); + if frame > MAX_FRAME { + return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); + } + Ok((layer, frame)) +} + +/// Layers a range command acts on: `layers: [ids]`, else `layer`, else the active layer. +pub(crate) fn target_layers(s: &Session, p: &Value) -> Result> { + let ids = match opt_u64_list(p, "layers")? { + Some(v) if !v.is_empty() => v.into_iter().map(LayerId).collect(), + Some(_) => return Err(EngineError::Param("param 'layers' must not be empty".into())), + None => vec![opt_u64(p, "layer")?.map_or(s.layer, LayerId)], + }; + let mut out: Vec = Vec::with_capacity(ids.len()); + for id in ids { + if s.doc.timeline.layer(id).is_none() { + return Err(EngineError::State(format!("no layer with id {}", id.0))); + } + if !out.contains(&id) { + out.push(id); + } + } + Ok(out) +} + +/// Frames a range command spans (`count`, default 1). +pub(crate) fn count_param(p: &Value) -> Result { + let n = opt_u32(p, "count")?.unwrap_or(1); + if !(1..=10_000).contains(&n) { + return Err(EngineError::Param("param 'count' must be between 1 and 10,000".into())); + } + Ok(n) +} + +/// Shifts keyframes starting at or after `from` by `delta` frames. +pub(crate) fn shift_after(layer: &mut Layer, from: u32, delta: i64) { + for k in layer.keyframes.iter_mut().filter(|k| k.start >= from).map(Arc::make_mut) { + k.start = (i64::from(k.start) + delta).clamp(0, i64::from(MAX_FRAME)) as u32; + } +} + +/// F5 over a range: `count` frames on each target layer. +fn insert_frame(s: &mut Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + let count = count_param(p)?; + let mut frames = 0; + for id in target_layers(s, p)? { + let layer = s.layer_mut(Some(id))?; + for _ in 0..count { + insert_frame_at(layer, frame)?; + } + frames = frames.max(layer.end_frame()); + } + Ok(json!({"frames": frames})) +} + +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())); + } + match layer.keyframe_index_at(frame) { + Some(i) => { + if let Some(k) = layer.keyframe_mut(i) { + k.duration += 1; + } + shift_after(layer, frame + 1, 1); + } + None => match layer.keyframes.iter().rposition(|k| k.start <= frame) { + // extend the previous keyframe up to and including `frame` + Some(i) => { + let next_start = layer.keyframes.get(i + 1).map(|k| k.start); + if let Some(k) = layer.keyframe_mut(i) { + let want = frame + 1 - k.start; + k.duration = next_start.map_or(want, |n| want.min(n - k.start)); + } + } + None => layer.keyframes.insert(0, Arc::new(Keyframe::new(frame, 1))), + }, + } + layer.normalize(); + Ok(()) +} + +/// Shift+F5 over a range: removes up to `count` frames on each target layer. Layers that run +/// out of frames stop early; it fails only when nothing could be removed. +pub(crate) fn remove_frame(s: &mut Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + let count = count_param(p)?; + let mut removed = 0u32; + let mut first_err = None; + for id in target_layers(s, p)? { + let layer = s.layer_mut(Some(id))?; + for _ in 0..count { + match remove_frame_at(layer, frame) { + Ok(()) => removed += 1, + Err(e) => { + first_err.get_or_insert(e); + break; + } + } + } + } + match (removed, first_err) { + (0, Some(e)) => Err(e), + _ => Ok(json!({"removed": removed, "frames": s.doc.frame_count()})), + } +} + +fn remove_frame_at(layer: &mut Layer, frame: u32) -> Result<()> { + let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; + let dur = layer.keyframes.get(i).map_or(1, |k| k.duration); + if dur > 1 { + if let Some(k) = layer.keyframe_mut(i) { + k.duration -= 1; + } + } else { + if layer.keyframes.len() == 1 { + return Err(EngineError::State("cannot remove the layer's only frame".into())); + } + layer.keyframes.remove(i); + } + shift_after(layer, frame + 1, -1); + layer.normalize(); + Ok(()) +} + +/// Inserts a keyframe at `frame` (F6 when `copy`, F7 otherwise). Inside a tween the new key +/// captures the tweened state, so the motion is unchanged. +pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> Result<()> { + if frame > MAX_FRAME { + return Err(EngineError::Param(format!("frame must be at most {MAX_FRAME}"))); + } + if layer.keyframe_starting_at(frame).is_some() { + if !copy { + // F7 on a keyframe clears it + if let Some(k) = layer.keyframe_starting_at(frame).and_then(|i| layer.keyframe_mut(i)) { + k.elements.clear(); + k.tween = None; + } + } + return Ok(()); + } + let elements = if copy { evaluate_layer_elements(layer, frame).map(|(_, e)| e.into_owned()) } else { 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 }; + k.duration = frame - k.start; + let mut nk = Keyframe::new(frame, end - frame); + nk.elements = elements.unwrap_or_default(); + nk.tween = tween; + layer.keyframes.insert(i + 1, Arc::new(nk)); + } + None => { + // Past the end or in a gap: extend the previous key and copy its last state. + let prev = layer.keyframes.iter().rposition(|k| k.start < frame); + let mut nk = Keyframe::new(frame, 1); + if let Some(i) = prev { + 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(); + } + k.duration = frame - k.start; + } + if let Some(n) = next_start { + nk.duration = n - frame; + } + } + let pos = layer.keyframes.partition_point(|k| k.start < frame); + layer.keyframes.insert(pos, Arc::new(nk)); + } + } + layer.normalize(); + Ok(()) +} + +fn insert_keyframe(s: &mut Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + for id in target_layers(s, p)? { + insert_keyframe_at(s.layer_mut(Some(id))?, frame, true)?; + } + Ok(json!({"keyframe": frame})) +} + +fn insert_blank_keyframe(s: &mut Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + for id in target_layers(s, p)? { + insert_keyframe_at(s.layer_mut(Some(id))?, frame, false)?; + } + Ok(json!({"keyframe": frame})) +} + +/// Shift+F6 over a range: clears every keyframe starting in `frame..frame + count` on each +/// target layer. +fn clear_keyframe(s: &mut Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + let count = count_param(p)?; + let mut cleared = 0; + for id in target_layers(s, p)? { + let layer = s.layer_mut(Some(id))?; + let starts: Vec = layer.keyframes.iter().map(|k| k.start).filter(|&f| f >= frame && f - frame < count).collect(); + // Last first, so each removal merges into a span that is still there. + for f in starts.into_iter().rev() { + clear_keyframe_at(layer, f)?; + cleared += 1; + } + } + if cleared == 0 { + return Err(EngineError::State(if count == 1 { format!("frame {} is not a keyframe", frame + 1) } else { "no keyframes in the selected frames".into() })); + } + Ok(json!({"cleared": cleared})) +} + +/// Moves the keyframes starting in `from..=to` by `by` frames (dragging a frame selection). +/// Keyframes they land on are replaced; the span before a key moved right grows to fill the +/// frames it left, and the layer keeps its length (no frames are lost by moving left). +fn move_keyframes(s: &mut Session, p: &Value) -> Result { + let from = opt_u32(p, "from")?.ok_or_else(|| EngineError::Param("param 'from' is required".into()))?; + let to = opt_u32(p, "to")?.unwrap_or(from); + let by = p.get("by").and_then(Value::as_i64).ok_or_else(|| EngineError::Param("param 'by' must be a whole number of frames".into()))?; + if to < from || to > MAX_FRAME || by.unsigned_abs() > u64::from(MAX_FRAME) { + return Err(EngineError::Param(format!("frames must be in order and within {MAX_FRAME}"))); + } + let layer_by = match p.get("layer_by") { + None | Some(Value::Null) => 0, + Some(v) => v.as_i64().ok_or_else(|| EngineError::Param("param 'layer_by' must be a whole number of layers".into()))?, + }; + if layer_by != 0 { + return move_across_layers(s, p, from, to, by, layer_by); + } + let mut moved = 0; + for id in target_layers(s, p)? { + moved += move_keys(s.layer_mut(Some(id))?, from, to, by)?; + } + Ok(json!({"moved": moved})) +} + +/// Dragging keyframes onto other layers (`layer_by` rows down, negative = up): the frames are +/// lifted out of every source layer first (leaving blank keyframes, as in Animate), then +/// placed on the target layers, replacing what was there; frames after the landing range +/// keep their content. Lifting everything before placing anything makes overlapping row +/// ranges (dragging two rows down by one) come out right. +fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, layer_by: i64) -> Result { + let order: Vec = s.doc.timeline.layers.iter().map(|l| l.id).collect(); + let mut rows: Vec = target_layers(s, p)?.iter().filter_map(|id| order.iter().position(|o| o == id)).collect(); + rows.sort_unstable(); + let mut plan = Vec::with_capacity(rows.len()); + for &r in &rows { + let t = i64::try_from(r).unwrap_or(i64::MAX).checked_add(layer_by).filter(|t| *t >= 0 && (*t as usize) < order.len()); + let Some(t) = t else { return Err(EngineError::State("there is no layer there to move the frames to".into())) }; + let (Some(&src), Some(&dst)) = (order.get(r), order.get(t as usize)) else { continue }; + plan.push((src, dst)); + } + // 1. Lift. + let mut lifted: Vec<(LayerId, Vec)> = Vec::new(); + for &(src, dst) in &plan { + let layer = s.layer_mut(Some(src))?; + let keys: Vec = layer.keyframes.iter().filter(|k| k.start >= from && k.start <= to).map(|k| (**k).clone()).collect(); + if let (Some(first), Some(last)) = (keys.first().map(|k| k.start), keys.last().map(Keyframe::end)) { + layer.keyframes.retain(|k| !(k.start >= from && k.start <= to)); + // The frames stay; their content leaves. + layer.keyframes.push(Arc::new(Keyframe::new(first, last - first))); + layer.normalize(); + } + lifted.push((dst, keys)); + } + // 2. Place. + let mut moved = 0; + for (dst, keys) in lifted { + let (Some(first), Some(last)) = (keys.first().map(|k| k.start), keys.last().map(Keyframe::end)) else { continue }; + let (a, b) = (i64::from(first) + by, i64::from(last) + by); + if a < 0 || b > i64::from(MAX_FRAME) + 1 { + return Err(EngineError::State(if a < 0 { "keyframes cannot move before frame 1".into() } else { "keyframes would move past the end of the timeline".into() })); + } + let (a, b) = (a as u32, b as u32); + let layer = s.layer_mut(Some(dst))?; + // Cut the target at both ends of the landing range so what lies outside it stays. + if layer.keyframe_index_at(a).is_some_and(|i| layer.keyframes.get(i).is_some_and(|k| k.start < a)) { + insert_keyframe_at(layer, a, true)?; + } + if b < layer.end_frame() && layer.keyframe_index_at(b).is_some() { + insert_keyframe_at(layer, b, true)?; + } + layer.keyframes.retain(|k| !(k.start >= a && k.start < b)); + for mut k in keys { + k.start = (i64::from(k.start) + by) as u32; + layer.keyframes.push(Arc::new(k)); + moved += 1; + } + layer.normalize(); + } + Ok(json!({"moved": moved})) +} + +fn move_keys(layer: &mut Layer, from: u32, to: u32, by: i64) -> Result { + if by == 0 { + return Ok(0); + } + let end = layer.end_frame(); + let (mut moving, mut staying): (Vec>, Vec>) = std::mem::take(&mut layer.keyframes).into_iter().partition(|k| k.start >= from && k.start <= to); + if moving.is_empty() { + layer.keyframes = staying; + return Ok(0); + } + let first = moving.first().map_or(0, |k| i64::from(k.start)); + let last_end = moving.last().map_or(0, |k| i64::from(k.end())); + if first + by < 0 || last_end + by > i64::from(MAX_FRAME) + 1 { + layer.keyframes = moving.into_iter().chain(staying).collect(); + layer.normalize(); + return Err(EngineError::State(if first + by < 0 { "keyframes cannot move before frame 1".into() } else { "keyframes would move past the end of the timeline".into() })); + } + for k in moving.iter_mut().map(Arc::make_mut) { + k.start = (i64::from(k.start) + by) as u32; + } + let landed: Vec = moving.iter().map(|k| k.start).collect(); + staying.retain(|k| !landed.contains(&k.start)); + let n = moving.len(); + let new_end = end.max((last_end + by) as u32); + let mut keys: Vec> = staying.into_iter().chain(moving).collect(); + keys.sort_by_key(|k| k.start); + // Each span runs to the next key; the last runs to the layer's end. + let starts: Vec = keys.iter().map(|k| k.start).collect(); + for (i, k) in keys.iter_mut().enumerate() { + let stop = starts.get(i + 1).copied().unwrap_or(new_end); + let want = stop.saturating_sub(k.start).max(1); + if k.duration != want { + Arc::make_mut(k).duration = want; + } + } + layer.keyframes = keys; + layer.normalize(); + Ok(n) +} + +fn clear_keyframe_at(layer: &mut Layer, frame: u32) -> Result<()> { + let i = layer.keyframe_starting_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is not a keyframe", frame + 1)))?; + if i == 0 { + if let Some(k) = layer.keyframe_mut(0) { + k.elements.clear(); + k.tween = None; + } + } else { + let removed = layer.keyframes.remove(i); + if let Some(prev) = layer.keyframe_mut(i - 1) { + prev.duration = removed.end() - prev.start; + } + } + layer.normalize(); + Ok(()) +} + +fn keyframe_mut<'a>(s: &'a mut Session, p: &Value) -> Result<&'a mut Keyframe> { + 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)))?; + layer.keyframe_mut(i).ok_or_else(|| EngineError::State("keyframe vanished".into())) +} + +fn create_tween(s: &mut Session, p: &Value) -> Result { + let easing = opt_easing(p, "easing")?.unwrap_or_default(); + let k = keyframe_mut(s, p)?; + k.tween = Some(Tween { easing }); + Ok(json!({"tween": k.start, "easing": easing.label()})) +} + +fn remove_tween(s: &mut Session, p: &Value) -> Result { + let k = keyframe_mut(s, p)?; + k.tween = None; + Ok(json!({"removed": k.start})) +} + +fn set_easing(s: &mut Session, p: &Value) -> Result { + let easing = opt_easing(p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?; + let k = keyframe_mut(s, p)?; + let t = k.tween.as_mut().ok_or_else(|| EngineError::State("this span has no tween; create one first".into()))?; + t.easing = easing; + Ok(json!({"easing": easing.label()})) +} + +fn set_label(s: &mut Session, p: &Value) -> Result { + let label = str_req(p, "label")?.chars().take(256).collect::(); + let k = keyframe_mut(s, p)?; + k.label = label; + Ok(json!({"label": k.label})) +} + +fn goto(s: &mut Session, p: &Value) -> Result { + let f = opt_u32(p, "frame")?.ok_or_else(|| EngineError::Param("param 'frame' is required".into()))?; + s.set_frame(f); + Ok(json!({"frame": s.frame})) +} + +fn step(s: &mut Session, d: i64) -> Result { + let n = i64::from(s.frame_count().max(1)); + let f = (i64::from(s.frame) + d).rem_euclid(n); + s.set_frame(f as u32); + Ok(json!({"frame": s.frame})) +} + +fn new_layer(s: &mut Session, p: &Value) -> Result { + let n = s.doc.timeline.layers.len() + 1; + let name = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Layer {n}")); + if s.doc.timeline.layers.len() >= 1000 { + return Err(EngineError::State("too many layers (limit 1000)".into())); + } + let id = LayerId(s.doc.alloc_id()); + let mut layer = Layer::new(id, name); + // Match the timeline length so the new layer spans the existing frames. + if let Some(k) = layer.keyframe_mut(0) { + k.duration = s.doc.frame_count().max(1); + } + let palette = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; + layer.color = anicraft_doc::Rgba::hex(palette[n % palette.len()]); + let at = s.active_layer_index().unwrap_or(0); + // Added above a masked layer, it lands inside the mask's group, so it is masked too. + layer.parent = s.doc.timeline.layers.get(at).and_then(|l| l.parent); + s.doc.timeline.layers.insert(at, Arc::new(layer)); + s.layer = id; + s.selection.clear(); + Ok(json!({"layer": id.0})) +} + +fn delete_layer(s: &mut Session, p: &Value) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + if s.doc.timeline.layers.len() <= 1 { + return Err(EngineError::State("a document needs at least one layer".into())); + } + let i = s.doc.timeline.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + s.doc.timeline.layers.remove(i); + // Layers masked by a deleted mask become normal layers. + s.doc.timeline.repair_masks(); + if s.layer == id { + let j = i.min(s.doc.timeline.layers.len() - 1); + s.layer = s.doc.timeline.layers.get(j).map_or(LayerId(0), |l| l.id); + s.selection.clear(); + } + Ok(json!({"deleted": id.0})) +} + +fn rename_layer(s: &mut Session, p: &Value) -> Result { + let name: String = str_req(p, "name")?.chars().take(128).collect(); + if name.trim().is_empty() { + return Err(EngineError::Param("layer name must not be empty".into())); + } + let lid = opt_u64(p, "layer")?.map(LayerId); + let layer = s.layer_mut(lid)?; + layer.name = name; + Ok(json!({"name": layer.name})) +} + +fn toggle(s: &mut Session, p: &Value, f: fn(&mut Layer)) -> Result { + let lid = opt_u64(p, "layer")?.map(LayerId); + let layer = s.layer_mut(lid)?; + f(layer); + Ok(json!({"visible": layer.visible, "locked": layer.locked, "outline": layer.outline})) +} + +fn select_layer(s: &mut Session, p: &Value) -> Result { + let id = if let Some(id) = opt_u64(p, "layer")? { + LayerId(id) + } else if let Some(i) = opt_u64(p, "index")? { + usize::try_from(i).ok().and_then(|i| s.doc.timeline.layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))? + } else { + return Err(EngineError::Param("pass {\"layer\": id} or {\"index\": n}".into())); + }; + if s.doc.timeline.layer(id).is_none() { + return Err(EngineError::State(format!("no layer with id {}", id.0))); + } + if s.layer != id { + s.layer = id; + s.selection.clear(); + } + Ok(json!({"layer": id.0})) +} + +/// Moves a layer one step. A mask layer moves with its masked layers and steps over a whole +/// neighbouring mask group. Any other layer swaps with its neighbour and then belongs to the +/// mask group it landed in, if any: moving a layer in under a mask masks it, moving it out +/// frees it. +fn move_layer(s: &mut Session, p: &Value, d: i64) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + let tl = &mut s.doc.timeline; + let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let n = tl.layers.len(); + if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Mask) { + let block = tl.group_range(i); + // The neighbouring unit: a layer, or a whole mask group. + let unit = if d < 0 { + let Some(a) = i.checked_sub(1) else { return Ok(json!({"index": i})) }; + let top = match tl.layers.get(a).and_then(|l| l.parent) { + Some(m) => tl.layers.iter().position(|l| l.id == m).unwrap_or(a), + None => a, + }; + top..i + } else { + if block.end >= n { + return Ok(json!({"index": i})); + } + tl.group_range(block.end) + }; + let (lo, hi) = (unit.start.min(block.start), unit.end.max(block.end)); + let Some(span) = tl.layers.get_mut(lo..hi) else { return Ok(json!({"index": i})) }; + // Rotate so the block and the unit trade places. + if d < 0 { span.rotate_left(unit.len()) } else { span.rotate_right(unit.len()) } + let at = if d < 0 { unit.start } else { block.start + unit.len() }; + tl.repair_masks(); + return Ok(json!({"index": at})); + } + let j = i as i64 + d; + if j < 0 || j as usize >= n { + return Ok(json!({"index": i})); + } + let j = j as usize; + tl.layers.swap(i, j); + let join = tl.mask_above(j).filter(|_| tl.layers.get(j).is_some_and(|l| l.kind == LayerKind::Normal)); + if let Some(l) = tl.layers.get_mut(j) + && l.parent != join + { + Arc::make_mut(l).parent = join; + } + tl.repair_masks(); + Ok(json!({"index": j})) +} diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs new file mode 100644 index 00000000..0214c1c6 --- /dev/null +++ b/crates/engine/src/confirm.rs @@ -0,0 +1,149 @@ +//! Which commands need the user's confirmation, and why (ADR 0004). +//! +//! The rules live in the engine so every front end (desktop, CLI, agents) is equally safe: +//! irreversible actions are refused unless the params carry `"confirm": true`. + +use crate::Session; +use anicraft_doc::{Keyframe, Layer, LayerId}; +use serde_json::Value; +use std::path::Path; + +/// A confirmation the user must give before a command runs. +#[derive(Clone, Debug, PartialEq)] +pub struct Confirmation { + pub title: String, + pub message: String, + /// Label for the destructive button, e.g. "Delete Layer". + pub action: String, + /// True when undo cannot bring the loss back (unsaved work, files on disk). + pub irreversible: bool, +} + +/// Whether the params carry an explicit confirmation. +pub fn confirmed(p: &Value) -> bool { + p.get("confirm").and_then(Value::as_bool) == Some(true) +} + +fn doc_name(s: &Session) -> String { + s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned()) +} + +fn layer_content(l: &Layer) -> (usize, usize) { + let keys = l.keyframes.iter().filter(|k| !k.elements.is_empty()).count(); + let elements = l.keyframes.iter().map(|k| k.elements.len()).sum(); + (keys, elements) +} + +fn plural(n: usize, word: &str) -> String { + if n == 1 { format!("1 {word}") } else { format!("{n} {word}s") } +} + +fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> { + let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId); + s.doc.timeline.layer(id) +} + +fn target_frame(s: &Session, p: &Value) -> u32 { + p.get("frame").and_then(Value::as_u64).and_then(|f| u32::try_from(f).ok()).unwrap_or(s.frame) +} + +fn target_count(p: &Value) -> u32 { + p.get("count").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(1).max(1) +} + +/// Keyframes with artwork that `hit` selects on the target layers (`layers` or `layer`), as +/// `(layer name, element count)`. +fn lost_keys(s: &Session, p: &Value, hit: impl Fn(&Keyframe) -> bool) -> Vec<(String, usize)> { + let ids: Vec = match p.get("layers").and_then(Value::as_array) { + Some(v) => v.iter().filter_map(Value::as_u64).map(LayerId).take(1000).collect(), + None => vec![p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId)], + }; + ids.iter() + .filter_map(|id| s.doc.timeline.layer(*id)) + .flat_map(|l| l.keyframes.iter().filter(|k| !k.elements.is_empty() && hit(k)).map(|k| (l.name.clone(), k.elements.len()))) + .collect() +} + +fn overwrite(path: &Path, what: &str) -> Confirmation { + Confirmation { + title: "Replace existing file?".into(), + message: format!("{} already exists. {what} will replace it; this cannot be undone.", path.display()), + action: "Replace".into(), + irreversible: true, + } +} + +/// The confirmation `id` with `p` needs right now, if any. +pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { + match id { + "file.new" | "file.new_sample" | "file.open" 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(), + irreversible: true, + }), + "file.save" | "file.save_as" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + let same = s.path.as_deref() == Some(path); + (!same && path.exists()).then(|| overwrite(path, "Saving")) + } + "file.export_png" | "file.export_gif" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + path.exists().then(|| overwrite(path, "Exporting")) + } + "file.export_png_sequence" => { + let dir = Path::new(p.get("dir").and_then(Value::as_str)?); + let has_frames = std::fs::read_dir(dir).ok()?.take(10_000).flatten().any(|e| { + let n = e.file_name(); + let n = n.to_string_lossy(); + n.starts_with("frame_") && n.ends_with(".png") + }); + has_frames.then(|| Confirmation { + title: "Replace exported frames?".into(), + message: format!("{} already contains exported frames. Matching files will be replaced; this cannot be undone.", dir.display()), + action: "Replace".into(), + irreversible: true, + }) + } + "layer.delete" => { + let l = target_layer(s, p)?; + let (keys, elements) = layer_content(l); + (elements > 0).then(|| Confirmation { + title: "Delete layer?".into(), + message: format!("Layer “{}” has {} with {}. You can undo this.", l.name, plural(keys, "keyframe"), plural(elements, "element")), + action: "Delete Layer".into(), + irreversible: false, + }) + } + "timeline.clear_keyframe" => { + let (f, n) = (target_frame(s, p), target_count(p)); + let lost = lost_keys(s, p, |k| k.start >= f && k.start - f < n); + let (keys, elements) = (lost.len(), lost.iter().map(|(_, e)| e).sum::()); + (elements > 0).then(|| Confirmation { + title: if keys == 1 { "Clear keyframe?".into() } else { "Clear keyframes?".into() }, + message: match lost.as_slice() { + [(name, e)] if n == 1 => format!("The keyframe at frame {} on “{name}” holds {}. You can undo this.", f + 1, plural(*e, "element")), + _ => format!("The selected frames hold {} with {}. You can undo this.", plural(keys, "keyframe"), plural(elements, "element")), + }, + action: if keys == 1 { "Clear Keyframe".into() } else { "Clear Keyframes".into() }, + irreversible: false, + }) + } + "timeline.remove_frame" => { + // A keyframe whose whole span is removed takes its artwork with it. + let (f, n) = (target_frame(s, p), target_count(p)); + let lost = lost_keys(s, p, |k| k.start >= f && k.end() <= f.saturating_add(n)); + let (keys, elements) = (lost.len(), lost.iter().map(|(_, e)| e).sum::()); + (elements > 0).then(|| Confirmation { + title: if n == 1 { "Remove frame?".into() } else { "Remove frames?".into() }, + message: match lost.as_slice() { + [(name, e)] if n == 1 => format!("Frame {} is a one-frame keyframe on “{name}” with {}; removing it deletes that artwork. You can undo this.", f + 1, plural(*e, "element")), + _ => format!("Removing these frames deletes {} with {}. You can undo this.", plural(keys, "keyframe"), plural(elements, "element")), + }, + action: if n == 1 { "Remove Frame".into() } else { "Remove Frames".into() }, + irreversible: false, + }) + } + _ => None, + } +} diff --git a/crates/engine/src/format.rs b/crates/engine/src/format.rs new file mode 100644 index 00000000..9b89e2f0 --- /dev/null +++ b/crates/engine/src/format.rs @@ -0,0 +1,168 @@ +//! The `.anicraft` native format: a versioned JSON envelope around the document. + +use crate::EngineError; +use anicraft_doc::{Document, path_table}; +use anicraft_geom::Path; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +pub const FORMAT_NAME: &str = "anicraft"; +/// v1: inline tagged paths. v2: SVG path strings, shared paths stored once in `paths`. +pub const FORMAT_VERSION: u32 = 2; +/// Largest file we will parse. +pub const MAX_FILE_BYTES: u64 = 1024 * 1024 * 1024; +/// Files smaller than this (compact) are pretty-printed for humans and diffs. +const PRETTY_LIMIT: usize = 1024 * 1024; + +/// Written in this field order: the path table precedes the document, so a reader can stream +/// the file in one pass with references already resolvable. +#[derive(Serialize)] +struct EnvelopeOut<'a> { + format: &'a str, + version: u32, + generator: String, + paths: &'a [Arc], + document: &'a Document, +} + +/// Streaming reader: when `paths` arrives it opens a path-table scope for `document`. +struct EnvelopeIn { + format: String, + version: u32, + document: Option, +} + +impl<'de> Deserialize<'de> for EnvelopeIn { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> serde::de::Visitor<'de> for V { + type Value = EnvelopeIn; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("an .anicraft envelope object") + } + fn visit_map>(self, mut map: A) -> Result { + let (mut format, mut version, mut document) = (None, None, None); + let mut _scope = None; + while let Some(key) = map.next_key::()? { + match key.as_str() { + "format" => format = Some(map.next_value::()?), + "version" => version = Some(map.next_value::()?), + "paths" => { + let paths: Vec = map.next_value()?; + _scope = Some(path_table::begin_read(paths.into_iter().map(Arc::new).collect())); + } + "document" => document = Some(map.next_value::()?), + _ => { + map.next_value::()?; + } + } + } + Ok(EnvelopeIn { + format: format.ok_or_else(|| serde::de::Error::missing_field("format"))?, + version: version.ok_or_else(|| serde::de::Error::missing_field("version"))?, + document, + }) + } + } + d.deserialize_map(V) + } +} + +pub fn to_json(doc: &Document) -> Result { + let paths = path_table::build_table(doc); + let env = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator: format!("AniCraft {}", env!("CARGO_PKG_VERSION")), paths: &paths, document: doc }; + let compact = path_table::write_with_paths(&paths, || serde_json::to_string(&env)).map_err(|e| EngineError::Format(e.to_string()))?; + if compact.len() < PRETTY_LIMIT { + return path_table::write_with_paths(&paths, || serde_json::to_string_pretty(&env)).map_err(|e| EngineError::Format(e.to_string())); + } + Ok(compact) +} + +pub fn from_json(text: &str) -> Result { + let env: EnvelopeIn = serde_json::from_str(text).map_err(|e| EngineError::Format(format!("not a valid .anicraft file: {e}")))?; + if env.format != FORMAT_NAME { + return Err(EngineError::Format(format!("unexpected format '{}'", env.format))); + } + if env.version > FORMAT_VERSION { + return Err(EngineError::Format(format!("file version {} is newer than this AniCraft (supports {FORMAT_VERSION})", env.version))); + } + let mut doc = env.document.ok_or_else(|| EngineError::Format("the file has no document".into()))?; + doc.sanitize(); + Ok(doc) +} + +pub fn load(path: &std::path::Path) -> Result { + let meta = std::fs::metadata(path)?; + if meta.len() > MAX_FILE_BYTES { + return Err(EngineError::Format(format!("file is {} bytes; the limit is {MAX_FILE_BYTES}", meta.len()))); + } + from_json(&std::fs::read_to_string(path)?) +} + +pub fn save(doc: &Document, path: &std::path::Path) -> Result<(), EngineError> { + let json = to_json(doc)?; + // Write next to the target, then rename: a crash mid-write never corrupts the old file. + let tmp = path.with_extension("anicraft.tmp"); + std::fs::write(&tmp, json)?; + std::fs::rename(&tmp, path)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_doc::sample; + + #[test] + fn round_trip_is_lossless() { + let d = sample::demo(); + let back = from_json(&to_json(&d).unwrap()).unwrap(); + assert_eq!(d, back); + } + + #[test] + fn shared_paths_are_written_once_and_shared_again_on_load() { + let d = anicraft_doc::sample::stress(2, 40, 48); // 4 keyframes per element share a path + let json = to_json(&d).unwrap(); + let env: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(env["version"], 2); + assert_eq!(env["paths"].as_array().unwrap().len(), 80, "one entry per distinct path"); + let back = from_json(&json).unwrap(); + assert_eq!(d, back); + let l = &back.timeline.layers[0]; + let (anicraft_doc::ElementKind::Shape(a), anicraft_doc::ElementKind::Shape(b)) = (&l.keyframes[0].elements[0].kind, &l.keyframes[3].elements[0].kind) else { panic!() }; + assert!(Arc::ptr_eq(&a.path, &b.path), "sharing restored on load"); + } + + #[test] + fn version_1_files_still_load() { + let v1 = r#"{"format":"anicraft","version":1,"document":{"timeline":{"layers":[{"id":1,"name":"L","keyframes":[{"start":0,"duration":2,"elements":[ + {"id":2,"kind":{"Shape":{"path":{"cmds":[{"MoveTo":{"x":0.0,"y":0.0}},{"LineTo":{"x":10.0,"y":0.0}},{"LineTo":{"x":10.0,"y":10.0}},"Close"]},"fill":{"Solid":{"r":1.0,"g":0.0,"b":0.0,"a":1.0}}}}}]}]}]},"next_id":3}}"#; + let d = from_json(v1).unwrap(); + assert_eq!(d.frame_count(), 2); + assert_eq!(anicraft_doc::evaluate(&d, 1).items.len(), 1); + } + + #[test] + fn bad_path_references_are_errors() { + let bad = r#"{"format":"anicraft","version":2,"paths":["M0 0L1 1Z"],"document":{"timeline":{"layers":[{"id":1,"name":"L","keyframes":[{"start":0,"duration":1,"elements":[ + {"id":2,"kind":{"Shape":{"path":7}}}]}]}]}}}"#; + assert!(from_json(bad).is_err()); + assert!(from_json(r#"{"format":"anicraft","version":2,"paths":["M0 0 Q"],"document":{}}"#).is_err()); + } + + #[test] + fn rejects_garbage_and_future_versions() { + assert!(from_json("{").is_err()); + assert!(from_json(r#"{"format":"other","version":1,"document":{}}"#).is_err()); + assert!(from_json(r#"{"format":"anicraft","version":99,"document":{}}"#).is_err()); + } + + #[test] + fn missing_fields_default() { + let d = from_json(r#"{"format":"anicraft","version":1,"document":{"stage":{"width":0,"height":50,"fps":-3,"background":{"r":2,"g":0,"b":0,"a":1}}}}"#).unwrap(); + assert_eq!(d.stage.width, 1); + assert_eq!(d.stage.fps, 24.0); + assert_eq!(d.stage.background.r, 1.0); + } +} diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs new file mode 100644 index 00000000..20880567 --- /dev/null +++ b/crates/engine/src/history.rs @@ -0,0 +1,232 @@ +//! Undo/redo history over persistent document snapshots. +//! +//! Design (see `docs/adr/0001-undo-persistent-snapshots.md`): every undo step is a snapshot of +//! the structurally-shared [`Document`], so a step costs memory only for the nodes the edit +//! actually copied. History is bounded by an estimate of that unique memory, not by step count, +//! so a thousand small nudges are cheap while one huge import is still evictable. + +use anicraft_doc::{Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Symbol}; +use std::collections::{HashSet, VecDeque}; +use std::mem::size_of; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Globally unique id of a document *state*. Equal ids mean identical content, so render caches +/// can key on it and an undo back to a cached state is a cache hit. +pub type StateId = u64; + +static NEXT_STATE: AtomicU64 = AtomicU64::new(1); + +pub fn fresh_state() -> StateId { + NEXT_STATE.fetch_add(1, Ordering::Relaxed) +} + +/// Everything restored by undo/redo. +#[derive(Clone)] +pub struct Snapshot { + pub label: String, + pub doc: Document, + pub state: StateId, + pub frame: u32, + pub layer: LayerId, + pub selection: Vec, + /// Estimated bytes this snapshot keeps alive that the neighbouring state does not share. + pub bytes: usize, +} + +/// Default memory budget for undo history. +pub const DEFAULT_BUDGET_BYTES: usize = 512 * 1024 * 1024; +/// Hard cap on steps, whatever their size. +pub const MAX_STEPS: usize = 10_000; + +pub struct History { + undo: VecDeque, + redo: Vec, + pub budget_bytes: usize, + pub max_steps: usize, + undo_bytes: usize, + redo_bytes: usize, + /// Steps dropped from the old end because of the budget. + pub evicted: usize, +} + +impl Default for History { + fn default() -> Self { + History { undo: VecDeque::new(), redo: Vec::new(), budget_bytes: DEFAULT_BUDGET_BYTES, max_steps: MAX_STEPS, undo_bytes: 0, redo_bytes: 0, evicted: 0 } + } +} + +impl History { + /// Records `before` as an undo step leading to `current`, and clears redo. + pub fn record(&mut self, mut before: Snapshot, current: &Document) { + before.bytes = unique_bytes(&before.doc, current); + self.undo_bytes += before.bytes; + self.undo.push_back(before); + self.redo.clear(); + self.redo_bytes = 0; + self.enforce_budget(); + } + + fn enforce_budget(&mut self) { + while self.undo.len() > 1 && (self.undo_bytes + self.redo_bytes > self.budget_bytes || self.undo.len() > self.max_steps) { + if let Some(old) = self.undo.pop_front() { + self.undo_bytes = self.undo_bytes.saturating_sub(old.bytes); + self.evicted += 1; + } + } + } + + /// Pops the newest undo step and pushes `current` onto the redo stack. + pub fn undo(&mut self, mut current: Snapshot) -> Option { + let s = self.undo.pop_back()?; + self.undo_bytes = self.undo_bytes.saturating_sub(s.bytes); + current.bytes = unique_bytes(¤t.doc, &s.doc); + current.label = s.label.clone(); + self.redo_bytes += current.bytes; + self.redo.push(current); + Some(s) + } + + /// Pops the newest redo step and pushes `current` back onto the undo stack. + pub fn redo(&mut self, mut current: Snapshot) -> Option { + let s = self.redo.pop()?; + self.redo_bytes = self.redo_bytes.saturating_sub(s.bytes); + current.bytes = unique_bytes(¤t.doc, &s.doc); + current.label = s.label.clone(); + self.undo_bytes += current.bytes; + self.undo.push_back(current); + self.enforce_budget(); + Some(s) + } + + pub fn can_undo(&self) -> bool { + !self.undo.is_empty() + } + pub fn can_redo(&self) -> bool { + !self.redo.is_empty() + } + pub fn undo_len(&self) -> usize { + self.undo.len() + } + pub fn redo_len(&self) -> usize { + self.redo.len() + } + pub fn undo_label(&self) -> Option<&str> { + self.undo.back().map(|s| s.label.as_str()) + } + pub fn redo_label(&self) -> Option<&str> { + self.redo.last().map(|s| s.label.as_str()) + } + /// Labels, oldest first. + pub fn undo_labels(&self) -> impl Iterator { + self.undo.iter().map(|s| s.label.as_str()) + } + /// Labels of redoable steps, next-to-redo first. + pub fn redo_labels(&self) -> impl Iterator { + self.redo.iter().rev().map(|s| s.label.as_str()) + } + /// Estimated memory held by history. + pub fn bytes(&self) -> usize { + self.undo_bytes + self.redo_bytes + } +} + +// ----- unique-memory estimate ------------------------------------------------------------------ + +fn ptr(a: &Arc) -> usize { + Arc::as_ptr(a) as *const u8 as usize +} + +fn path_bytes(e: &Element) -> usize { + match &e.kind { + ElementKind::Shape(s) => size_of::() + s.path.cmds.len() * size_of::(), + ElementKind::Symbol { .. } => 0, + } +} + +fn element_bytes(e: &Element, shared_paths: &HashSet) -> usize { + let mut b = size_of::() + e.name.len(); + if let ElementKind::Shape(s) = &e.kind { + if !shared_paths.contains(&ptr(&s.path)) { + b += path_bytes(e); + } + if let Some(anicraft_doc::Paint::Linear { stops, .. } | anicraft_doc::Paint::Radial { stops, .. }) = &s.fill { + b += stops.len() * size_of::(); + } + } + b +} + +fn keyframe_bytes(k: &Keyframe, other: Option<&Keyframe>) -> usize { + let shared_els: HashSet = other.map(|o| o.elements.iter().map(ptr).collect()).unwrap_or_default(); + let shared_paths: HashSet = other + .map(|o| { + o.elements + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(s) => Some(ptr(&s.path)), + ElementKind::Symbol { .. } => None, + }) + .collect() + }) + .unwrap_or_default(); + let mut b = size_of::() + k.label.len() + k.elements.len() * size_of::(); + for e in &k.elements { + if !shared_els.contains(&ptr(e)) { + b += element_bytes(e, &shared_paths); + } + } + b +} + +fn layer_bytes(l: &Layer, other: Option<&Layer>) -> usize { + let shared: HashSet = other.map(|o| o.keyframes.iter().map(ptr).collect()).unwrap_or_default(); + let mut b = size_of::() + l.name.len() + l.keyframes.len() * size_of::(); + for k in &l.keyframes { + if shared.contains(&ptr(k)) { + continue; + } + let peer = other.and_then(|o| o.keyframes.iter().find(|p| p.start == k.start)).map(|p| &**p); + b += keyframe_bytes(k, peer); + } + b +} + +fn symbol_bytes(s: &Symbol, other: Option<&Symbol>) -> usize { + let shared: HashSet = other.map(|o| o.timeline.layers.iter().map(ptr).collect()).unwrap_or_default(); + let mut b = size_of::() + s.name.len(); + for l in &s.timeline.layers { + if !shared.contains(&ptr(l)) { + let peer = other.and_then(|o| o.timeline.layers.iter().find(|p| p.id == l.id)).map(|p| &**p); + b += layer_bytes(l, peer); + } + } + b +} + +/// Estimated bytes reachable from `old` that are not shared with `new`. Costs O(changed) after +/// an O(layers + symbols) pointer scan. +pub fn unique_bytes(old: &Document, new: &Document) -> usize { + let mut b = size_of::() + (old.timeline.layers.len() + old.library.len()) * size_of::(); + let shared_layers: HashSet = new.timeline.layers.iter().map(ptr).collect(); + for l in &old.timeline.layers { + if !shared_layers.contains(&ptr(l)) { + let peer = new.timeline.layers.iter().find(|p| p.id == l.id).map(|p| &**p); + b += layer_bytes(l, peer); + } + } + let shared_syms: HashSet = new.library.iter().map(ptr).collect(); + for s in &old.library { + if !shared_syms.contains(&ptr(s)) { + let peer = new.library.iter().find(|p| p.id == s.id).map(|p| &**p); + b += symbol_bytes(s, peer); + } + } + b +} + +/// Estimated total bytes of a document (as if nothing were shared). Used for reporting. +pub fn document_bytes(doc: &Document) -> usize { + let empty = Document { stage: doc.stage, timeline: Default::default(), library: Vec::new(), next_id: doc.next_id }; + unique_bytes(doc, &empty) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs new file mode 100644 index 00000000..eb899e17 --- /dev/null +++ b/crates/engine/src/lib.rs @@ -0,0 +1,516 @@ +//! AniCraft engine (layer L3): the session, undo history and the command registry. +//! +//! Every user-visible action is a [`CommandSpec`]. The egui shell, the CLI, the JSON-lines +//! control channel and future MCP server all call [`Session::execute`] with a command id and +//! JSON params, so headless and interactive behaviour cannot drift apart. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod cmds_draw; +mod cmds_file; +mod cmds_frames; +mod cmds_modify; +mod cmds_paint; +mod cmds_path; +mod cmds_timeline; +pub mod confirm; +pub mod format; +pub mod history; +pub mod render_service; +pub mod params; + +use anicraft_doc::{DisplayList, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, evaluate, evaluate_layer_elements}; +use anicraft_geom::{Rect, Vec2}; +use serde_json::{Value, json}; +use history::History; +use std::cell::RefCell; +use std::path::PathBuf; +use std::sync::Arc; + +pub use anicraft_doc as doc; +pub use anicraft_geom as geom; +pub use anicraft_render as render; + +#[derive(Debug, thiserror::Error)] +pub enum EngineError { + #[error("unknown command '{0}'")] + UnknownCommand(String), + #[error("{0}")] + Param(String), + #[error("{0}")] + State(String), + #[error("file format: {0}")] + Format(String), + #[error("I/O: {0}")] + Io(#[from] std::io::Error), + #[error("render: {0}")] + Render(#[from] anicraft_render::RenderError), + #[error("{0}")] + NeedsConfirmation(String), +} + +pub type Result = std::result::Result; + +/// Signature of a command implementation. +pub type RunFn = fn(&mut Session, &Value) -> Result; + +/// Description of one command. +#[derive(Clone, Copy)] +pub struct CommandSpec { + /// Stable id, e.g. `timeline.insert_keyframe`. + pub id: &'static str, + pub label: &'static str, + /// Menu path, e.g. `Insert/Timeline`. Empty = not in a menu. + pub menu: &'static str, + pub shortcut: Option<&'static str>, + /// Human-readable params description. + pub params: &'static str, + /// Whether it changes the document (and therefore records an undo step). + pub mutates: bool, + pub run: RunFn, +} + +impl CommandSpec { + pub fn to_json(&self) -> Value { + json!({ "id": self.id, "label": self.label, "menu": self.menu, "shortcut": self.shortcut, "params": self.params, "mutates": self.mutates }) + } +} + +/// All commands, in menu order. +pub fn commands() -> Vec { + let mut v = Vec::new(); + v.extend(cmds_file::specs()); + v.extend(cmds_timeline::specs()); + v.extend(cmds_frames::specs()); + v.extend(cmds_draw::specs()); + v.extend(cmds_modify::specs()); + v.extend(cmds_path::specs()); + v.extend(cmds_paint::specs()); + v +} + +/// Second keys for commands, `(keys, command id)`: Animate's where the primary key is the +/// platform's, and keys that differ by keyboard (a Mac's Delete key sends Backspace). +pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[ + ("Backspace", "edit.delete"), + ("Shift+,", "timeline.first_frame"), + ("Shift+.", "timeline.last_frame"), +]; + +pub fn find_command(id: &str) -> Option { + commands().into_iter().find(|c| c.id == id) +} + +pub use history::{Snapshot, StateId}; + +/// Last addressable frame (0-based); about 70 minutes at 24 fps. +pub const MAX_FRAME: u32 = 100_000; + +/// Drawing defaults used by the drawing commands when params omit colours. +#[derive(Clone, Copy, Debug)] +pub struct ToolStyle { + pub fill: anicraft_doc::Rgba, + pub stroke: anicraft_doc::Rgba, + pub stroke_width: f32, + pub use_fill: bool, + pub use_stroke: bool, +} + +impl Default for ToolStyle { + fn default() -> Self { + ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true } + } +} + +/// An open document plus everything the editor tracks about it. +pub struct Session { + /// The document: a persistent tree, so cloning it (undo, render thread) is cheap. + pub doc: Document, + /// Playhead (0-based). + pub frame: u32, + /// Active layer. + pub layer: LayerId, + /// Selected elements on the active layer. + pub selection: Vec, + /// Bumped on every document change, undo and redo (UI invalidation). + pub revision: u64, + /// Identity of the current document content (equal ids ⇒ identical content). + pub state: StateId, + saved_state: Option, + pub path: Option, + pub style: ToolStyle, + history: History, + /// Open gesture (e.g. a drag): commands inside it coalesce into one undo step. + gesture: Option, + /// Display list of `(state, frame)`, shared by hit testing, bounds and overlays. + dl_cache: RefCell)>>, + /// Copied elements (and the symbols they use), outside the document so undo leaves it alone. + pub clipboard: cmds_modify::Clipboard, + /// Copied frames (Copy Frames), separate from copied artwork as in Animate. + pub frame_clipboard: cmds_frames::FrameClipboard, +} + +impl Default for Session { + fn default() -> Self { + Session::new(Document::default()) + } +} + +impl Session { + pub fn new(mut doc: Document) -> Session { + doc.sanitize(); + if doc.timeline.layers.is_empty() { + let id = LayerId(doc.alloc_id()); + doc.timeline.layers.push(Arc::new(Layer::new(id, "Layer 1"))); + } + let layer = doc.timeline.layers.first().map_or(LayerId(0), |l| l.id); + let state = history::fresh_state(); + Session { + doc, + frame: 0, + layer, + selection: Vec::new(), + revision: 1, + state, + saved_state: Some(state), + path: None, + style: ToolStyle::default(), + history: History::default(), + gesture: None, + dl_cache: RefCell::new(None), + clipboard: cmds_modify::Clipboard::default(), + frame_clipboard: cmds_frames::FrameClipboard::default(), + } + } + + /// Whether the document differs from the last saved (or opened) state. Undoing back to + /// the saved state makes it clean again. + pub fn is_dirty(&self) -> bool { + self.saved_state != Some(self.state) + } + + /// Marks the current state as saved. + pub fn mark_saved(&mut self) { + self.saved_state = Some(self.state); + } + + /// The confirmation running `id` with `params` needs right now (ADR 0004). + pub fn confirmation(&self, id: &str, params: &Value) -> Option { + confirm::confirmation(self, id, params) + } + + pub fn history(&self) -> &History { + &self.history + } + + /// Sets the undo memory budget (bytes); older steps are evicted beyond it. + pub fn set_history_budget(&mut self, bytes: usize) { + self.history.budget_bytes = bytes; + } + + /// Starts coalescing: every mutating command until [`Session::end_gesture`] becomes a single + /// undo step labelled `label` (used for drags, so a move is one step, not sixty). + pub fn begin_gesture(&mut self, label: &str) { + if self.gesture.is_none() { + self.gesture = Some(self.snapshot(label)); + } + } + + /// Ends the open gesture, recording one undo step if the document changed. + pub fn end_gesture(&mut self) { + if let Some(before) = self.gesture.take() + && self.doc != before.doc + { + self.history.record(before, &self.doc); + } + } + + pub fn in_gesture(&self) -> bool { + self.gesture.is_some() + } + + /// Replaces the document (new/open), clearing history. + pub fn replace_document(&mut self, doc: Document, path: Option) { + let style = self.style; + let rev = self.revision; + let budget = self.history.budget_bytes; + let clipboard = std::mem::take(&mut self.clipboard); + *self = Session::new(doc); + // The clipboard survives New/Open, so artwork can move between documents. + self.clipboard = clipboard; + self.style = style; + self.revision = rev + 1; + self.path = path; + self.history.budget_bytes = budget; + } + + /// Runs a command by id. Mutating commands are atomic: on error the document is restored. + pub fn execute(&mut self, id: &str, params: &Value) -> Result { + let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + // Irreversible loss (unsaved work, files on disk) needs explicit consent, whoever asks. + if let Some(c) = self.confirmation(id, params) + && c.irreversible + && !confirm::confirmed(params) + { + return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message))); + } + if !spec.mutates { + return (spec.run)(self, params); + } + let before = self.snapshot(spec.label); + // A command must never observe a display list of the state it is changing. + self.dl_cache.replace(None); + let result = (spec.run)(self, params); + self.dl_cache.replace(None); + match result { + Ok(v) => { + // O(changed): unchanged subtrees compare by pointer. + if self.doc != before.doc { + self.state = history::fresh_state(); + self.revision += 1; + if self.gesture.is_none() { + self.history.record(before, &self.doc); + } + } + self.fix_selection(); + Ok(v) + } + Err(e) => { + self.restore(before); + Err(e) + } + } + } + + fn snapshot(&self, label: &str) -> Snapshot { + Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } + } + + fn restore(&mut self, s: Snapshot) { + self.doc = s.doc; + self.state = s.state; + self.frame = s.frame; + self.layer = s.layer; + self.selection = s.selection; + self.dl_cache.replace(None); + } + + pub fn can_undo(&self) -> bool { + self.history.can_undo() || self.gesture.as_ref().is_some_and(|g| g.doc != self.doc) + } + pub fn can_redo(&self) -> bool { + self.history.can_redo() + } + pub fn undo_label(&self) -> Option<&str> { + self.history.undo_label() + } + pub fn history_len(&self) -> usize { + self.history.undo_len() + } + + pub fn undo(&mut self) -> Result { + self.end_gesture(); + let cur = self.snapshot(""); + let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?; + let label = s.label.clone(); + self.restore(s); + self.revision += 1; + self.fix_selection(); + Ok(json!({ "undone": label })) + } + + pub fn redo(&mut self) -> Result { + self.end_gesture(); + let cur = self.snapshot(""); + let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?; + let label = s.label.clone(); + self.restore(s); + self.revision += 1; + self.fix_selection(); + Ok(json!({ "redone": label })) + } + + /// Moves through history until `undo_len()` equals `target` (for a History panel click). + pub fn travel_to(&mut self, target: usize) -> Result { + let mut moved = 0usize; + while self.history.undo_len() > target && self.history.can_undo() { + self.undo()?; + moved += 1; + } + while self.history.undo_len() < target && self.history.can_redo() { + self.redo()?; + moved += 1; + } + Ok(json!({ "steps": moved, "position": self.history.undo_len() })) + } + + // ----- queries --------------------------------------------------------------------------- + + pub fn frame_count(&self) -> u32 { + self.doc.frame_count() + } + + pub fn active_layer(&self) -> Option<&Layer> { + self.doc.timeline.layer(self.layer) + } + + pub fn active_layer_index(&self) -> Option { + self.doc.timeline.layers.iter().position(|l| l.id == self.layer) + } + + /// The evaluated frame at the playhead, cached per `(state, frame)`. + pub fn display_list(&self) -> Arc { + if let Some((s, f, dl)) = &*self.dl_cache.borrow() + && *s == self.state + && *f == self.frame + { + return dl.clone(); + } + let dl = Arc::new(evaluate(&self.doc, self.frame)); + self.dl_cache.replace(Some((self.state, self.frame, dl.clone()))); + dl + } + + /// Elements on the active layer at the playhead (tweens applied). Shares the document's + /// element `Arc`s on non-tweened frames. + pub fn visible_elements(&self) -> Vec> { + self.active_layer().and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() + } + + /// Topmost element under `p` (stage space) on a visible, unlocked layer. A bounding-box + /// test rejects almost every item before any curve is flattened. + pub fn hit_test(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> { + let dl = self.display_list(); + for item in dl.items.iter().rev() { + let hw = item.stroke.map_or(0.0, |s| s.width * 0.5 * item.transform.mean_scale()); + let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop); + if !bounds.contains(p) { + continue; + } + let Some(layer) = self.doc.timeline.layer(item.layer) else { continue }; + if layer.locked { + continue; + } + // Masked-away parts cannot be picked. + if item.clip.is_some_and(|c| !dl.clip_contains(c, p)) { + continue; + } + let inside = item.fill.is_some() && item.path.contains(p, &item.transform, item.fill_rule); + if inside || item.path.distance_to_edge(p, &item.transform) <= hw + slop { + return Some((item.layer, item.element)); + } + } + None + } + + /// Stage-space bounds of a top-level element at the playhead. + pub fn element_bounds(&self, id: ElementId) -> Rect { + let mut r = Rect::EMPTY; + for item in self.display_list().items.iter().filter(|i| i.element == id) { + let pad = item.stroke.map_or(0.0, |s| s.width * 0.5); + r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform)); + } + r + } + + /// Bounds of the whole selection. + pub fn selection_bounds(&self) -> Rect { + self.selection.iter().fold(Rect::EMPTY, |r, id| r.union(&self.element_bounds(*id))) + } + + /// Drops selected ids that no longer exist on the active layer at the playhead. + pub fn fix_selection(&mut self) { + if self.doc.timeline.layer(self.layer).is_none() { + self.layer = self.doc.timeline.layers.first().map_or(LayerId(0), |l| l.id); + } + if self.selection.is_empty() { + return; + } + let ids: Vec = self.visible_elements().iter().map(|e| e.id).collect(); + self.selection.retain(|s| ids.contains(s)); + } + + pub fn set_frame(&mut self, frame: u32) { + self.frame = frame.min(MAX_FRAME); + self.fix_selection(); + } + + // ----- mutation helpers used by commands ------------------------------------------------ + + pub(crate) fn layer_mut(&mut self, id: Option) -> Result<&mut Layer> { + let id = id.unwrap_or(self.layer); + self.doc.timeline.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) + } + + /// The keyframe on the active layer that edits at the playhead should change. Creates a + /// keyframe when the playhead is inside a tween (auto-key) or past the layer's end. + pub(crate) fn editable_keyframe(&mut self) -> Result<&mut Keyframe> { + let frame = self.frame; + let layer = self.layer_mut(None)?; + if layer.locked { + return Err(EngineError::State(format!("layer '{}' is locked", layer.name))); + } + let needs_key = match layer.keyframe_at(frame) { + None => true, + Some(k) => k.tween.is_some() && k.start != frame, + }; + if needs_key { + // Inside a tween: capture the tweened state. On an empty frame: start blank. + let copy = layer.keyframe_at(frame).is_some(); + 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())) + } + + /// Selected elements in the editable keyframe (copy-on-write: only these are cloned). + pub(crate) fn selected_elements_mut(&mut self) -> Result> { + let sel = self.selection.clone(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let kf = self.editable_keyframe()?; + Ok(kf.elements_mut_where(|id| sel.contains(&id))) + } + + /// JSON summary used by `doc.info` and the CLI. + pub fn info(&self) -> Value { + let layers: Vec = self + .doc + .timeline + .layers + .iter() + .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::>() + }) + }) + .collect(); + let symbols: Vec = self.doc.library.iter().map(|s| json!({"id": s.id.0, "name": s.name, "kind": format!("{:?}", s.kind), "frames": s.timeline.frame_count()})).collect(); + json!({ + "stage": {"width": self.doc.stage.width, "height": self.doc.stage.height, "fps": self.doc.stage.fps, "background": self.doc.stage.background.to_hex()}, + "frames": self.frame_count(), + "frame": self.frame, + "layer": self.layer.0, + "selection": self.selection.iter().map(|e| e.0).collect::>(), + "layers": layers, + "library": symbols, + "revision": self.revision, + "dirty": self.is_dirty(), + "history": {"undo": self.history.undo_len(), "redo": self.history.redo_len(), "bytes": self.history.bytes(), "evicted": self.history.evicted}, + "state": self.state, + }) + } +} + +/// Short human label for an element (properties panel, library, CLI). +pub fn element_label(doc: &Document, e: &Element) -> String { + let kind = match &e.kind { + ElementKind::Shape(_) => "Shape".to_string(), + ElementKind::Symbol { symbol, .. } => format!("Graphic: {}", doc.symbol(*symbol).map_or("missing", |s| s.name.as_str())), + }; + if e.name.is_empty() { kind } else { format!("{} ({kind})", e.name) } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs new file mode 100644 index 00000000..2399dae5 --- /dev/null +++ b/crates/engine/src/params.rs @@ -0,0 +1,115 @@ +//! Typed, validating access to JSON command params. Every getter returns an error the caller +//! can show, never panics, and rejects non-finite numbers. + +use crate::{EngineError, Result}; +use anicraft_doc::{Easing, Rgba}; +use serde_json::Value; + +fn bad(key: &str, want: &str) -> EngineError { + EngineError::Param(format!("param '{key}' must be {want}")) +} + +pub fn opt_f32(p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let f = v.as_f64().ok_or_else(|| bad(key, "a number"))?; + if !f.is_finite() || f.abs() > 1e7 { + return Err(bad(key, "a finite number within ±10,000,000")); + } + Ok(Some(f as f32)) + } + } +} + +pub fn f32_req(p: &Value, key: &str) -> Result { + opt_f32(p, key)?.ok_or_else(|| bad(key, "given (a number)")) +} + +pub fn opt_u32(p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let n = v.as_u64().ok_or_else(|| bad(key, "a non-negative integer"))?; + u32::try_from(n).map(Some).map_err(|_| bad(key, "an integer below 4,294,967,296")) + } + } +} + +pub fn opt_u64(p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(key, "a non-negative integer")), + } +} + +pub fn opt_str<'a>(p: &'a Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_str().map(Some).ok_or_else(|| bad(key, "a string")), + } +} + +pub fn str_req<'a>(p: &'a Value, key: &str) -> Result<&'a str> { + opt_str(p, key)?.ok_or_else(|| bad(key, "given (a string)")) +} + +pub fn opt_bool(p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(key, "true or false")), + } +} + +pub fn opt_color(p: &Value, key: &str) -> Result> { + match opt_str(p, key)? { + None => Ok(None), + Some(s) => Rgba::parse_hex(s).map(Some).ok_or_else(|| bad(key, "a colour like \"#ff8800\"")), + } +} + +pub fn opt_u64_list(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) => { + if a.len() > 100_000 { + return Err(bad(key, "a list of at most 100,000 ids")); + } + a.iter().map(|v| v.as_u64().ok_or_else(|| bad(key, "a list of integer ids"))).collect::>>().map(Some) + } + Some(_) => Err(bad(key, "a list of integer ids")), + } +} + +/// Easing from a preset name (`"Linear"`, `"QuadIn"`…), `{"classic": n}` or `{"bezier": [x1,y1,x2,y2]}`. +pub fn opt_easing(p: &Value, key: &str) -> Result> { + let Some(v) = p.get(key) else { return Ok(None) }; + if v.is_null() { + return Ok(None); + } + if let Some(s) = v.as_str() { + let e = match s.to_ascii_lowercase().replace(['-', '_', ' '], "").as_str() { + "linear" | "none" => Easing::Linear, + "quadin" | "easein" => Easing::QuadIn, + "quadout" | "easeout" => Easing::QuadOut, + "quadinout" | "easeinout" => Easing::QuadInOut, + "cubicin" => Easing::CubicIn, + "cubicout" => Easing::CubicOut, + "cubicinout" => Easing::CubicInOut, + "smooth" => Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), + _ => return Err(bad(key, "one of Linear, QuadIn, QuadOut, QuadInOut, CubicIn, CubicOut, CubicInOut, Smooth")), + }; + return Ok(Some(e)); + } + if let Some(c) = v.get("classic") { + let s = c.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(key, "{\"classic\": -100..100}"))?; + return Ok(Some(Easing::Classic((s as f32).clamp(-100.0, 100.0)))); + } + if let Some(Value::Array(b)) = v.get("bezier") { + let n: Vec = b.iter().filter_map(Value::as_f64).filter(|f| f.is_finite()).map(|f| f as f32).collect(); + if let [x1, y1, x2, y2] = n[..] { + return Ok(Some(Easing::CubicBezier(x1.clamp(0.0, 1.0), y1.clamp(-5.0, 5.0), x2.clamp(0.0, 1.0), y2.clamp(-5.0, 5.0)))); + } + } + Err(bad(key, "an easing name, {\"classic\": n} or {\"bezier\": [x1, y1, x2, y2]}")) +} diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs new file mode 100644 index 00000000..79945e34 --- /dev/null +++ b/crates/engine/src/render_service.rs @@ -0,0 +1,554 @@ +//! Background rendering of stage tiles and frames, with a memory-bounded cache. +//! +//! The stage is drawn from **tiles** (ADR 0007): fixed-size pieces of the stage at a zoom level, +//! each a [`FrameJob`]. The UI asks for the tiles it needs as one **batch**. The worker takes the +//! whole batch, evaluates the scene **once per (state, frame, onion)** (the job's `scene`), and +//! renders the tiles in parallel. Newer batches replace older pending ones (latest wins), so a +//! drag or a fast pan never builds a backlog. Jobs carry a `Document` clone, which is O(layers) +//! thanks to structural sharing. Keys hash the document *state id*, so undoing back to a state +//! already rendered is a cache hit. + +use crate::history::StateId; +use anicraft_doc::{ColorEffect, DisplayList, Document, Rgba, evaluate}; +use anicraft_render::{RenderStats, View, render}; +use rayon::prelude::*; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::Instant; + +/// One image to render: a whole frame or one stage tile. +#[derive(Clone)] +pub struct FrameJob { + pub key: u64, + /// Identity of the evaluated scene (`scene_key`): tiles of one frame share it. + pub scene: u64, + pub doc: Document, + pub frame: u32, + pub view: View, + pub onion: bool, +} + +/// A finished image: premultiplied RGBA8, ready for a texture upload. +pub struct FrameImage { + pub key: u64, + pub frame: u32, + pub width: u32, + pub height: u32, + pub rgba_premul: Vec, + pub ms: f32, + pub stats: RenderStats, + pub error: Option, +} + +/// Identity of an evaluated scene: the display list depends on these and nothing else. +pub fn scene_key(state: StateId, frame: u32, onion: bool) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (state, frame, onion).hash(&mut h); + h.finish() +} + +/// Cache key for a scene seen through a view (a frame or a tile). +pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + state.hash(&mut h); + frame.hash(&mut h); + for v in view.transform.m { + v.to_bits().hash(&mut h); + } + view.width.hash(&mut h); + view.height.hash(&mut h); + if let Some(bg) = view.background { + [bg.r, bg.g, bg.b, bg.a].map(f32::to_bits).hash(&mut h); + } + onion.hash(&mut h); + h.finish() +} + +/// A job whose `scene` is derived from the same inputs as its key. +pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob { + FrameJob { key: frame_key(state, frame, &view, onion), scene: scene_key(state, frame, onion), doc: doc.clone(), frame, view, onion } +} + +/// The frame's display list, with ±2 onion-skin frames (tinted red before, green after) underneath. +pub fn display_list_with_onion(doc: &Document, frame: u32, onion: bool) -> DisplayList { + let mut dl = DisplayList::default(); + if onion { + let n = i64::from(doc.frame_count()); + for (off, tint, alpha) in [(-2i64, 0xff5a5a, 0.12f32), (2, 0x4cd07d, 0.12), (-1, 0xff5a5a, 0.25), (1, 0x4cd07d, 0.25)] { + let f = i64::from(frame) + off; + if f < 0 || f >= n { + continue; + } + let mut ghost = evaluate(doc, f as u32); + for item in &mut ghost.items { + item.color = item.color.concat(&ColorEffect { alpha, tint: Rgba::hex(tint), tint_amount: 1.0 }); + } + dl.append(ghost); + } + } + dl.append(evaluate(doc, frame)); + dl +} + +/// Renders a job against an already evaluated scene. +pub fn render_job_with(job: &FrameJob, dl: &DisplayList) -> FrameImage { + let t0 = Instant::now(); + // Last-resort guard: a renderer bug must not take the editor down with it. + let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render(dl, &job.view))); + let (rgba, stats, error) = match out { + Ok(Ok((pm, stats))) => (pm.to_premul_rgba8(), stats, None), + Ok(Err(e)) => (Vec::new(), RenderStats::default(), Some(e.to_string())), + Err(_) => (Vec::new(), RenderStats::default(), Some("the renderer failed on this frame".into())), + }; + let (width, height) = if error.is_none() { (job.view.width, job.view.height) } else { (0, 0) }; + FrameImage { key: job.key, frame: job.frame, width, height, rgba_premul: rgba, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error } +} + +/// Renders a job synchronously, evaluating its scene. +pub fn render_job(job: &FrameJob) -> FrameImage { + render_job_with(job, &display_list_with_onion(&job.doc, job.frame, job.onion)) +} + +/// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel. +pub fn render_batch(jobs: &[FrameJob]) -> Vec { + let mut scenes: HashMap> = HashMap::new(); + for j in jobs { + scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_with_onion(&j.doc, j.frame, j.onion))); + } + jobs.par_iter() + .map(|j| match scenes.get(&j.scene) { + Some(dl) => render_job_with(j, dl), + None => render_job(j), + }) + .collect() +} + +/// LRU cache of finished images, bounded by bytes. +pub struct FrameCache { + map: HashMap, u64)>, + tick: u64, + bytes: usize, + pub budget_bytes: usize, + pub hits: u64, + pub misses: u64, +} + +impl FrameCache { + pub fn new(budget_bytes: usize) -> Self { + FrameCache { map: HashMap::new(), tick: 0, bytes: 0, budget_bytes, hits: 0, misses: 0 } + } + pub fn get(&mut self, key: u64) -> Option> { + self.tick += 1; + let tick = self.tick; + match self.map.get_mut(&key) { + Some((img, t)) => { + *t = tick; + self.hits += 1; + Some(img.clone()) + } + None => { + self.misses += 1; + None + } + } + } + pub fn contains(&self, key: u64) -> bool { + self.map.contains_key(&key) + } + pub fn insert(&mut self, img: Arc) { + self.tick += 1; + let size = img.rgba_premul.len() + std::mem::size_of::(); + if let Some((old, _)) = self.map.insert(img.key, (img, self.tick)) { + self.bytes = self.bytes.saturating_sub(old.rgba_premul.len() + std::mem::size_of::()); + } + self.bytes += size; + while self.bytes > self.budget_bytes && self.map.len() > 1 { + let Some((&victim, _)) = self.map.iter().min_by_key(|(_, (_, t))| *t) else { break }; + if let Some((old, _)) = self.map.remove(&victim) { + self.bytes = self.bytes.saturating_sub(old.rgba_premul.len() + std::mem::size_of::()); + } + } + } + pub fn len(&self) -> usize { + self.map.len() + } + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + pub fn bytes(&self) -> usize { + self.bytes + } +} + +#[derive(Default)] +struct Queue { + /// What the screen needs now (replaced by each new batch). + urgent: VecDeque, + /// Look-ahead: margin tiles and upcoming playback frames (replaced wholesale). + prefetch: VecDeque, + busy: HashSet, + shutdown: bool, +} + +struct Shared { + queue: Mutex, + wake: Condvar, + cache: Mutex, + notify: Option>, +} + +/// Default image-cache budget. +pub const DEFAULT_CACHE_BYTES: usize = 768 * 1024 * 1024; +/// Most jobs the worker renders in one parallel pass. +const BATCH: usize = 32; + +/// A render thread plus its cache. +pub struct RenderService { + shared: Arc, + worker: Option>, +} + +impl RenderService { + /// Starts the worker. `notify` runs on the worker after each finished batch (the UI passes + /// "request a repaint"). If no thread can be spawned, requests render synchronously. + pub fn new(cache_bytes: usize, notify: Option>) -> RenderService { + let shared = Arc::new(Shared { queue: Mutex::new(Queue::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), notify }); + let s = shared.clone(); + let worker = std::thread::Builder::new().name("anicraft-render".into()).spawn(move || worker_loop(&s)).ok(); + RenderService { shared, worker } + } + + fn cache(&self) -> std::sync::MutexGuard<'_, FrameCache> { + self.shared.cache.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn queue(&self) -> std::sync::MutexGuard<'_, Queue> { + self.shared.queue.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Images that are ready, in order; the missing ones become the new urgent batch + /// (replacing any older pending batch). + pub fn request_batch(&self, jobs: Vec) -> Vec>> { + let mut out = Vec::with_capacity(jobs.len()); + let mut missing = Vec::new(); + { + let mut cache = self.cache(); + for j in jobs { + match cache.get(j.key) { + Some(img) => out.push(Some(img)), + None => { + out.push(None); + missing.push(j); + } + } + } + } + if missing.is_empty() { + return out; + } + if self.worker.is_none() { + // No thread available: render here, so the caller still gets pictures. + let imgs: Vec> = render_batch(&missing).into_iter().map(Arc::new).collect(); + let mut cache = self.cache(); + for img in &imgs { + cache.insert(img.clone()); + } + let mut it = imgs.into_iter(); + for slot in out.iter_mut().filter(|s| s.is_none()) { + *slot = it.next(); + } + return out; + } + let mut q = self.queue(); + let busy = q.busy.clone(); + q.urgent = missing.into_iter().filter(|j| !busy.contains(&j.key)).collect(); + if !q.urgent.is_empty() { + self.shared.wake.notify_one(); + } + out + } + + /// Single-image form of [`RenderService::request_batch`]. + pub fn request(&self, job: FrameJob) -> Option> { + self.request_batch(vec![job]).into_iter().next().flatten() + } + + /// Renders on the calling thread (one scene evaluation, tiles in parallel) and caches the + /// results: for edits, where showing the change in this frame matters most. + pub fn render_now_batch(&self, jobs: Vec) -> Vec> { + let (mut out, missing): (Vec>>, Vec) = { + let mut cache = self.cache(); + let mut missing = Vec::new(); + let out = jobs + .into_iter() + .map(|j| { + let hit = cache.get(j.key); + if hit.is_none() { + missing.push(j); + } + hit + }) + .collect(); + (out, missing) + }; + let fresh: Vec> = render_batch(&missing).into_iter().map(Arc::new).collect(); + { + let mut cache = self.cache(); + for img in &fresh { + cache.insert(img.clone()); + } + } + let mut it = fresh.into_iter(); + for slot in out.iter_mut().filter(|s| s.is_none()) { + *slot = it.next(); + } + out.into_iter().flatten().collect() + } + + /// Single-image form of [`RenderService::render_now_batch`]. + pub fn render_now(&self, job: FrameJob) -> Arc { + let key = job.key; + let frame = job.frame; + self.render_now_batch(vec![job]).into_iter().next().unwrap_or_else(|| { + Arc::new(FrameImage { key, frame, width: 0, height: 0, rgba_premul: Vec::new(), ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()) }) + }) + } + + /// Replaces the look-ahead queue (images already cached are skipped). + pub fn prefetch(&self, jobs: Vec) { + if self.worker.is_none() { + return; + } + let jobs: VecDeque = { + let cache = self.cache(); + jobs.into_iter().filter(|j| !cache.contains(j.key)).collect() + }; + let mut q = self.queue(); + q.prefetch = jobs; + if !q.prefetch.is_empty() { + self.shared.wake.notify_one(); + } + } + + /// Whether the worker has queued or in-flight work. + pub fn busy(&self) -> bool { + let q = self.queue(); + !q.busy.is_empty() || !q.urgent.is_empty() || !q.prefetch.is_empty() + } + + /// `(images, bytes, hits, misses)`. + pub fn cache_stats(&self) -> (usize, usize, u64, u64) { + let c = self.cache(); + (c.len(), c.bytes(), c.hits, c.misses) + } + + /// Blocks until `key` is rendered (tests, headless tools). Times out after `ms`. + pub fn wait_for(&self, key: u64, ms: u64) -> Option> { + let deadline = Instant::now() + std::time::Duration::from_millis(ms); + while Instant::now() < deadline { + if let Some(img) = self.cache().get(key) { + return Some(img); + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + None + } +} + +impl Drop for RenderService { + fn drop(&mut self) { + { + let mut q = self.queue(); + q.shutdown = true; + q.urgent.clear(); + q.prefetch.clear(); + } + self.shared.wake.notify_all(); + if let Some(w) = self.worker.take() { + let _ = w.join(); + } + } +} + +fn worker_loop(s: &Shared) { + loop { + // Take a whole batch: urgent first, topped up with prefetch work. + let jobs: Vec = { + let mut q = s.queue.lock().unwrap_or_else(PoisonError::into_inner); + loop { + if q.shutdown { + return; + } + if !q.urgent.is_empty() || !q.prefetch.is_empty() { + let mut batch = Vec::new(); + while batch.len() < BATCH { + let Some(j) = q.urgent.pop_front().or_else(|| q.prefetch.pop_front()) else { break }; + batch.push(j); + } + for j in &batch { + q.busy.insert(j.key); + } + break batch; + } + q = s.wake.wait(q).unwrap_or_else(PoisonError::into_inner); + } + }; + let todo: Vec = { + let cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner); + jobs.iter().filter(|j| !cache.contains(j.key)).cloned().collect() + }; + let imgs = render_batch(&todo); + { + let mut cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner); + for img in imgs { + cache.insert(Arc::new(img)); + } + } + { + let mut q = s.queue.lock().unwrap_or_else(PoisonError::into_inner); + for j in &jobs { + q.busy.remove(&j.key); + } + } + if let Some(n) = &s.notify { + n(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_doc::sample; + use anicraft_geom::Affine; + + fn job(doc: &Document, state: u64, frame: u32) -> FrameJob { + let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) }; + make_job(state, doc, frame, view, false) + } + + #[test] + fn worker_matches_synchronous_render() { + let doc = sample::demo(); + let svc = RenderService::new(64 << 20, None); + let j = job(&doc, 1, 9); + let direct = render_job(&j); + assert!(svc.request(j.clone()).is_none(), "first request is queued"); + let img = svc.wait_for(j.key, 10_000).unwrap(); + assert_eq!(img.rgba_premul, direct.rgba_premul); + // second request is a cache hit + assert!(svc.request(j).is_some()); + } + + #[test] + fn render_now_is_synchronous_and_cached() { + let doc = sample::demo(); + let svc = RenderService::new(64 << 20, None); + let j = job(&doc, 3, 4); + let img = svc.render_now(j.clone()); + assert_eq!(img.rgba_premul, render_job(&j).rgba_premul); + assert!(svc.request(j).is_some(), "available to later requests without re-rendering"); + } + + /// Tiles rendered separately and stitched match one full render to within 1/255 per + /// channel (float rounding differs at anti-aliased edges when coordinates are offset), with + /// differences rare: no visible seams. Each tile itself is deterministic. + #[test] + fn stitched_tiles_match_a_full_render() { + let doc = sample::demo(); + let z = 0.37f32; // deliberately odd zoom + let (w, h) = ((1280.0 * z).ceil() as u32, (720.0 * z).ceil() as u32); + let bg = Some(doc.stage.background); + let full = render_job(&make_job(1, &doc, 13, View { transform: Affine::scale(z, z), width: w, height: h, background: bg }, false)); + let t = 128u32; + let mut jobs = Vec::new(); + for ty in 0..h.div_ceil(t) { + for tx in 0..w.div_ceil(t) { + let view = View { + transform: Affine::translate(-((tx * t) as f32), -((ty * t) as f32)).mul(&Affine::scale(z, z)), + width: t.min(w - tx * t), + height: t.min(h - ty * t), + background: bg, + }; + jobs.push((tx, ty, make_job(1, &doc, 13, view, false))); + } + } + let batch: Vec = jobs.iter().map(|(_, _, j)| j.clone()).collect(); + let imgs = render_batch(&batch); + assert!(jobs.windows(2).all(|p| p[0].2.scene == p[1].2.scene), "one scene for all tiles"); + let (mut differing, mut total) = (0usize, 0usize); + for ((tx, ty, _), img) in jobs.iter().zip(&imgs) { + for y in 0..img.height { + for x in 0..img.width { + let (gx, gy) = (tx * t + x, ty * t + y); + let a = ((y * img.width + x) * 4) as usize; + let b = ((gy * w + gx) * 4) as usize; + let (p, q) = (&img.rgba_premul[a..a + 4], &full.rgba_premul[b..b + 4]); + let d = p.iter().zip(q).map(|(u, v)| u.abs_diff(*v)).max().unwrap_or(0); + assert!(d <= 1, "tile ({tx},{ty}) px ({x},{y}): {p:?} vs {q:?}"); + differing += usize::from(d > 0); + total += 1; + } + } + } + assert!(differing * 200 < total, "{differing} of {total} pixels differ (by 1/255)"); + // determinism: the same tile twice gives the same bytes + assert_eq!(render_batch(&batch[..1])[0].rgba_premul, imgs[0].rgba_premul); + } + + #[test] + fn batches_replace_pending_work_and_complete() { + let doc = sample::demo(); + let svc = RenderService::new(64 << 20, None); + let first: Vec = (0..8).map(|f| job(&doc, 7, f)).collect(); + let second: Vec = (20..24).map(|f| job(&doc, 7, f)).collect(); + let keys: Vec = second.iter().map(|j| j.key).collect(); + let _ = svc.request_batch(first); + let r = svc.request_batch(second); + assert!(r.iter().all(Option::is_none)); + for k in keys { + assert!(svc.wait_for(k, 10_000).is_some(), "the latest batch is always rendered"); + } + } + + #[test] + fn prefetch_fills_cache() { + let doc = sample::demo(); + let svc = RenderService::new(64 << 20, None); + let jobs: Vec = (0..6).map(|f| job(&doc, 2, f)).collect(); + let keys: Vec = jobs.iter().map(|j| j.key).collect(); + svc.prefetch(jobs); + for k in keys { + assert!(svc.wait_for(k, 10_000).is_some()); + } + } + + #[test] + fn cache_respects_budget_lru() { + let mut c = FrameCache::new(3 * 1000); + for k in 0..10u64 { + c.insert(Arc::new(FrameImage { key: k, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], ms: 0.0, stats: RenderStats::default(), error: None })); + } + assert!(c.bytes() <= 3000); + assert!(c.contains(9) && !c.contains(0)); + } + + #[test] + fn keys_distinguish_state_frame_and_view() { + let doc = sample::demo(); + let a = job(&doc, 1, 0).key; + assert_ne!(a, job(&doc, 2, 0).key); + assert_ne!(a, job(&doc, 1, 1).key); + assert_eq!(a, job(&doc, 1, 0).key); + } + + #[test] + fn onion_adds_neighbour_frames() { + let doc = sample::demo(); + let plain = display_list_with_onion(&doc, 10, false).items.len(); + let onion = display_list_with_onion(&doc, 10, true).items.len(); + assert_eq!(onion, plain * 5); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs new file mode 100644 index 00000000..7cd9d96b --- /dev/null +++ b/crates/engine/src/tests.rs @@ -0,0 +1,1054 @@ +use super::*; +use anicraft_doc::sample; +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}"), + } +} + +#[test] +fn command_ids_are_unique_and_well_formed() { + let cmds = commands(); + let mut ids: Vec<&str> = cmds.iter().map(|c| c.id).collect(); + ids.sort_unstable(); + let n = ids.len(); + ids.dedup(); + assert_eq!(ids.len(), n, "duplicate command ids"); + for c in &cmds { + assert!(c.id.contains('.'), "{}", c.id); + assert!(!c.label.is_empty()); + } +} + +#[test] +fn draw_undo_redo() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 100, "h": 50})); + assert_eq!(s.visible_elements().len(), 1); + assert_eq!(s.selection.len(), 1); + let rev = s.revision; + run(&mut s, "edit.undo", json!({})); + assert!(s.visible_elements().is_empty()); + assert!(s.revision > rev); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.visible_elements().len(), 1); +} + +#[test] +fn gestures_coalesce_into_one_undo_step() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let steps = s.history_len(); + s.begin_gesture("Move"); + for _ in 0..30 { + run(&mut s, "element.translate", json!({"dx": 1, "dy": 0})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.visible_elements()[0].transform.translation().x, 5.0); +} + +#[test] +fn undo_step_in_a_large_document_costs_only_what_changed() { + // 20 layers × 500 shapes × 120 frames: 200k element instances. + let mut s = Session::new(sample::stress(20, 500, 120)); + let total = history::document_bytes(&s.doc); + run(&mut s, "layer.select", json!({"index": 3})); + s.set_frame(30); + let id = s.visible_elements()[0].id.0; + run(&mut s, "element.select", json!({"ids": [id]})); + run(&mut s, "element.translate", json!({"dx": 5, "dy": 0})); + let step = s.history().bytes(); + assert!(step * 100 < total, "one edit kept {step} bytes of a {total}-byte document"); + // Untouched layers are shared with the undo snapshot, pointer-for-pointer. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + let before = s.doc.clone(); + run(&mut s, "element.translate", json!({"dx": 1, "dy": 0})); + let shared = before.timeline.layers.iter().zip(&s.doc.timeline.layers).filter(|(a, b)| std::sync::Arc::ptr_eq(a, b)).count(); + assert_eq!(shared, 19); +} + +#[test] +fn dirty_tracks_the_save_point_through_undo() { + let mut s = Session::default(); + assert!(!s.is_dirty()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + assert!(s.is_dirty()); + run(&mut s, "edit.undo", json!({})); + assert!(!s.is_dirty(), "undoing back to the saved state is clean"); + run(&mut s, "edit.redo", json!({})); + assert!(s.is_dirty()); + s.mark_saved(); + run(&mut s, "edit.undo", json!({})); + assert!(s.is_dirty()); +} + +#[test] +fn state_ids_identify_content() { + let mut s = Session::default(); + let a = s.state; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let b = s.state; + assert_ne!(a, b); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.state, a, "undo returns to the earlier state id (render cache hit)"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.state, b); + // a no-op command keeps the state + let _ = s.execute("timeline.goto", &json!({"frame": 0})); + assert_eq!(s.state, b); +} + +#[test] +fn history_is_bounded_by_memory() { + let mut s = Session::default(); + s.set_history_budget(64 * 1024); + for i in 0..400 { + run(&mut s, "draw.rect", json!({"x": i, "y": 0, "w": 10, "h": 10})); + } + assert!(s.history().bytes() <= 64 * 1024 + 8 * 1024, "{}", s.history().bytes()); + assert!(s.history().evicted > 0); + assert!(s.can_undo()); +} + +#[test] +fn travel_to_moves_through_history() { + let mut s = Session::default(); + for i in 0..5 { + run(&mut s, "draw.rect", json!({"x": i * 20, "y": 0, "w": 10, "h": 10})); + } + s.travel_to(2).unwrap(); + assert_eq!(s.visible_elements().len(), 2); + assert_eq!(s.history().redo_len(), 3); + s.travel_to(5).unwrap(); + assert_eq!(s.visible_elements().len(), 5); +} + +#[test] +fn display_list_cache_follows_state_and_frame() { + let mut s = Session::new(sample::demo()); + let a = s.display_list(); + assert!(std::sync::Arc::ptr_eq(&a, &s.display_list()), "same state+frame is cached"); + s.set_frame(5); + let b = s.display_list(); + assert!(!std::sync::Arc::ptr_eq(&a, &b)); + run(&mut s, "layer.toggle_visible", json!({})); + assert_ne!(s.display_list().items.len(), b.items.len()); +} + +#[test] +fn parallel_sequence_export_matches_single_frames() { + let dir = std::env::temp_dir().join(format!("anicraft-seq-{}", std::process::id())); + let mut s = Session::new(sample::demo()); + run(&mut s, "file.export_png_sequence", json!({"dir": dir.display().to_string(), "from": 0, "to": 5, "scale": 0.2})); + for f in 0..=5u32 { + let on_disk = std::fs::read(dir.join(format!("frame_{:05}.png", f + 1))).unwrap(); + assert_eq!(on_disk, cmds_file::render_png(&s.doc, f, 0.2).unwrap()); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn discarding_unsaved_work_needs_confirmation() { + let mut s = Session::default(); + // clean document: no confirmation + assert!(s.confirmation("file.new", &json!({})).is_none()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let c = s.confirmation("file.new", &json!({})).unwrap(); + assert!(c.irreversible); + // refused without consent, document untouched + let err = s.execute("file.new", &json!({})).unwrap_err(); + assert!(matches!(err, EngineError::NeedsConfirmation(_))); + assert_eq!(s.visible_elements().len(), 1); + assert!(s.execute("file.new_sample", &json!({})).is_err()); + // explicit consent proceeds + run(&mut s, "file.new", json!({"confirm": true})); + assert!(s.visible_elements().is_empty()); +} + +#[test] +fn overwriting_files_needs_confirmation() { + let dir = std::env::temp_dir().join(format!("anicraft-confirm-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("f.png"); + let mut s = Session::new(sample::demo()); + let p = json!({"path": png.display().to_string(), "scale": 0.1}); + assert!(s.confirmation("file.export_png", &p).is_none()); + run(&mut s, "file.export_png", p.clone()); + assert!(s.confirmation("file.export_png", &p).unwrap().irreversible); + assert!(s.execute("file.export_png", &p).is_err()); + run(&mut s, "file.export_png", json!({"path": png.display().to_string(), "scale": 0.1, "confirm": true})); + // saving over the document's own file is a normal save + let doc = dir.join("d.anicraft"); + run(&mut s, "file.save_as", json!({"path": doc.display().to_string()})); + assert!(s.confirmation("file.save", &json!({"path": doc.display().to_string()})).is_none()); + let mut t = Session::default(); + assert!(t.execute("file.save_as", &json!({"path": doc.display().to_string()})).is_err(), "another document must not silently replace it"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn undoable_bulk_deletions_ask_but_are_not_blocked() { + let mut s = Session::new(sample::demo()); + let c = s.confirmation("layer.delete", &json!({})).unwrap(); + assert!(!c.irreversible); + assert!(c.message.contains("Ball")); + // headless callers may proceed without consent; undo restores + run(&mut s, "layer.delete", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.timeline.layers.len(), 5); + // empty layer: no question + run(&mut s, "layer.new", json!({})); + assert!(s.confirmation("layer.delete", &json!({})).is_none()); + // clearing a keyframe with artwork asks; routine element delete does not + run(&mut s, "layer.select", json!({"index": 1})); + assert!(s.confirmation("timeline.clear_keyframe", &json!({"frame": 0})).is_some()); + assert!(s.confirmation("edit.delete", &json!({})).is_none()); +} + +#[test] +fn copy_paste_cut_and_paste_in_place() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20})); + let orig = s.selection[0]; + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.paste", json!({})); + let els = s.visible_elements(); + assert_eq!(els.len(), 2); + assert_ne!(s.selection[0], orig, "pasted elements get fresh ids"); + let pasted = els.iter().find(|e| e.id == s.selection[0]).unwrap(); + assert_eq!(pasted.transform.translation(), Vec2::new(30.0, 30.0)); + run(&mut s, "edit.paste_in_place", json!({})); + let last = s.visible_elements().into_iter().find(|e| e.id == s.selection[0]).unwrap(); + assert_eq!(last.transform.translation(), Vec2::new(20.0, 20.0)); + // paste centred on a point + run(&mut s, "edit.paste", json!({"x": 500, "y": 400})); + assert_eq!(s.selection_bounds().center(), Vec2::new(500.0, 400.0)); + // cut removes, undo restores + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.visible_elements().len(), 3); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.visible_elements().len(), 4); + assert!(Session::default().execute("edit.paste", &json!({})).is_err(), "empty clipboard"); +} + +#[test] +fn clipboard_carries_symbols_into_another_document() { + let mut s = Session::new(sample::demo()); + run(&mut s, "layer.select", json!({"index": 0})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"confirm": true})); + assert!(s.doc.library.is_empty()); + run(&mut s, "edit.paste_in_place", json!({})); + assert_eq!(s.doc.library.len(), 1, "the Ball symbol came along"); + assert!(!anicraft_doc::evaluate(&s.doc, 0).items.is_empty(), "and it renders"); + let ids: Vec = s.doc.library.iter().map(|x| x.id.0).collect(); + assert!(s.doc.next_id > *ids.iter().max().unwrap()); +} + +#[test] +fn rotate_flip_and_free_transform() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 20})); + let b0 = s.selection_bounds(); + run(&mut s, "modify.rotate_cw", json!({})); + let b1 = s.selection_bounds(); + assert!((b1.width() - b0.height()).abs() < 0.5 && (b1.height() - b0.width()).abs() < 0.5, "{b1:?}"); + assert!(b1.center().distance(b0.center()) < 0.01, "rotates about the centre"); + run(&mut s, "modify.rotate_ccw", json!({})); + run(&mut s, "modify.flip_h", json!({})); + run(&mut s, "modify.flip_h", json!({})); + let t = s.visible_elements()[0].transform; + assert!((t.m[0] - 1.0).abs() < 1e-4 && t.m[1].abs() < 1e-4, "{t:?}"); + run(&mut s, "modify.transform", json!({"a": 2, "b": 0, "c": 0, "d": 1, "e": 5, "f": 0})); + assert!((s.selection_bounds().width() - 2.0 * b0.width()).abs() < 1.0); + assert!(s.execute("modify.transform", &json!({"a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0})).is_err(), "degenerate"); + assert!(s.execute("modify.transform", &json!({"a": 1e6, "b": 0, "c": 0, "d": 1e6, "e": 0, "f": 0})).is_err(), "absurd scale"); +} + +#[test] +fn align_and_distribute() { + let mut s = Session::default(); + for (x, y) in [(10, 50), (200, 10), (90, 120)] { + run(&mut s, "draw.rect", json!({"x": x, "y": y, "w": 20, "h": 20, "stroke": null})); + } + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "align.left", json!({})); + let lefts: Vec = s.selection.iter().map(|id| s.element_bounds(*id).min.x).collect(); + assert!(lefts.iter().all(|x| (x - 10.0).abs() < 1e-3), "{lefts:?}"); + run(&mut s, "align.distribute_v", json!({})); + let mut ys: Vec = s.selection.iter().map(|id| s.element_bounds(*id).center().y).collect(); + ys.sort_by(f32::total_cmp); + assert!(((ys[1] - ys[0]) - (ys[2] - ys[1])).abs() < 1e-3, "{ys:?}"); + // a single element aligns to the stage + run(&mut s, "edit.deselect", json!({})); + let id = s.visible_elements()[0].id.0; + run(&mut s, "element.select", json!({"ids": [id]})); + run(&mut s, "align.right", json!({})); + assert!((s.selection_bounds().max.x - s.doc.stage.width as f32).abs() < 1e-3); +} + +#[test] +fn animated_gif_export() { + let dir = std::env::temp_dir().join(format!("anicraft-gif-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ball.gif"); + let mut s = Session::new(sample::demo()); + let v = run(&mut s, "file.export_gif", json!({"path": path.display().to_string(), "scale": 0.125})); + assert_eq!(v["frames"], 48); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(&bytes[..6], b"GIF89a"); + // decode: 48 frames, 160×90, total delay ≈ 2 s at 24 fps + let mut opts = gif::DecodeOptions::new(); + opts.set_color_output(gif::ColorOutput::Indexed); + let mut dec = opts.read_info(std::fs::File::open(&path).unwrap()).unwrap(); + assert_eq!((dec.width(), dec.height()), (160, 90)); + let (mut n, mut total) = (0, 0u32); + while let Some(f) = dec.read_next_frame().unwrap() { + n += 1; + total += u32::from(f.delay); + } + assert_eq!(n, 48); + assert_eq!(total, 200, "delays sum to exactly 2 s"); + // overwriting asks; absurd sizes are refused + assert!(s.execute("file.export_gif", &json!({"path": path.display().to_string()})).is_err()); + assert!(s.execute("file.export_gif", &json!({"path": dir.join("big.gif").display().to_string(), "scale": 8})).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn gif_delays_are_exact_on_average() { + let d = cmds_file::gif_delays(30, 30.0); + assert_eq!(d.iter().map(|&x| u32::from(x)).sum::(), 100); + assert!(d.iter().all(|&x| x == 3 || x == 4)); + assert!(cmds_file::gif_delays(5, f32::NAN).iter().all(|&x| x >= 2)); +} + +#[test] +fn failed_command_is_atomic() { + let mut s = Session::default(); + let before = s.doc.clone(); + assert!(s.execute("draw.rect", &json!({"x": 0, "y": 0, "w": 10})).is_err()); + assert_eq!(s.doc, before); + assert!(!s.can_undo()); +} + +#[test] +fn keyframes_and_tween_from_commands() { + let mut s = Session::default(); + run(&mut s, "draw.ellipse", json!({"x": 0, "y": 0, "w": 20, "h": 20})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 0})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + assert_eq!(s.frame_count(), 11); + s.set_frame(5); + let el = &s.visible_elements()[0]; + assert!((el.transform.translation().x - 60.0).abs() < 1e-3, "{:?}", el.transform); + // F6 inside the tween keeps the motion unchanged. + run(&mut s, "timeline.insert_keyframe", json!({})); + let el2 = &s.visible_elements()[0]; + assert!((el2.transform.translation().x - 60.0).abs() < 1e-3); + s.set_frame(7); + assert!((s.visible_elements()[0].transform.translation().x - 80.0).abs() < 1e-3); +} + +#[test] +fn editing_inside_tween_auto_keys() { + let mut s = Session::new(sample::demo()); + let ball = s.doc.timeline.layers[0].id; + run(&mut s, "layer.select", json!({"layer": ball.0})); + s.set_frame(6); + run(&mut s, "edit.select_all", json!({})); + let keys_before = s.active_layer().map_or(0, |l| l.keyframes.len()); + run(&mut s, "element.translate", json!({"dx": 0, "dy": -50})); + assert_eq!(s.active_layer().map_or(0, |l| l.keyframes.len()), keys_before + 1); +} + +#[test] +fn insert_and_remove_frames() { + let mut s = Session::default(); + run(&mut s, "timeline.insert_frame", json!({"frame": 9})); + assert_eq!(s.frame_count(), 10); + run(&mut s, "timeline.insert_frame", json!({"frame": 3})); + assert_eq!(s.frame_count(), 11); + run(&mut s, "timeline.remove_frame", json!({"frame": 0})); + assert_eq!(s.frame_count(), 10); + assert!(s.execute("timeline.remove_frame", &json!({"frame": 50})).is_err()); +} + +#[test] +fn layers() { + let mut s = Session::default(); + run(&mut s, "layer.new", json!({"name": "Top"})); + assert_eq!(s.doc.timeline.layers[0].name, "Top"); + run(&mut s, "layer.toggle_lock", json!({})); + assert!(s.execute("draw.rect", &json!({"x": 0, "y": 0, "w": 10, "h": 10})).is_err()); + run(&mut s, "layer.delete", json!({})); + assert!(s.execute("layer.delete", &json!({})).is_err(), "last layer must stay"); +} + +#[test] +fn convert_to_symbol_and_break_apart_preserve_pixels() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 60, "h": 40, "fill": "#ff0000"})); + run(&mut s, "draw.ellipse", json!({"x": 50, "y": 30, "w": 60, "h": 60, "fill": "#00ff00"})); + let before = commands_png(&s); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Thing"})); + assert_eq!(s.doc.library.len(), 1); + assert_eq!(s.visible_elements().len(), 1); + assert_eq!(commands_png(&s), before, "converting must not move anything"); + run(&mut s, "modify.break_apart", json!({})); + assert_eq!(s.visible_elements().len(), 2); + assert_eq!(commands_png(&s), before); +} + +fn commands_png(s: &Session) -> Vec { + match anicraft_render::render_frame(&s.doc, s.frame, 0.25) { + Ok(p) => p.to_rgba8(), + Err(e) => panic!("{e}"), + } +} + +#[test] +fn pick_selects_topmost() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100})); + let a = s.selection[0]; + run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100})); + let b = s.selection[0]; + run(&mut s, "element.pick", json!({"x": 75, "y": 75})); + assert_eq!(s.selection, vec![b]); + run(&mut s, "element.pick", json!({"x": 10, "y": 10})); + assert_eq!(s.selection, vec![a]); + run(&mut s, "element.pick", json!({"x": 500, "y": 500})); + assert!(s.selection.is_empty()); +} + +#[test] +fn save_load_round_trip() { + let dir = std::env::temp_dir().join(format!("anicraft-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("demo.anicraft"); + let mut s = Session::new(sample::demo()); + run(&mut s, "file.save", json!({"path": path.display().to_string()})); + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": path.display().to_string()})); + assert_eq!(s.doc, t.doc); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Adversarial params for every command: must return Ok or Err, never panic. +#[test] +fn panic_hunt_every_command() { + let hostile: Vec = vec![ + Value::Null, + json!({}), + json!([]), + json!("x"), + json!({"x": null, "y": "a", "w": -1e30, "h": f64::MAX}), + json!({"x": 1e300, "y": -1e300, "w": 0, "h": 0}), + json!({"x": 0, "y": 0, "w": 1e7, "h": 1e7, "fill": "#zzzzzz"}), + json!({"x": 1, "y": 1, "w": 10, "h": 10, "radius": -5, "stroke_width": 1e9}), + json!({"frame": u64::MAX, "layer": u64::MAX}), + json!({"frame": 99_999, "layer": 0}), + json!({"frame": -1, "index": 1e9}), + json!({"ids": [1, 2, 3, u64::MAX], "add": "yes"}), + json!({"ids": "nope"}), + json!({"dx": f64::MIN_POSITIVE, "dy": 1e-30, "alpha": 2.0}), + json!({"sx": 0, "sy": 1e9, "rotation": 1e9}), + json!({"easing": {"bezier": [1, 2]}, "label": ""}), + json!({"easing": {"classic": "a"}}), + json!({"easing": 7}), + json!({"cx": 0, "cy": 0, "outer": 1e9, "points": 2}), + json!({"cx": 0, "cy": 0, "outer": 10, "inner": -10, "points": 64}), + json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0}), + json!({"name": "", "symbol": 0}), + json!({"color": null, "width": -1}), + json!({"width": 0, "height": 999_999, "fps": 0}), + json!({"background": "#12345"}), + json!({"layers": [1, 2, 3], "from": 0, "to": 100, "by": -5, "layer_by": -9999999}), + json!({"from": 0, "to": 50, "by": 2, "layer_by": 1}), + json!({"x": 0, "y": 0, "gap": 1e9, "color": "#zz", "width": 0}), + json!({"x": 50, "y": 50, "gap": 999, "width": 999}), + json!({"layers": [0, 1, 2, u64::MAX], "frame": 3, "count": 10_000, "from": 0, "to": 100_000, "by": -100_000}), + json!({"layers": [], "from": 99_999, "by": 1e30, "count": 0}), + json!({"d": "M0 0 L1e30 1e30 Z", "points": [[0, 0], [1e30, 1]], "mode": "ink"}), + json!({"d": "M 0 0 C", "points": [[0, 0]], "mode": "straighten", "tolerance": 0}), + json!({"id": 3, "points": [[0, 0], [99, 9], [1, 2]], "dx": 1e30, "dy": 0, "cmds": [0, 1, 2, 3, 4, 5, 99], "cmd": 0, "smooth": true}), + json!({"id": 5, "points": [[1, 1]], "dx": 3, "dy": 4, "x": 0, "y": 0, "slop": 1e9, "cmds": [1, 1, 0], "cmd": 1, "smooth": false}), + ]; + // File commands are exercised separately (they touch the disk). + let skip = |id: &str| id.starts_with("file."); + for start in [Session::default(), Session::new(sample::demo())] { + let mut s = start; + for spec in commands().iter().filter(|c| !skip(c.id)) { + for p in &hostile { + let _ = s.execute(spec.id, p); + } + // and with a selection present + let _ = s.execute("edit.select_all", &json!({})); + for p in &hostile { + let _ = s.execute(spec.id, p); + } + } + // The document must still evaluate and render. + for f in [0, 1, 5, 47, 1000] { + let _ = anicraft_render::render_frame(&s.doc, f, 0.1); + } + } +} + +#[test] +fn file_commands_reject_bad_params() { + let mut s = Session::default(); + for id in ["file.open", "file.save", "file.export_png", "file.export_png_sequence"] { + assert!(s.execute(id, &json!({"path": 5, "dir": []})).is_err(), "{id}"); + } + assert!(s.execute("file.open", &json!({"path": "/definitely/not/here.anicraft"})).is_err()); + assert!(s.execute("file.new", &json!({"width": 0})).is_err()); + assert!(s.execute("no.such.command", &json!({})).is_err()); +} + + +// ----- paths: pen, pencil, point editing --------------------------------------------------- + +fn shape_path(s: &Session, id: u64) -> anicraft_geom::Path { + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).expect("element"); + match &el.kind { + ElementKind::Shape(sh) => (*sh.path).clone(), + _ => panic!("not a shape"), + } +} + +fn stage_anchor(s: &Session, id: u64, cmd: usize) -> Vec2 { + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).expect("element"); + el.transform.apply(shape_path(s, id).point(cmd, 0).expect("anchor")) +} + +#[test] +fn pen_paths_are_centred_and_closed_explicitly() { + let mut s = Session::default(); + let id = run(&mut s, "draw.path", json!({"d": "M 100 100 L 200 100 C 220 150 180 200 150 200 Z"}))["element"].as_u64().unwrap(); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap(); + let b = s.element_bounds(el.id); + assert!((b.min.x - 99.0).abs() < 1.5 && (b.max.y - 201.0).abs() < 1.5, "{b:?}"); + let p = shape_path(&s, id); + assert!(p.bounds().center().length() < 1e-3, "local origin is the centre"); + assert_eq!(p.editable_anchors().len(), 3, "the closing edge is a segment, the start is one anchor"); + // Open paths have no fill. + let open = run(&mut s, "draw.path", json!({"d": "M 0 0 L 50 50 L 100 0"}))["element"].as_u64().unwrap(); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == open).unwrap(); + assert!(matches!(&el.kind, ElementKind::Shape(sh) if sh.fill.is_none() && sh.stroke.is_some())); + for bad in ["", "M 0 0", "M 0 0 L 0.1 0.1", "nonsense"] { + assert!(s.execute("draw.path", &json!({"d": bad})).is_err(), "{bad}"); + } +} + +#[test] +fn moving_an_anchor_brings_its_handles_and_is_one_undo_step_in_a_gesture() { + let mut s = Session::default(); + let id = run(&mut s, "draw.path", json!({"d": "M 0 0 C 10 -20 30 -20 40 0 C 50 20 70 20 80 0"}))["element"].as_u64().unwrap(); + let before = shape_path(&s, id); + let a0 = stage_anchor(&s, id, 1); + let steps = s.history_len(); + s.begin_gesture("Move Points"); + for _ in 0..5 { + run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 0]], "dx": 2, "dy": 1})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + let a1 = stage_anchor(&s, id, 1); + assert!((a1 - a0 - Vec2::new(10.0, 5.0)).length() < 1e-3); + let after = shape_path(&s, id); + for (cmd, slot) in [(1usize, 2u8), (2, 1)] { + let d = after.point(cmd, slot).unwrap() - before.point(cmd, slot).unwrap(); + assert!((d - Vec2::new(10.0, 5.0)).length() < 1e-3, "handle ({cmd},{slot}) moved with the anchor"); + } + assert_eq!(after.point(1, 1), before.point(1, 1), "the far handle stays"); + // A handle alone moves alone. + run(&mut s, "path.move_points", json!({"id": id, "points": [[2, 2]], "dx": 0, "dy": 7})); + assert_eq!(shape_path(&s, id).point(2, 0), after.point(2, 0)); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(shape_path(&s, id), before); + assert!(s.execute("path.move_points", &json!({"id": id, "points": [[0, 2]], "dx": 1, "dy": 1})).is_err(), "MoveTo has no handles"); +} + +#[test] +fn moves_follow_the_element_transform() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100})); + let id = s.selection[0].0; + run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 90})); + let a0 = stage_anchor(&s, id, 0); + run(&mut s, "path.move_points", json!({"id": id, "points": [[0, 0]], "dx": 10, "dy": 0})); + assert!((stage_anchor(&s, id, 0) - a0 - Vec2::new(10.0, 0.0)).length() < 1e-3, "the point follows the pointer in stage space"); +} + +#[test] +fn add_delete_and_convert_points() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100})); + let id = s.selection[0].0; + let area = |s: &Session| shape_path(s, id).flatten(&anicraft_geom::Affine::IDENTITY, 0.1)[0].points.len(); + let n0 = shape_path(&s, id).editable_anchors().len(); + // The closing edge (left side, x = 0) can take a point too. + let r = run(&mut s, "path.add_point", json!({"id": id, "x": 0.5, "y": 50})); + assert!(r["cmd"].is_u64()); + assert_eq!(shape_path(&s, id).editable_anchors().len(), n0 + 1); + assert!(s.execute("path.add_point", &json!({"id": id, "x": 50, "y": 50})).is_err(), "nowhere near an edge"); + let cmd = r["cmd"].as_u64().unwrap(); + run(&mut s, "path.convert_point", json!({"id": id, "cmd": cmd, "smooth": true})); + run(&mut s, "path.move_points", json!({"id": id, "points": [[cmd, 0]], "dx": -30, "dy": 0})); + assert!(area(&s) > 8, "the edge is now a curve"); + run(&mut s, "path.convert_point", json!({"id": id, "cmd": cmd, "smooth": false})); + run(&mut s, "path.delete_points", json!({"id": id, "cmds": [cmd]})); + assert_eq!(shape_path(&s, id).editable_anchors().len(), n0); + // Deleting all but two works; the last two stay. + let all: Vec = shape_path(&s, id).editable_anchors().iter().map(|(i, _)| *i as u64).collect(); + let r = run(&mut s, "path.delete_points", json!({"id": id, "cmds": all})); + assert_eq!(r["deleted"].as_u64(), Some(n0 as u64 - 2)); + assert!(s.execute("path.delete_points", &json!({"id": id, "cmds": [0]})).is_err()); + // Symbols are not point-editable. + run(&mut s, "modify.convert_to_symbol", json!({})); + let inst = s.selection[0].0; + assert!(s.execute("path.add_point", &json!({"id": inst, "x": 0, "y": 0})).is_err()); +} + +#[test] +fn pencil_modes() { + let mut s = Session::default(); + let wave: Vec<[f32; 2]> = (0..=200).map(|i| [100.0 + i as f32, 100.0 + (i as f32 * 0.05).sin() * 30.0]).collect(); + let count = |s: &mut Session, mode: &str| { + let id = run(s, "draw.freehand", json!({"points": wave, "mode": mode, "tolerance": 1.0}))["element"].as_u64().unwrap(); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap(); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + assert!(sh.fill.is_none() && sh.stroke.is_some(), "a pencil stroke is a line"); + sh.path.cmds.len() + }; + let smooth = count(&mut s, "smooth"); + let ink = count(&mut s, "ink"); + let straight = count(&mut s, "straighten"); + assert!(smooth < 16, "smooth: {smooth}"); + assert!(straight < ink, "straighten {straight} < ink {ink}"); + assert!(s.execute("draw.freehand", &json!({"points": wave, "mode": "felt"})).is_err()); + assert!(s.execute("draw.freehand", &json!({"points": [[0, 0], [0, 0]]})).is_err()); +} + +// ----- timeline frame ranges --------------------------------------------------------------- + +fn starts(s: &Session, layer: anicraft_doc::LayerId) -> Vec<(u32, u32)> { + s.doc.timeline.layer(layer).unwrap().keyframes.iter().map(|k| (k.start, k.duration)).collect() +} + +#[test] +fn range_insert_and_remove_frames_across_layers() { + let mut s = Session::default(); + let a = s.layer; + run(&mut s, "timeline.insert_frame", json!({"frame": 0, "count": 9})); + let b = anicraft_doc::LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + assert_eq!(starts(&s, b), vec![(0, 10)], "a new layer spans the timeline"); + run(&mut s, "timeline.insert_keyframe", json!({"layers": [a.0, b.0], "frame": 4})); + assert_eq!(starts(&s, a), vec![(0, 4), (4, 6)]); + assert_eq!(starts(&s, b), vec![(0, 4), (4, 6)]); + // F5 over frames 2�4 of both layers: three frames each, keys after move right. + run(&mut s, "timeline.insert_frame", json!({"layers": [a.0, b.0], "frame": 1, "count": 3})); + assert_eq!(starts(&s, a), vec![(0, 7), (7, 6)]); + assert_eq!(starts(&s, b), starts(&s, a)); + // Shift+F5 takes them out again; one undo step restores both layers. + let before = starts(&s, a); + run(&mut s, "timeline.remove_frame", json!({"layers": [a.0, b.0], "frame": 1, "count": 3})); + assert_eq!(starts(&s, a), vec![(0, 4), (4, 6)]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(starts(&s, a), before); + // Removing more frames than a layer has stops at its last frame instead of failing. + let r = run(&mut s, "timeline.remove_frame", json!({"layers": [a.0], "frame": 0, "count": 500})); + assert!(r["removed"].as_u64().unwrap() >= 12); + assert!(!starts(&s, a).is_empty()); + assert!(s.execute("timeline.insert_frame", &json!({"layers": [], "frame": 0})).is_err()); + assert!(s.execute("timeline.insert_frame", &json!({"layers": [u64::MAX], "frame": 0})).is_err()); + assert!(s.execute("timeline.insert_frame", &json!({"count": 0})).is_err()); +} + +#[test] +fn range_clear_removes_every_key_in_the_span() { + let mut s = Session::default(); + let a = s.layer; + run(&mut s, "timeline.insert_frame", json!({"frame": 0, "count": 19})); + for f in [5, 8, 12] { + run(&mut s, "timeline.insert_keyframe", json!({"frame": f})); + } + run(&mut s, "timeline.clear_keyframe", json!({"frame": 4, "count": 6})); + assert_eq!(starts(&s, a), vec![(0, 12), (12, 8)], "keys at 5 and 8 merged into the span before"); + assert!(s.execute("timeline.clear_keyframe", &json!({"frame": 1, "count": 3})).is_err(), "nothing to clear"); +} + +#[test] +fn moving_keyframes_by_drag() { + let mut s = Session::default(); + let a = s.layer; + run(&mut s, "timeline.insert_frame", json!({"frame": 0, "count": 19})); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20})); + run(&mut s, "timeline.insert_keyframe", json!({"frame": 5})); + run(&mut s, "timeline.insert_keyframe", json!({"frame": 10})); + // Right: the span before grows into the frames left behind; the layer keeps its length. + run(&mut s, "timeline.move_keyframes", json!({"from": 5, "by": 3})); + assert_eq!(starts(&s, a), vec![(0, 8), (8, 2), (10, 10)]); + // Onto another key: that key is replaced. + run(&mut s, "timeline.move_keyframes", json!({"from": 8, "by": 2})); + assert_eq!(starts(&s, a), vec![(0, 10), (10, 10)]); + // A range moves together, left; nothing is lost at the end. + run(&mut s, "timeline.insert_keyframe", json!({"frame": 14})); + run(&mut s, "timeline.move_keyframes", json!({"from": 10, "to": 14, "by": -4})); + assert_eq!(starts(&s, a), vec![(0, 6), (6, 4), (10, 10)]); + assert_eq!(s.doc.frame_count(), 20); + // Content travels with its key. + s.set_frame(6); + assert_eq!(s.visible_elements().len(), 1); + assert!(s.execute("timeline.move_keyframes", &json!({"from": 0, "by": -1})).is_err(), "not before frame 1"); + assert!(s.execute("timeline.move_keyframes", &json!({"from": 5, "to": 2, "by": 1})).is_err()); + assert_eq!(run(&mut s, "timeline.move_keyframes", json!({"from": 1, "to": 3, "by": 2}))["moved"], 0); +} + +#[test] +fn range_deletions_ask_when_artwork_would_go() { + let mut s = Session::default(); + run(&mut s, "timeline.insert_frame", json!({"frame": 0, "count": 9})); + run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": 3})); + s.set_frame(3); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": 5})); + // Frames 4–5 hold the key 3..5 entirely: removing them deletes its artwork. + let c = s.confirmation("timeline.remove_frame", &json!({"frame": 3, "count": 2})).expect("asks"); + assert!(!c.irreversible && c.action == "Remove Frames", "{c:?}"); + assert!(s.confirmation("timeline.remove_frame", &json!({"frame": 3, "count": 1})).is_none(), "the key keeps a frame"); + assert!(s.confirmation("timeline.clear_keyframe", &json!({"frame": 0, "count": 10})).is_some()); + assert!(s.confirmation("timeline.clear_keyframe", &json!({"frame": 5, "count": 5})).is_none(), "only empty keys"); +} + +// ----- frame clipboard --------------------------------------------------------------------- + +#[test] +fn copy_and_paste_frames_inserts_and_cuts_at_the_selection_edges() { + let mut s = Session::default(); + let a = s.layer; + run(&mut s, "timeline.insert_frame", json!({"frame": 0, "count": 9})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_keyframe", json!({"frame": 9})); + run(&mut s, "element.translate", json!({"dx": 90, "dy": 0})); + s.set_frame(0); + run(&mut s, "timeline.create_tween", json!({})); + // Frames 4–6, mid-tween: the copy starts with the tweened state at frame 4. + run(&mut s, "timeline.copy_frames", json!({"frame": 3, "count": 3})); + let clip = s.frame_clipboard.clone(); + assert_eq!(clip.count, 3); + assert_eq!(clip.layers[0].keys.len(), 1); + assert_eq!((clip.layers[0].keys[0].start, clip.layers[0].keys[0].duration), (0, 3)); + let x_at_3 = { s.set_frame(3); s.visible_elements()[0].transform.translation().x }; + let copied_x = clip.layers[0].keys[0].elements[0].transform.translation().x; + assert!((copied_x - x_at_3).abs() < 1e-3, "{copied_x} vs {x_at_3}"); + // Paste at frame 1: inserts three frames, later keys move right, ids are fresh. + let before = s.doc.frame_count(); + let old_ids: Vec = s.doc.timeline.layer(a).unwrap().keyframes.iter().flat_map(|k| k.elements.iter().map(|e| e.id.0)).collect(); + run(&mut s, "timeline.paste_frames", json!({"frame": 0})); + assert_eq!(s.doc.frame_count(), before + 3); + let l = s.doc.timeline.layer(a).unwrap(); + assert_eq!(l.keyframes[0].start, 0); + assert!(l.keyframe_starting_at(12).is_some(), "the key at frame 10 moved to frame 13"); + assert!(!old_ids.contains(&l.keyframes[0].elements[0].id.0), "fresh ids"); + // One undo step. + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.frame_count(), before); + // Cut removes what it copied. + run(&mut s, "timeline.cut_frames", json!({"frame": 0, "count": 2})); + assert_eq!(s.doc.frame_count(), before - 2); + assert!(s.execute("timeline.copy_frames", &json!({"frame": 500})).is_err(), "nothing there"); +} + +#[test] +fn pasting_several_layers_fills_the_layers_below_and_creates_missing_ones() { + let mut s = Session::new(anicraft_doc::sample::demo()); + let layers: Vec = s.doc.timeline.layers.iter().map(|l| l.id.0).collect(); + let n = layers.len(); + run(&mut s, "timeline.copy_frames", json!({"layers": [layers[1], layers[0]], "frame": 0, "count": 5})); + assert_eq!(s.frame_clipboard.layers.len(), 2); + assert_eq!(s.frame_clipboard.layers[0].name, s.doc.timeline.layers[0].name, "kept top to bottom"); + // Onto the bottom layer: the second copied layer needs a new layer under it. + run(&mut s, "timeline.paste_frames", json!({"layer": layers[n - 1], "frame": 0})); + assert_eq!(s.doc.timeline.layers.len(), n + 1); + let fresh = s.doc.timeline.layers.last().unwrap(); + assert_eq!(fresh.keyframes.first().map(|k| k.start), Some(0)); + assert!(s.doc.frame_count() >= 5); + // Every element id in the document stays unique per layer. + for l in &s.doc.timeline.layers { + let mut ids: Vec = l.keyframes.iter().filter(|k| k.start == 0).flat_map(|k| k.elements.iter().map(|e| e.id.0)).collect(); + let before = ids.len(); + ids.dedup(); + assert_eq!(ids.len(), before); + } + let empty = Session::default().execute("timeline.paste_frames", &json!({})); + assert!(empty.is_err(), "nothing copied"); +} + +// ----- paint bucket / ink bottle ----------------------------------------------------------- + +fn shapes_on_layer(s: &Session) -> Vec<(u64, Option, Option)> { + s.visible_elements() + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some((e.id.0, sh.fill.clone(), sh.stroke)), + _ => None, + }) + .collect() +} + +#[test] +fn bucket_recolours_a_fill_and_fills_a_closed_outline_underneath() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 50, "h": 50, "fill": "#ff0000"})); + let r = run(&mut s, "paint.bucket", json!({"x": 25, "y": 25, "color": "#00ff00"})); + assert!(r["recolored"].is_u64()); + assert!(matches!(shapes_on_layer(&s)[0].1, Some(anicraft_doc::Paint::Solid(c)) if c == anicraft_doc::Rgba::hex(0x00ff00))); + // An outline with no fill (a closed pen path): the bucket adds a fill below it. + run(&mut s, "draw.path", json!({"d": "M 100 100 L 200 100 L 200 180 L 100 180 Z", "fill": null, "stroke": "#000000", "stroke_width": 2})); + let r = run(&mut s, "paint.bucket", json!({"x": 150, "y": 140, "color": "#0000ff"})); + let id = r["element"].as_u64().expect("a new fill"); + let first = s.visible_elements()[0].clone(); + assert_eq!(first.id.0, id, "inserted at the bottom of the layer"); + let b = s.element_bounds(first.id); + assert!((b.min.x - 100.0).abs() < 2.5 && (b.max.x - 200.0).abs() < 2.5 && (b.min.y - 100.0).abs() < 2.5 && (b.max.y - 180.0).abs() < 2.5, "fills the inside, tucked under the line: {b:?}"); + let ElementKind::Shape(sh) = &first.kind else { panic!() }; + assert!(sh.stroke.is_none()); + // One undo step removes it. + run(&mut s, "edit.undo", json!({})); + assert!(s.visible_elements().iter().all(|e| e.id.0 != id)); +} + +#[test] +fn bucket_closes_small_gaps_only_when_asked() { + let mut s = Session::default(); + // Four separate lines forming a square with a 4 px opening in the top edge. + for (x0, y0, x1, y1) in [(0, 0, 48, 0), (52, 0, 100, 0), (100, 0, 100, 100), (100, 100, 0, 100), (0, 100, 0, 0)] { + run(&mut s, "draw.line", json!({"x0": x0 + 100, "y0": y0 + 100, "x1": x1 + 100, "y1": y1 + 100, "stroke_width": 2})); + } + let n = s.visible_elements().len(); + let e = s.execute("paint.bucket", &json!({"x": 150, "y": 150})); + assert!(e.is_err() && e.unwrap_err().to_string().contains("isn't closed"), "open without a gap size"); + assert_eq!(s.visible_elements().len(), n, "nothing added"); + run(&mut s, "paint.bucket", json!({"x": 150, "y": 150, "gap": 8})); + assert_eq!(s.visible_elements().len(), n + 1, "a larger gap size closes it"); + // Outside everything: not enclosed. + assert!(s.execute("paint.bucket", &json!({"x": 10, "y": 10})).is_err()); +} + +#[test] +fn ink_bottle_strokes_the_clicked_shape() { + let mut s = Session::default(); + run(&mut s, "draw.ellipse", json!({"x": 0, "y": 0, "w": 40, "h": 40, "stroke": null})); + assert!(shapes_on_layer(&s)[0].2.is_none()); + run(&mut s, "paint.ink", json!({"x": 20, "y": 20, "color": "#123456", "width": 4})); + let st = shapes_on_layer(&s)[0].2.expect("stroked"); + assert_eq!((st.color, st.width), (anicraft_doc::Rgba::hex(0x123456), 4.0)); + assert!(s.execute("paint.ink", &json!({"x": 300, "y": 300})).is_err(), "nothing there"); + // Symbols keep their colours. + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({})); + assert!(s.execute("paint.ink", &json!({"x": 20, "y": 20})).is_err()); +} + +#[test] +fn dragging_keyframes_onto_another_layer() { + let mut s = Session::default(); + let a = s.layer; + run(&mut s, "timeline.insert_frame", json!({"frame": 0, "count": 19})); + s.set_frame(5); + run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": 5})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": 10})); + let b = anicraft_doc::LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + // New layers go above the active one: b is row 0, a is row 1. Drag a's frames 6–10 up a row. + let content = |s: &Session, l| s.doc.timeline.layer(l).unwrap().keyframe_at(5).map_or(0, |k| k.elements.len()); + assert_eq!((content(&s, a), content(&s, b)), (1, 0)); + run(&mut s, "timeline.move_keyframes", json!({"layers": [a.0], "from": 5, "to": 9, "by": 0, "layer_by": -1})); + assert_eq!((content(&s, a), content(&s, b)), (0, 1), "the artwork moved up"); + assert_eq!(s.doc.timeline.layer(a).unwrap().end_frame(), 20, "the source keeps its frames, now empty"); + assert!(s.doc.timeline.layer(b).unwrap().keyframe_at(12).is_some(), "the target keeps the frames after the landing range"); + // One undo step puts it all back. + run(&mut s, "edit.undo", json!({})); + assert_eq!((content(&s, a), content(&s, b)), (1, 0)); + // With a frame shift too, and no layer there: an error, nothing changes. + run(&mut s, "timeline.move_keyframes", json!({"layers": [a.0], "from": 5, "to": 9, "by": 3, "layer_by": -1})); + assert!(s.doc.timeline.layer(b).unwrap().keyframe_starting_at(8).is_some_and(|i| !s.doc.timeline.layer(b).unwrap().keyframes[i].elements.is_empty())); + assert!(s.execute("timeline.move_keyframes", &json!({"layers": [b.0], "from": 0, "to": 30, "by": 0, "layer_by": -1})).is_err()); + assert!(s.execute("timeline.move_keyframes", &json!({"layers": [a.0], "from": 0, "by": 0, "layer_by": "x"})).is_err()); +} + +#[test] +fn opening_an_xfl_folder_imports_it_untitled() { + let dir = std::env::temp_dir().join(format!("anicraft-open-xfl-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("DOMDocument.xml"), + r##" + + "##, + ) + .unwrap(); + let mut s = Session::default(); + let v = run(&mut s, "file.open", json!({"path": dir.display().to_string()})); + assert_eq!((s.doc.stage.width, s.doc.stage.fps), (320, 12.0)); + assert_eq!(s.doc.timeline.layers[0].name, "Art"); + assert_eq!(s.doc.frame_count(), 6); + assert!(v["report"].as_str().unwrap().contains("1 text fields"), "{v}"); + assert!(s.path.is_none(), "imported documents are untitled: Save never writes over the original"); + assert!(s.execute("file.save", &json!({})).is_err()); + // It renders. + 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)))); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn animate_default_keys_map_to_the_same_commands() { + // Muscle memory: Animate's default keys (as its documentation lists them) do the same here. + let expected = [ + ("Ctrl+Z", "edit.undo"), + ("Ctrl+Y", "edit.redo"), + ("Ctrl+X", "edit.cut"), + ("Ctrl+C", "edit.copy"), + ("Ctrl+V", "edit.paste"), + ("Ctrl+Shift+V", "edit.paste_in_place"), + ("Ctrl+D", "edit.duplicate"), + ("Ctrl+A", "edit.select_all"), + ("Ctrl+Shift+A", "edit.deselect"), + ("Delete", "edit.delete"), + ("Backspace", "edit.delete"), + ("F5", "timeline.insert_frame"), + ("Shift+F5", "timeline.remove_frame"), + ("F6", "timeline.insert_keyframe"), + ("Shift+F6", "timeline.clear_keyframe"), + ("F7", "timeline.insert_blank_keyframe"), + ("Ctrl+Alt+X", "timeline.cut_frames"), + ("Ctrl+Alt+C", "timeline.copy_frames"), + ("Ctrl+Alt+V", "timeline.paste_frames"), + (".", "timeline.next_frame"), + (",", "timeline.prev_frame"), + ("Shift+,", "timeline.first_frame"), + ("Shift+.", "timeline.last_frame"), + ("F8", "modify.convert_to_symbol"), + ("Ctrl+B", "modify.break_apart"), + ("Ctrl+Shift+Z", "modify.remove_transform"), + ("Ctrl+Shift+9", "modify.rotate_cw"), + ("Ctrl+Shift+7", "modify.rotate_ccw"), + ("Ctrl+Shift+Up", "arrange.bring_to_front"), + ("Ctrl+Up", "arrange.bring_forward"), + ("Ctrl+Down", "arrange.send_backward"), + ("Ctrl+Shift+Down", "arrange.send_to_back"), + ("Ctrl+Alt+1", "align.left"), + ("Ctrl+Alt+2", "align.hcenter"), + ("Ctrl+Alt+3", "align.right"), + ("Ctrl+Alt+4", "align.top"), + ("Ctrl+Alt+5", "align.vcenter"), + ("Ctrl+Alt+6", "align.bottom"), + ("Ctrl+N", "file.new"), + ("Ctrl+O", "file.open"), + ("Ctrl+S", "file.save"), + ("Ctrl+Shift+S", "file.save_as"), + ]; + let cmds = commands(); + for (keys, id) in expected { + let c = cmds.iter().find(|c| c.id == id).unwrap_or_else(|| panic!("{id} missing")); + let alias = SHORTCUT_ALIASES.iter().any(|(k, i)| *k == keys && *i == id); + assert!(c.shortcut == Some(keys) || alias, "{id}: {:?}, expected {keys}", c.shortcut); + } + // No chord does two things. + let mut all: Vec<&str> = cmds.iter().filter_map(|c| c.shortcut).chain(SHORTCUT_ALIASES.iter().map(|(k, _)| *k)).collect(); + all.sort_unstable(); + let n = all.len(); + all.dedup(); + assert_eq!(all.len(), n, "a key chord is bound twice"); +} + +#[test] +fn bring_forward_send_backward_and_remove_transform() { + let mut s = Session::default(); + let ids: Vec = (0..3).map(|i| run(&mut s, "draw.rect", json!({"x": i * 10, "y": 0, "w": 50, "h": 50}))["element"].as_u64().unwrap()).collect(); + let order = |s: &Session| s.visible_elements().iter().map(|e| e.id.0).collect::>(); + run(&mut s, "element.select", json!({"ids": [ids[0]]})); + run(&mut s, "arrange.bring_forward", json!({})); + assert_eq!(order(&s), vec![ids[1], ids[0], ids[2]], "one step up"); + run(&mut s, "arrange.bring_forward", json!({})); + run(&mut s, "arrange.bring_forward", json!({})); + assert_eq!(order(&s), vec![ids[1], ids[2], ids[0]], "stops at the top"); + run(&mut s, "arrange.send_backward", json!({})); + assert_eq!(order(&s), vec![ids[1], ids[0], ids[2]]); + // Remove Transform keeps the position, drops scale and rotation. + run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 30})); + let before = s.visible_elements().iter().find(|e| e.id.0 == ids[0]).unwrap().transform.translation(); + run(&mut s, "modify.remove_transform", json!({})); + let t = s.visible_elements().iter().find(|e| e.id.0 == ids[0]).unwrap().transform; + assert_eq!(t.m[..4], [1.0, 0.0, 0.0, 1.0]); + assert_eq!(t.translation(), before); +} + +#[test] +fn mask_layers_reveal_hide_pick_and_move_as_a_group() { + let mut s = Session::default(); + let art = s.layer; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 200})); + let mask = run(&mut s, "layer.new", json!({"name": "Mask"}))["layer"].as_u64().map(LayerId).unwrap(); + run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 20, "h": 20})); + let r = run(&mut s, "layer.toggle_mask", json!({})); + assert_eq!(r["type"], "mask"); + assert_eq!(s.doc.timeline.layer(art).unwrap().parent, Some(mask), "the layer under it is masked"); + + // Only the mask's area shows, and only it can be picked. + let px = |s: &Session, x, y| anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().pixel(x, y).unwrap(); + let bg = px(&s, 500, 500); + assert_eq!(px(&s, 10, 10), bg, "masked away"); + assert_ne!(px(&s, 60, 60), bg, "revealed"); + run(&mut s, "layer.toggle_lock", json!({"layer": mask.0})); + assert_eq!(s.hit_test(Vec2::new(10.0, 10.0), 0.0), None); + assert_eq!(s.hit_test(Vec2::new(60.0, 60.0), 0.0).map(|(l, _)| l), Some(art)); + + // A layer added above a masked layer is masked too; the mask moves with its group. + run(&mut s, "layer.select", json!({"layer": art.0})); + let extra = run(&mut s, "layer.new", json!({}))["layer"].as_u64().map(LayerId).unwrap(); + assert_eq!(s.doc.timeline.layer(extra).unwrap().parent, Some(mask)); + let top = run(&mut s, "layer.new", json!({"name": "Top"}))["layer"].as_u64().map(LayerId).unwrap(); + run(&mut s, "layer.move_up", json!({"layer": top.0})); + let names = |s: &Session| s.doc.timeline.layers.iter().map(|l| l.id).collect::>(); + // `Top` was added inside the group too (above `extra`); moving it up leaves the group. + assert_eq!(s.doc.timeline.layer(top).unwrap().parent, None); + assert_eq!(names(&s), vec![top, mask, extra, art]); + run(&mut s, "layer.move_up", json!({"layer": mask.0})); + assert_eq!(names(&s), vec![mask, extra, art, top], "the whole group moved above Top"); + run(&mut s, "layer.move_down", json!({"layer": mask.0})); + assert_eq!(names(&s), vec![top, mask, extra, art]); + // Moving the last masked layer up past its mask frees it; undo puts it back. + run(&mut s, "layer.move_up", json!({"layer": extra.0})); + assert_eq!(s.doc.timeline.layer(extra).unwrap().parent, None); + s.undo().unwrap(); + assert_eq!(s.doc.timeline.layer(extra).unwrap().parent, Some(mask)); + + // `masked` needs a mask above; unknown types are refused. + assert!(s.execute("layer.set_type", &json!({"type": "masked", "layer": top.0})).is_err()); + assert!(s.execute("layer.set_type", &json!({"type": "wobbly"})).is_err()); + // Turning the mask off frees its layers; deleting a mask does the same. + run(&mut s, "layer.toggle_mask", json!({"layer": mask.0})); + assert!(s.doc.timeline.layers.iter().all(|l| l.parent.is_none())); + assert_ne!(px(&s, 10, 10), bg, "everything shows again"); + s.undo().unwrap(); + run(&mut s, "layer.delete", json!({"layer": mask.0, "confirm": true})); + assert!(s.doc.timeline.layers.iter().all(|l| l.parent.is_none())); +} \ No newline at end of file diff --git a/crates/geom/Cargo.toml b/crates/geom/Cargo.toml new file mode 100644 index 00000000..b7205fcc --- /dev/null +++ b/crates/geom/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "anicraft-geom" +description = "AniCraft L0: points, affine transforms, Bezier paths, flattening and hit testing" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[dependencies] +serde.workspace = true + +[dev-dependencies] +serde_json.workspace = true + +[lints] +workspace = true diff --git a/crates/geom/src/affine.rs b/crates/geom/src/affine.rs new file mode 100644 index 00000000..c64bfebd --- /dev/null +++ b/crates/geom/src/affine.rs @@ -0,0 +1,205 @@ +//! 2D affine transforms and their decomposition for tweening. + +use crate::Vec2; +use serde::{Deserialize, Serialize}; + +/// Affine transform `[a b c d e f]` mapping `(x, y)` to `(a x + c y + e, b x + d y + f)` +/// (the column convention used by SVG, PDF and most animation formats). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Affine { + pub m: [f32; 6], +} + +impl Default for Affine { + fn default() -> Self { + Affine::IDENTITY + } +} + +impl Affine { + pub const IDENTITY: Affine = Affine { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] }; + + pub fn translate(tx: f32, ty: f32) -> Affine { + Affine { m: [1.0, 0.0, 0.0, 1.0, tx, ty] } + } + pub fn scale(sx: f32, sy: f32) -> Affine { + Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] } + } + /// Rotation by `radians` (clockwise on a y-down screen). + pub fn rotate(radians: f32) -> Affine { + let (s, c) = radians.sin_cos(); + Affine { m: [c, s, -s, c, 0.0, 0.0] } + } + + /// `self ∘ other`: apply `other` first, then `self`. + pub fn then_apply_to(&self, other: &Affine) -> Affine { + let [a, b, c, d, e, f] = self.m; + let [a2, b2, c2, d2, e2, f2] = other.m; + Affine { + m: [ + a * a2 + c * b2, + b * a2 + d * b2, + a * c2 + c * d2, + b * c2 + d * d2, + a * e2 + c * f2 + e, + b * e2 + d * f2 + f, + ], + } + } + + /// Composition in reading order: `a.mul(b)` applies `b` first, then `a`. + pub fn mul(&self, other: &Affine) -> Affine { + self.then_apply_to(other) + } + + pub fn apply(&self, p: Vec2) -> Vec2 { + let [a, b, c, d, e, f] = self.m; + Vec2::new(a * p.x + c * p.y + e, b * p.x + d * p.y + f) + } + + /// Applies only the linear part (for vectors). + pub fn apply_vector(&self, v: Vec2) -> Vec2 { + let [a, b, c, d, _, _] = self.m; + Vec2::new(a * v.x + c * v.y, b * v.x + d * v.y) + } + + pub fn determinant(&self) -> f32 { + self.m[0] * self.m[3] - self.m[1] * self.m[2] + } + + /// Inverse, or `None` for a singular (or non-finite) matrix. + pub fn inverse(&self) -> Option { + let det = self.determinant(); + if !det.is_finite() || det.abs() < 1e-12 { + return None; + } + let [a, b, c, d, e, f] = self.m; + let inv = 1.0 / det; + let ia = d * inv; + let ib = -b * inv; + let ic = -c * inv; + let id = a * inv; + Some(Affine { m: [ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)] }) + } + + pub fn translation(&self) -> Vec2 { + Vec2::new(self.m[4], self.m[5]) + } + + pub fn is_finite(&self) -> bool { + self.m.iter().all(|v| v.is_finite()) + } + + /// Approximate uniform scale factor (sqrt of |det|), used for stroke widths and tolerances. + pub fn mean_scale(&self) -> f32 { + self.determinant().abs().sqrt() + } + + /// Decompose into translation, rotation, scale and skew (QR-style). + pub fn decompose(&self) -> Decomposed { + let [a, b, c, d, e, f] = self.m; + let sx = (a * a + b * b).sqrt(); + let rotation = b.atan2(a); + let det = a * d - b * c; + let (sy, skew) = if sx > 1e-12 { + let sy = det / sx; + // col1 · col2 = sx · sy · skew + let skew = if det.abs() > 1e-12 { (a * c + b * d) / det } else { 0.0 }; + (sy, skew) + } else { + ((c * c + d * d).sqrt(), 0.0) + }; + Decomposed { tx: e, ty: f, sx, sy, rotation, skew } + } +} + +/// Transform components that interpolate well over time. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Decomposed { + pub tx: f32, + pub ty: f32, + pub sx: f32, + pub sy: f32, + /// Radians. + pub rotation: f32, + /// Shear factor (x += skew * y before scaling). + pub skew: f32, +} + +impl Default for Decomposed { + fn default() -> Self { + Decomposed { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, rotation: 0.0, skew: 0.0 } + } +} + +impl Decomposed { + /// `T · R · Shear · S` — the inverse of [`Affine::decompose`]. + pub fn compose(&self) -> Affine { + let t = Affine::translate(self.tx, self.ty); + let r = Affine::rotate(self.rotation); + let k = Affine { m: [1.0, 0.0, self.skew, 1.0, 0.0, 0.0] }; + let s = Affine::scale(self.sx, self.sy); + t.mul(&r).mul(&k).mul(&s) + } + + /// Component-wise interpolation; rotation takes the shortest arc. + pub fn lerp(&self, o: &Decomposed, t: f32) -> Decomposed { + let mut dr = o.rotation - self.rotation; + let tau = std::f32::consts::TAU; + while dr > std::f32::consts::PI { + dr -= tau; + } + while dr < -std::f32::consts::PI { + dr += tau; + } + Decomposed { + tx: crate::lerp(self.tx, o.tx, t), + ty: crate::lerp(self.ty, o.ty, t), + sx: crate::lerp(self.sx, o.sx, t), + sy: crate::lerp(self.sy, o.sy, t), + rotation: self.rotation + dr * t, + skew: crate::lerp(self.skew, o.skew, t), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: &Affine, b: &Affine) -> bool { + a.m.iter().zip(b.m.iter()).all(|(x, y)| (x - y).abs() < 1e-4) + } + + #[test] + fn inverse_roundtrip() { + let m = Affine::translate(10.0, -4.0).mul(&Affine::rotate(0.7)).mul(&Affine::scale(2.0, 0.5)); + let inv = m.inverse().unwrap(); + assert!(close(&m.mul(&inv), &Affine::IDENTITY)); + assert!(Affine::scale(0.0, 1.0).inverse().is_none()); + } + + #[test] + fn decompose_compose_identity() { + for (rot, sx, sy, skew) in [(0.3, 2.0, 1.5, 0.0), (-2.5, 0.5, 3.0, 0.2), (1.0, 1.0, -1.0, 0.0)] { + let d = Decomposed { tx: 5.0, ty: 7.0, sx, sy, rotation: rot, skew }; + let m = d.compose(); + let back = m.decompose().compose(); + assert!(close(&m, &back), "{m:?} vs {back:?}"); + } + } + + #[test] + fn rotation_lerp_takes_short_arc() { + let a = Decomposed { rotation: 3.0, ..Default::default() }; + let b = Decomposed { rotation: -3.0, ..Default::default() }; + let mid = a.lerp(&b, 0.5); + assert!((mid.rotation.abs() - std::f32::consts::PI).abs() < 0.01); + } + + #[test] + fn apply_order() { + let m = Affine::translate(10.0, 0.0).mul(&Affine::scale(2.0, 2.0)); + assert_eq!(m.apply(Vec2::new(1.0, 1.0)), Vec2::new(12.0, 2.0)); + } +} diff --git a/crates/geom/src/edit.rs b/crates/geom/src/edit.rs new file mode 100644 index 00000000..3f5dbc80 --- /dev/null +++ b/crates/geom/src/edit.rs @@ -0,0 +1,487 @@ +//! Point editing on Bézier paths: addressing anchors and handles, splitting and removing +//! segments, smooth/corner conversion and nearest-segment search. +//! +//! Addressing: command `i` of a path owns its *end point* (the anchor, slot 0) and its control +//! points: slot 1 is the first control point (`QuadTo`'s or `CubicTo`'s `c1`, the out-handle of +//! the previous anchor) and slot 2 is `CubicTo`'s `c2` (the in-handle of anchor `i`). + +use crate::{Affine, Path, PathCmd, Vec2}; + +/// Slot numbers. +pub const ANCHOR: u8 = 0; +pub const C1: u8 = 1; +pub const C2: u8 = 2; + +/// Points closer than this (stage units) are the same anchor. +const LINK_EPS: f32 = 1e-3; + +impl Path { + /// The point at `(cmd, slot)`. + pub fn point(&self, cmd: usize, slot: u8) -> Option { + match (self.cmds.get(cmd)?, slot) { + (PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p), ANCHOR) => Some(*p), + (PathCmd::QuadTo(c, _) | PathCmd::CubicTo(c, _, _), C1) => Some(*c), + (PathCmd::CubicTo(_, c, _), C2) => Some(*c), + _ => None, + } + } + + /// Sets the point at `(cmd, slot)`; false when it does not exist or `p` is not finite. + pub fn set_point(&mut self, cmd: usize, slot: u8, p: Vec2) -> bool { + if !p.is_finite() { + return false; + } + let Some(c) = self.cmds.get_mut(cmd) else { return false }; + let target = match (c, slot) { + (PathCmd::MoveTo(a) | PathCmd::LineTo(a) | PathCmd::QuadTo(_, a) | PathCmd::CubicTo(_, _, a), ANCHOR) => a, + (PathCmd::QuadTo(c1, _) | PathCmd::CubicTo(c1, _, _), C1) => c1, + (PathCmd::CubicTo(_, c2, _), C2) => c2, + _ => return false, + }; + *target = p; + true + } + + /// Commands that own an anchor, with the anchor position. + pub fn anchors(&self) -> Vec<(usize, Vec2)> { + (0..self.cmds.len()).filter_map(|i| self.point(i, ANCHOR).map(|p| (i, p))).collect() + } + + /// The point a segment command starts from (previous anchor, or the subpath start after a + /// `Close`). `None` for `MoveTo`/`Close` or out of range. + pub fn segment_start(&self, cmd: usize) -> Option { + if !matches!(self.cmds.get(cmd)?, PathCmd::LineTo(_) | PathCmd::QuadTo(..) | PathCmd::CubicTo(..)) { + return None; + } + let (mut cur, mut start) = (Vec2::ZERO, Vec2::ZERO); + for c in self.cmds.get(..cmd)? { + match *c { + PathCmd::MoveTo(p) => { + cur = p; + start = p; + } + PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => cur = p, + PathCmd::Close => cur = start, + } + } + Some(cur) + } + + /// Point on segment `cmd` at parameter `t ∈ [0, 1]`. + pub fn segment_point(&self, cmd: usize, t: f32) -> Option { + let s = self.segment_start(cmd)?; + let mt = 1.0 - t; + Some(match *self.cmds.get(cmd)? { + PathCmd::LineTo(p) => s.lerp(p, t), + PathCmd::QuadTo(c, p) => s * (mt * mt) + c * (2.0 * mt * t) + p * (t * t), + PathCmd::CubicTo(c1, c2, p) => s * (mt * mt * mt) + c1 * (3.0 * mt * mt * t) + c2 * (3.0 * mt * t * t) + p * (t * t * t), + _ => return None, + }) + } + + /// Splits segment `cmd` at `t` (de Casteljau), adding an anchor without changing the shape. + pub fn split_segment(&mut self, cmd: usize, t: f32) -> bool { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { return false }; + let Some(s) = self.segment_start(cmd) else { return false }; + let Some(&c) = self.cmds.get(cmd) else { return false }; + let (first, second) = match c { + PathCmd::LineTo(p) => (PathCmd::LineTo(s.lerp(p, t)), PathCmd::LineTo(p)), + PathCmd::QuadTo(c1, p) => { + let (a, b) = (s.lerp(c1, t), c1.lerp(p, t)); + let m = a.lerp(b, t); + (PathCmd::QuadTo(a, m), PathCmd::QuadTo(b, p)) + } + PathCmd::CubicTo(c1, c2, p) => { + let (a, b, c3) = (s.lerp(c1, t), c1.lerp(c2, t), c2.lerp(p, t)); + let (d, e) = (a.lerp(b, t), b.lerp(c3, t)); + let m = d.lerp(e, t); + (PathCmd::CubicTo(a, d, m), PathCmd::CubicTo(e, c3, p)) + } + _ => return false, + }; + if let Some(slot) = self.cmds.get_mut(cmd) { + *slot = first; + } + self.cmds.insert(cmd + 1, second); + true + } + + fn is_segment(&self, cmd: usize) -> bool { + matches!(self.cmds.get(cmd), Some(PathCmd::LineTo(_) | PathCmd::QuadTo(..) | PathCmd::CubicTo(..))) + } + + /// The `MoveTo` that starts the subpath containing `cmd`. + fn subpath_start(&self, cmd: usize) -> Option { + self.cmds.get(..=cmd)?.iter().rposition(|x| matches!(x, PathCmd::MoveTo(_))) + } + + /// Writes every `Close` that would draw an implicit edge as an explicit line back to the + /// subpath start, so each edge of the outline is a command that can be split and curved. + /// The shape does not change. + pub fn close_explicitly(&mut self) { + let mut out = Vec::with_capacity(self.cmds.len() + 4); + let (mut cur, mut start) = (Vec2::ZERO, Vec2::ZERO); + for &c in &self.cmds { + match c { + PathCmd::MoveTo(p) => { + cur = p; + start = p; + } + PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => cur = p, + PathCmd::Close => { + if cur.distance(start) > LINK_EPS { + out.push(PathCmd::LineTo(start)); + } + cur = start; + } + } + out.push(c); + } + self.cmds = out; + } + + /// In a closed subpath whose last segment returns to the start, the start `MoveTo` and that + /// segment's end are one anchor stored twice. Returns the other copy. + pub fn linked_anchor(&self, cmd: usize) -> Option { + match self.cmds.get(cmd)? { + PathCmd::MoveTo(p) => { + let end = (cmd + 1..self.cmds.len()).find(|&j| !self.is_segment(j))?; + let last = end.checked_sub(1).filter(|&l| l > cmd)?; + (matches!(self.cmds.get(end), Some(PathCmd::Close)) && self.point(last, ANCHOR)?.distance(*p) <= LINK_EPS).then_some(last) + } + _ if self.is_segment(cmd) && matches!(self.cmds.get(cmd + 1), Some(PathCmd::Close)) => { + let m = self.subpath_start(cmd)?; + (self.linked_anchor(m) == Some(cmd)).then_some(m) + } + _ => None, + } + } + + /// The command that names an anchor: the `MoveTo` for a closed subpath's start, else `cmd`. + /// Overlays list only canonical anchors, so the start is not drawn twice. + pub fn canonical_anchor(&self, cmd: usize) -> usize { + match self.cmds.get(cmd) { + Some(PathCmd::MoveTo(_)) | None => cmd, + _ => self.linked_anchor(cmd).unwrap_or(cmd), + } + } + + /// Anchors as the user sees them: one per position, start of a closed subpath once. + pub fn editable_anchors(&self) -> Vec<(usize, Vec2)> { + self.anchors().into_iter().filter(|(i, _)| self.canonical_anchor(*i) == *i).collect() + } + + /// The segments that arrive at and leave anchor `cmd`: `(in, out)`. The in-segment's `C2` + /// and the out-segment's `C1` are the anchor's handles. + pub fn anchor_segments(&self, cmd: usize) -> (Option, Option) { + let cmd = self.canonical_anchor(cmd); + let out = |i: usize| (self.is_segment(i + 1)).then_some(i + 1); + match self.cmds.get(cmd) { + Some(PathCmd::MoveTo(_)) => (self.linked_anchor(cmd), out(cmd)), + Some(_) if self.is_segment(cmd) => (Some(cmd), out(cmd)), + _ => (None, None), + } + } + + /// Every stored point that moves when anchor `cmd` moves: both copies of the anchor and its + /// two handles. + pub fn anchor_group(&self, cmd: usize) -> Vec<(usize, u8)> { + let cmd = self.canonical_anchor(cmd); + let mut v = vec![(cmd, ANCHOR)]; + if let Some(k) = self.linked_anchor(cmd) { + v.push((k, ANCHOR)); + } + let (i, o) = self.anchor_segments(cmd); + if let Some(i) = i.filter(|&i| matches!(self.cmds.get(i), Some(PathCmd::CubicTo(..)))) { + v.push((i, C2)); + } + if let Some(o) = o.filter(|&o| matches!(self.cmds.get(o), Some(PathCmd::CubicTo(..)))) { + v.push((o, C1)); + } + v + } + + /// Removes anchor `cmd`. A segment anchor is dropped (the next segment then starts from the + /// previous anchor); a subpath start passes to the next anchor. Refuses when the subpath + /// would be left with fewer than two anchors. + pub fn remove_anchor(&mut self, cmd: usize) -> bool { + let cmd = self.canonical_anchor(cmd); + let Some(&c) = self.cmds.get(cmd) else { return false }; + let Some(m) = self.subpath_start(cmd) else { return false }; + let segs = (m + 1..self.cmds.len()).take_while(|&j| self.is_segment(j)).count(); + let linked = self.linked_anchor(m); + let distinct = 1 + segs - usize::from(linked.is_some()); + if distinct <= 2 { + return false; + } + match c { + PathCmd::MoveTo(_) => { + let Some(next_end) = self.point(cmd + 1, ANCHOR) else { return false }; + if let Some(k) = linked { + self.set_point(k, ANCHOR, next_end); + } + if let Some(slot) = self.cmds.get_mut(cmd) { + *slot = PathCmd::MoveTo(next_end); + } + self.cmds.remove(cmd + 1); + true + } + PathCmd::LineTo(_) | PathCmd::QuadTo(..) | PathCmd::CubicTo(..) => { + self.cmds.remove(cmd); + true + } + PathCmd::Close => false, + } + } + + /// Makes anchor `cmd` a corner: its handles collapse onto it (segments stay curves). + pub fn make_corner(&mut self, cmd: usize) -> bool { + let Some(a) = self.point(cmd, ANCHOR) else { return false }; + let (i, o) = self.anchor_segments(cmd); + let mut changed = false; + if let Some(i) = i.filter(|&i| matches!(self.cmds.get(i), Some(PathCmd::CubicTo(..)))) { + changed |= self.set_point(i, C2, a); + } + if let Some(o) = o.filter(|&o| matches!(self.cmds.get(o), Some(PathCmd::CubicTo(..)))) { + changed |= self.set_point(o, C1, a); + } + changed + } + + /// Makes anchor `cmd` smooth: neighbouring segments become cubics whose handles at this + /// anchor are collinear, along the direction from the previous to the next anchor. + pub fn make_smooth(&mut self, cmd: usize) -> bool { + let Some(a) = self.point(cmd, ANCHOR) else { return false }; + let (i, o) = self.anchor_segments(cmd); + let prev = i.and_then(|i| self.segment_start(i)); + let next = o.and_then(|o| self.point(o, ANCHOR)); + let dir = match (prev, next) { + (Some(p), Some(n)) => (n - p).normalized(), + (Some(p), None) => (a - p).normalized(), + (None, Some(n)) => (n - a).normalized(), + (None, None) => return false, + }; + if dir == Vec2::ZERO { + return false; + } + if let (Some(i), Some(p)) = (i, prev) { + self.to_cubic(i); + self.set_point(i, C2, a - dir * (a.distance(p) / 3.0)); + } + if let (Some(o), Some(n)) = (o, next) { + self.to_cubic(o); + self.set_point(o, C1, a + dir * (a.distance(n) / 3.0)); + } + true + } + + /// Converts segment `cmd` to an equivalent cubic (no-op for cubics and non-segments). + pub fn to_cubic(&mut self, cmd: usize) { + let Some(s) = self.segment_start(cmd) else { return }; + let Some(c) = self.cmds.get_mut(cmd) else { return }; + *c = match *c { + PathCmd::LineTo(p) => PathCmd::CubicTo(s.lerp(p, 1.0 / 3.0), s.lerp(p, 2.0 / 3.0), p), + PathCmd::QuadTo(q, p) => PathCmd::CubicTo(s + (q - s) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p), + other => other, + }; + } + + /// The segment nearest to `p` (in the space `m` maps to): `(cmd, t, distance)`. + pub fn nearest_segment(&self, p: Vec2, m: &Affine) -> Option<(usize, f32, f32)> { + let mut best: Option<(usize, f32, f32)> = None; + for cmd in 0..self.cmds.len().min(100_000) { + if self.segment_start(cmd).is_none() { + continue; + } + let steps = 32; + for i in 0..=steps { + let t = i as f32 / steps as f32; + let Some(q) = self.segment_point(cmd, t) else { continue }; + let d = m.apply(q).distance(p); + if best.is_none_or(|b| d < b.2) { + best = Some((cmd, t, d)); + } + } + } + // refine t around the best sample + let (cmd, mut t, mut d) = best?; + let mut step = 1.0 / 64.0; + for _ in 0..12 { + for cand in [t - step, t + step] { + let c = cand.clamp(0.0, 1.0); + if let Some(q) = self.segment_point(cmd, c) { + let dc = m.apply(q).distance(p); + if dc < d { + d = dc; + t = c; + } + } + } + step *= 0.5; + } + Some((cmd, t, d)) + } +} + +/// Ramer–Douglas–Peucker simplification (iterative; bounded memory). +pub fn simplify(points: &[Vec2], tolerance: f32) -> Vec { + let n = points.len(); + if n < 3 { + return points.to_vec(); + } + let tol = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.5 }; + let mut keep = vec![false; n]; + keep[0] = true; + keep[n - 1] = true; + let mut stack = vec![(0usize, n - 1)]; + while let Some((a, b)) = stack.pop() { + if b <= a + 1 { + continue; + } + let (pa, pb) = (points[a], points[b]); + let mut far = (a, 0.0f32); + for (i, p) in points.iter().enumerate().take(b).skip(a + 1) { + let d = crate::path::segment_distance(*p, pa, pb); + if d > far.1 { + far = (i, d); + } + } + if far.1 > tol { + keep[far.0] = true; + stack.push((a, far.0)); + stack.push((far.0, b)); + } + } + points.iter().zip(keep).filter_map(|(p, k)| k.then_some(*p)).collect() +} + +/// A straight-segment path through `points`. +pub fn polyline_path(points: &[Vec2], closed: bool) -> Path { + let mut path = Path::new(); + for (i, &p) in points.iter().enumerate() { + if i == 0 { + path.move_to(p); + } else { + path.line_to(p); + } + } + if closed && points.len() > 2 { + path.close(); + } + path +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cubic_path() -> Path { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(10.0, 20.0), Vec2::new(30.0, 20.0), Vec2::new(40.0, 0.0)).line_to(Vec2::new(40.0, -20.0)); + p + } + + #[test] + fn addressing() { + let p = cubic_path(); + assert_eq!(p.anchors().len(), 3); + assert_eq!(p.point(1, C2), Some(Vec2::new(30.0, 20.0))); + assert_eq!(p.point(2, C1), None); + assert_eq!(p.segment_start(2), Some(Vec2::new(40.0, 0.0))); + let mut q = p.clone(); + assert!(q.set_point(1, C1, Vec2::new(5.0, 5.0))); + assert!(!q.set_point(0, C1, Vec2::new(5.0, 5.0))); + assert!(!q.set_point(1, ANCHOR, Vec2::new(f32::NAN, 0.0))); + } + + #[test] + fn split_keeps_the_curve() { + let p = cubic_path(); + let mut q = p.clone(); + assert!(q.split_segment(1, 0.3)); + assert_eq!(q.anchors().len(), 4); + // the new anchor lies on the original curve + let on = p.segment_point(1, 0.3).unwrap(); + assert!(q.point(1, ANCHOR).unwrap().distance(on) < 1e-4); + // and the flattened shapes agree + let a = p.flatten(&Affine::IDENTITY, 0.01)[0].points.clone(); + let b = q.flatten(&Affine::IDENTITY, 0.01)[0].points.clone(); + let near = |pt: &Vec2, set: &[Vec2]| set.windows(2).map(|w| crate::path::segment_distance(*pt, w[0], w[1])).fold(f32::INFINITY, f32::min); + assert!(b.iter().all(|pt| near(pt, &a) < 0.2)); + assert!(!q.split_segment(0, 0.5), "MoveTo is not a segment"); + } + + #[test] + fn remove_keeps_at_least_two_anchors() { + let mut p = cubic_path(); + assert!(p.remove_anchor(1)); + assert_eq!(p.anchors().len(), 2); + assert!(!p.remove_anchor(1), "a subpath needs two anchors"); + let mut r = Path::rect(0.0, 0.0, 10.0, 10.0); + assert!(r.remove_anchor(0), "MoveTo takes over the next anchor"); + assert_eq!(r.point(0, ANCHOR), Some(Vec2::new(10.0, 0.0))); + } + + #[test] + fn closed_subpaths_have_one_start_anchor() { + let mut r = Path::rect(0.0, 0.0, 10.0, 10.0); + let before = r.flatten(&Affine::IDENTITY, 0.1); + r.close_explicitly(); + assert_eq!(r.flatten(&Affine::IDENTITY, 0.1)[0].points.len(), before[0].points.len() + 1, "only a duplicate end point added"); + assert_eq!(r.linked_anchor(0), Some(4)); + assert_eq!(r.linked_anchor(4), Some(0)); + assert_eq!(r.canonical_anchor(4), 0); + assert_eq!(r.editable_anchors().len(), 4); + assert_eq!(r.anchor_segments(0), (Some(4), Some(1))); + r.close_explicitly(); + assert_eq!(r.cmds.len(), 6, "idempotent"); + // The start anchor is smooth across the seam and removable. + assert!(r.make_smooth(0)); + assert!(matches!(r.cmds[4], PathCmd::CubicTo(..)) && matches!(r.cmds[1], PathCmd::CubicTo(..))); + let mut q = r.clone(); + assert!(q.remove_anchor(4), "the duplicate names the start"); + assert_eq!(q.editable_anchors().len(), 3); + assert_eq!(q.point(0, ANCHOR), Some(Vec2::new(10.0, 0.0))); + assert_eq!(q.linked_anchor(0), Some(3), "still closed on the new start"); + assert!(q.remove_anchor(0)); + assert!(!q.remove_anchor(0), "two anchors stay"); + // Moving the start moves both copies and both handles. + let g = r.anchor_group(0); + assert!(g.contains(&(0, ANCHOR)) && g.contains(&(4, ANCHOR)) && g.contains(&(4, C2)) && g.contains(&(1, C1))); + } + + #[test] + fn smooth_and_corner() { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(10.0, 10.0)).line_to(Vec2::new(20.0, 0.0)); + assert!(p.make_smooth(1)); + let (a, i, o) = (p.point(1, ANCHOR).unwrap(), p.point(1, C2).unwrap(), p.point(2, C1).unwrap()); + assert!((i - a).cross(o - a).abs() < 1e-3, "handles collinear"); + assert!((i - a).dot(o - a) < 0.0, "on opposite sides"); + assert!(p.make_corner(1)); + assert_eq!(p.point(1, C2), Some(a)); + } + + #[test] + fn nearest_segment_finds_the_curve() { + let p = cubic_path(); + let target = p.segment_point(1, 0.62).unwrap(); + let (cmd, t, d) = p.nearest_segment(target + Vec2::new(0.0, 0.5), &Affine::IDENTITY).unwrap(); + assert_eq!(cmd, 1); + assert!((t - 0.62).abs() < 0.05, "{t}"); + assert!(d < 1.0); + } + + #[test] + fn simplify_and_fit() { + let pts: Vec = (0..=100).map(|i| Vec2::new(i as f32, (i as f32 * 0.1).sin() * 0.05)).collect(); + assert_eq!(simplify(&pts, 0.5).len(), 2, "a nearly straight stroke collapses to its ends"); + let wave: Vec = (0..=200).map(|i| Vec2::new(i as f32, (i as f32 * 0.05).sin() * 30.0)).collect(); + let s = simplify(&wave, 1.0); + assert!(s.len() > 4 && s.len() < 60, "{}", s.len()); + let path = polyline_path(&s, false); + assert_eq!(path.anchors().len(), s.len()); + assert!(path.anchors().iter().zip(&s).all(|((_, a), b)| a.distance(*b) < 1e-4), "passes through the points"); + assert!(simplify(&[], 1.0).is_empty()); + } +} diff --git a/crates/geom/src/fit.rs b/crates/geom/src/fit.rs new file mode 100644 index 00000000..0bfcb728 --- /dev/null +++ b/crates/geom/src/fit.rs @@ -0,0 +1,381 @@ +//! Fitting cubic Béziers to freehand strokes (Pencil "Smooth" mode). +//! +//! 1. Consecutive duplicate points are dropped (a held mouse reports the same position). +//! 2. Corners are where the stroke direction, measured over `corner_window` of arc length on +//! each side, turns by more than 60°; only the sharpest point of each turn counts. +//! 3. Each run between corners is fitted by least squares with fixed end tangents and Newton +//! reparameterisation, splitting at the worst point until within `tolerance` (P. J. Schneider, +//! "An Algorithm for Automatically Fitting Digitized Curves", Graphics Gems, 1990). +//! +//! Ported from PhotoCraft's mask tracer (`vector::trace`, same project family, MIT OR +//! Apache-2.0) and adapted for strokes: open paths, a caller-chosen corner window (so it can +//! follow the zoom), end tangents measured over that window instead of from one noisy +//! neighbour, and no indexing that input can push out of range. Maths runs in `f64`. + +use crate::{Path, Vec2}; + +type P = (f64, f64); + +fn sub(a: P, b: P) -> P { + (a.0 - b.0, a.1 - b.1) +} +fn add(a: P, b: P) -> P { + (a.0 + b.0, a.1 + b.1) +} +fn mul(a: P, k: f64) -> P { + (a.0 * k, a.1 * k) +} +fn dot(a: P, b: P) -> f64 { + a.0 * b.0 + a.1 * b.1 +} +fn len(a: P) -> f64 { + a.0.hypot(a.1) +} +fn norm(a: P) -> P { + let l = len(a); + if l > 1e-12 { (a.0 / l, a.1 / l) } else { (0.0, 0.0) } +} + +/// A smooth path through a freehand stroke: cubic segments within `tolerance` of the points, +/// with corners kept sharp. Fewer than two distinct points give a path with at most a `MoveTo`. +pub fn fit_curve(points: &[Vec2], tolerance: f32, corner_window: f32, closed: bool) -> Path { + let tol = if tolerance.is_finite() && tolerance > 0.0 { f64::from(tolerance) } else { 1.0 }; + let window = if corner_window.is_finite() && corner_window > 0.0 { f64::from(corner_window) } else { 3.0 }; + let mut lp: Vec

= Vec::with_capacity(points.len()); + for p in points.iter().filter(|p| p.is_finite()) { + let q = (f64::from(p.x), f64::from(p.y)); + if lp.last().is_none_or(|&l| len(sub(q, l)) > 1e-4) { + lp.push(q); + } + } + if closed && lp.len() > 2 && lp.first().zip(lp.last()).is_some_and(|(a, b)| len(sub(*a, *b)) <= 1e-4) { + lp.pop(); + } + let mut path = Path::new(); + let v = |p: P| Vec2::new(p.0 as f32, p.1 as f32); + let Some(&first) = lp.first() else { return path }; + path.move_to(v(first)); + if lp.len() < 3 { + for &p in lp.iter().skip(1) { + path.line_to(v(p)); + } + return path; + } + let segs = if closed { fit_closed(&lp, tol, window) } else { fit_open(&lp, tol, window) }; + for s in segs { + path.cubic_to(v(s[1]), v(s[2]), v(s[3])); + } + if closed { + path.close(); + } + path +} + +/// The point `window` of arc length away from `i`, forwards or backwards. Open strokes stop at +/// their ends; closed ones wrap. +fn walk(lp: &[P], i: usize, window: f64, fwd: bool, closed: bool) -> P { + let n = lp.len(); + let mut acc = 0.0; + let mut cur = i.min(n - 1); + for _ in 0..n { + let nx = match (fwd, closed) { + (true, true) => (cur + 1) % n, + (false, true) => (cur + n - 1) % n, + (true, false) if cur + 1 < n => cur + 1, + (false, false) if cur > 0 => cur - 1, + _ => break, + }; + let d = len(sub(lp[nx], lp[cur])); + if acc + d >= window { + let t = (window - acc) / d.max(1e-12); + return add(lp[cur], mul(sub(lp[nx], lp[cur]), t)); + } + acc += d; + cur = nx; + } + lp[cur] +} + +/// Indices of corner points (never an open stroke's ends). +fn corners(lp: &[P], window: f64, closed: bool) -> Vec { + let n = lp.len(); + let cos_thresh = 60f64.to_radians().cos(); + let interior = |i: usize| closed || (i > 0 && i + 1 < n); + let turn: Vec = (0..n) + .map(|i| { + if !interior(i) { + return 1.0; + } + let a = norm(sub(lp[i], walk(lp, i, window, false, closed))); + let b = norm(sub(walk(lp, i, window, true, closed), lp[i])); + dot(a, b) + }) + .collect(); + let step = |j: usize, fwd: bool| -> Option { + match (fwd, closed) { + (true, true) => Some((j + 1) % n), + (false, true) => Some((j + n - 1) % n), + (true, false) => (j + 1 < n).then_some(j + 1), + (false, false) => j.checked_sub(1), + } + }; + let mut out = Vec::new(); + for i in 0..n { + if turn[i] >= cos_thresh { + continue; + } + // The sharpest point within ±window (ties go to the first index). + let mut is_min = true; + for fwd in [true, false] { + let (mut acc, mut j) = (0.0, i); + while is_min && acc < window { + let Some(nx) = step(j, fwd) else { break }; + acc += len(sub(lp[nx], lp[j])); + j = nx; + if j == i { + break; + } + if if fwd { turn[j] < turn[i] } else { turn[j] <= turn[i] } { + is_min = false; + } + } + } + if is_min { + out.push(i); + } + } + out +} + +fn fit_open(lp: &[P], tol: f64, window: f64) -> Vec<[P; 4]> { + let n = lp.len(); + let mut cuts = vec![0]; + cuts.extend(corners(lp, window, false)); + cuts.push(n - 1); + let mut segs = Vec::new(); + for w in cuts.windows(2) { + let (a, b) = (w[0], w[1]); + let run = &lp[a..=b]; + let t1 = norm(sub(walk(run, 0, window, true, false), run[0])); + let t2 = norm(sub(walk(run, run.len() - 1, window, false, false), run[run.len() - 1])); + fit_cubic(run, t1, t2, tol * tol, &mut segs, 0); + } + segs +} + +fn fit_closed(lp: &[P], tol: f64, window: f64) -> Vec<[P; 4]> { + let n = lp.len(); + let cs = corners(lp, window, true); + let mut segs = Vec::new(); + if cs.is_empty() { + // A smooth loop: start at 0 with one tangent across the seam. + let mut pts = lp.to_vec(); + pts.push(lp[0]); + let t = norm(sub(walk(lp, 0, window, true, true), walk(lp, 0, window, false, true))); + fit_cubic(&pts, t, mul(t, -1.0), tol * tol, &mut segs, 0); + return segs; + } + for (k, &c) in cs.iter().enumerate() { + let end = cs[(k + 1) % cs.len()]; + let mut pts = vec![lp[c]]; + let mut j = c; + loop { + j = (j + 1) % n; + pts.push(lp[j]); + if j == end { + break; + } + } + let m = pts.len(); + let t1 = norm(sub(walk(&pts, 0, window, true, false), pts[0])); + let t2 = norm(sub(walk(&pts, m - 1, window, false, false), pts[m - 1])); + fit_cubic(&pts, t1, t2, tol * tol, &mut segs, 0); + } + segs +} + +fn bezier(b: &[P; 4], t: f64) -> P { + let mt = 1.0 - t; + let (a, bb, c, d) = (mt * mt * mt, 3.0 * mt * mt * t, 3.0 * mt * t * t, t * t * t); + (a * b[0].0 + bb * b[1].0 + c * b[2].0 + d * b[3].0, a * b[0].1 + bb * b[1].1 + c * b[2].1 + d * b[3].1) +} + +fn bezier_d1(b: &[P; 4], t: f64) -> P { + let mt = 1.0 - t; + let q0 = mul(sub(b[1], b[0]), 3.0); + let q1 = mul(sub(b[2], b[1]), 3.0); + let q2 = mul(sub(b[3], b[2]), 3.0); + add(add(mul(q0, mt * mt), mul(q1, 2.0 * mt * t)), mul(q2, t * t)) +} + +fn bezier_d2(b: &[P; 4], t: f64) -> P { + let r0 = mul(add(sub(b[2], mul(b[1], 2.0)), b[0]), 6.0); + let r1 = mul(add(sub(b[3], mul(b[2], 2.0)), b[1]), 6.0); + add(mul(r0, 1.0 - t), mul(r1, t)) +} + +fn chord_params(pts: &[P]) -> Vec { + let mut u = vec![0.0; pts.len()]; + for i in 1..pts.len() { + u[i] = u[i - 1] + len(sub(pts[i], pts[i - 1])); + } + let total = u[pts.len() - 1]; + if total > 0.0 { + for v in &mut u { + *v /= total; + } + } + u +} + +/// Least-squares control points with fixed end tangents (`pts.len() >= 2`). +fn generate(pts: &[P], u: &[f64], t1: P, t2: P) -> [P; 4] { + let (p0, p3) = (pts[0], pts[pts.len() - 1]); + let mut c = [[0.0f64; 2]; 2]; + let mut x = [0.0f64; 2]; + for (i, &t) in u.iter().enumerate() { + let mt = 1.0 - t; + let b1 = 3.0 * mt * mt * t; + let b2 = 3.0 * mt * t * t; + let a1 = mul(t1, b1); + let a2 = mul(t2, b2); + c[0][0] += dot(a1, a1); + c[0][1] += dot(a1, a2); + c[1][1] += dot(a2, a2); + let tmp = sub(pts[i], add(mul(p0, mt * mt * mt + b1), mul(p3, b2 + t * t * t))); + x[0] += dot(a1, tmp); + x[1] += dot(a2, tmp); + } + c[1][0] = c[0][1]; + let det = c[0][0] * c[1][1] - c[1][0] * c[0][1]; + let det0 = c[0][0] * x[1] - c[1][0] * x[0]; + let det1 = x[0] * c[1][1] - x[1] * c[0][1]; + let (mut al, mut ar) = if det.abs() > 1e-12 { (det1 / det, det0 / det) } else { (0.0, 0.0) }; + let seg = len(sub(p3, p0)); + // Schneider's fallback when the solve is degenerate or flips a handle. + if al < 1e-6 * seg || ar < 1e-6 * seg { + al = seg / 3.0; + ar = seg / 3.0; + } + [p0, add(p0, mul(t1, al)), add(p3, mul(t2, ar)), p3] +} + +/// Largest squared distance between the points and the curve, and where (`pts.len() >= 3`). +fn max_error(pts: &[P], b: &[P; 4], u: &[f64]) -> (f64, usize) { + let mut best = (0.0, pts.len() / 2); + for i in 1..pts.len() - 1 { + let d = sub(bezier(b, u[i]), pts[i]); + let e = dot(d, d); + if e >= best.0 { + best = (e, i); + } + } + best +} + +/// One Newton step towards each point's nearest parameter on the curve. +fn reparam(pts: &[P], u: &[f64], b: &[P; 4]) -> Vec { + pts.iter() + .zip(u) + .map(|(p, &t)| { + let q = bezier(b, t); + let d1 = bezier_d1(b, t); + let d2 = bezier_d2(b, t); + let num = dot(sub(q, *p), d1); + let den = dot(d1, d1) + dot(sub(q, *p), d2); + if den.abs() < 1e-12 { t } else { (t - num / den).clamp(0.0, 1.0) } + }) + .collect() +} + +/// Fits `pts` (at least two) and appends the segments to `out`. Each split shortens both +/// halves, so recursion ends; `depth` caps it anyway. +fn fit_cubic(pts: &[P], t1: P, t2: P, err2: f64, out: &mut Vec<[P; 4]>, depth: u32) { + let n = pts.len(); + if n < 2 { + return; + } + if n == 2 || depth > 40 { + let d = len(sub(pts[n - 1], pts[0])) / 3.0; + out.push([pts[0], add(pts[0], mul(t1, d)), add(pts[n - 1], mul(t2, d)), pts[n - 1]]); + return; + } + let mut u = chord_params(pts); + let mut b = generate(pts, &u, t1, t2); + let (mut e, mut split) = max_error(pts, &b, &u); + if e < err2 { + out.push(b); + return; + } + if e < err2 * 16.0 { + for _ in 0..6 { + u = reparam(pts, &u, &b); + b = generate(pts, &u, t1, t2); + (e, split) = max_error(pts, &b, &u); + if e < err2 { + out.push(b); + return; + } + } + } + let split = split.clamp(1, n - 2); + let tc = norm(sub(pts[split - 1], pts[split + 1])); + let tc = if len(tc) < 0.5 { norm(sub(pts[split - 1], pts[split])) } else { tc }; + fit_cubic(&pts[..=split], t1, tc, err2, out, depth + 1); + fit_cubic(&pts[split..], mul(tc, -1.0), t2, err2, out, depth + 1); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Affine, PathCmd}; + + fn max_dist(path: &Path, pts: &[Vec2]) -> f32 { + let lines = path.flatten(&Affine::IDENTITY, 0.05); + pts.iter() + .map(|p| { + lines + .iter() + .flat_map(|l| l.points.windows(2).map(|w| crate::path::segment_distance(*p, w[0], w[1]))) + .fold(f32::INFINITY, f32::min) + }) + .fold(0.0, f32::max) + } + + #[test] + fn smooth_wave_fits_within_tolerance_with_few_segments() { + let wave: Vec = (0..=300).map(|i| Vec2::new(i as f32, (i as f32 * 0.04).sin() * 40.0)).collect(); + let path = fit_curve(&wave, 1.0, 3.0, false); + let segs = path.cmds.iter().filter(|c| matches!(c, PathCmd::CubicTo(..))).count(); + assert!((1..=12).contains(&segs), "{segs} segments"); + assert!(max_dist(&path, &wave) <= 1.05, "{}", max_dist(&path, &wave)); + assert_eq!(path.point(0, crate::edit::ANCHOR), Some(wave[0]), "starts where the stroke starts"); + } + + #[test] + fn corners_stay_sharp() { + // An "L": down then right, sampled every pixel. + let mut pts: Vec = (0..=50).map(|i| Vec2::new(0.0, i as f32)).collect(); + pts.extend((1..=50).map(|i| Vec2::new(i as f32, 50.0))); + let path = fit_curve(&pts, 0.5, 3.0, false); + assert!(path.anchors().iter().any(|(_, a)| a.distance(Vec2::new(0.0, 50.0)) < 1e-3), "an anchor at the corner"); + assert!(max_dist(&path, &pts) <= 0.55); + } + + #[test] + fn closed_loop_and_degenerate_input() { + let circle: Vec = (0..120).map(|i| { + let a = i as f32 / 120.0 * std::f32::consts::TAU; + Vec2::new(50.0 + 30.0 * a.cos(), 50.0 + 30.0 * a.sin()) + }).collect(); + let path = fit_curve(&circle, 0.5, 3.0, true); + assert!(matches!(path.cmds.last(), Some(PathCmd::Close))); + assert!(max_dist(&path, &circle) <= 0.55); + // Repeated, non-finite and tiny inputs never panic. + let same = vec![Vec2::new(1.0, 1.0); 20]; + assert_eq!(fit_curve(&same, 1.0, 3.0, false).cmds.len(), 1); + assert!(fit_curve(&[], 1.0, 3.0, true).is_empty()); + let odd = [Vec2::new(0.0, 0.0), Vec2::new(f32::NAN, 1.0), Vec2::new(5.0, 0.0), Vec2::new(5.0, 0.0)]; + assert_eq!(fit_curve(&odd, f32::NAN, -1.0, false).cmds.len(), 2); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs new file mode 100644 index 00000000..bb06a25f --- /dev/null +++ b/crates/geom/src/lib.rs @@ -0,0 +1,182 @@ +//! AniCraft geometry (layer L0): points, affine transforms, rectangles and Bézier paths. +//! +//! Everything here is pure math with no allocation beyond the path buffers, deterministic +//! across platforms (plain `f32`, no fused ops that depend on the target). +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod affine; +pub mod edit; +mod fit; +mod path; +pub mod svg; +pub mod trace; + +pub use affine::{Affine, Decomposed}; +pub use fit::fit_curve; +pub use path::{FillRule, Path, PathCmd, Polyline}; + +use serde::{Deserialize, Serialize}; +use std::ops::{Add, Mul, Neg, Sub}; + +/// A 2D point or vector. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Vec2 { + pub x: f32, + pub y: f32, +} + +impl Vec2 { + pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 }; + + pub const fn new(x: f32, y: f32) -> Self { + Self { x, y } + } + pub fn dot(self, o: Vec2) -> f32 { + self.x * o.x + self.y * o.y + } + pub fn cross(self, o: Vec2) -> f32 { + self.x * o.y - self.y * o.x + } + pub fn length(self) -> f32 { + self.dot(self).sqrt() + } + pub fn normalized(self) -> Vec2 { + let l = self.length(); + if l > 1e-12 { self * (1.0 / l) } else { Vec2::ZERO } + } + /// Perpendicular (rotated +90° in y-down screen space). + pub fn perp(self) -> Vec2 { + Vec2::new(-self.y, self.x) + } + pub fn lerp(self, o: Vec2, t: f32) -> Vec2 { + self + (o - self) * t + } + pub fn distance(self, o: Vec2) -> f32 { + (o - self).length() + } + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } +} + +impl Add for Vec2 { + type Output = Vec2; + fn add(self, o: Vec2) -> Vec2 { + Vec2::new(self.x + o.x, self.y + o.y) + } +} +impl Sub for Vec2 { + type Output = Vec2; + fn sub(self, o: Vec2) -> Vec2 { + Vec2::new(self.x - o.x, self.y - o.y) + } +} +impl Mul for Vec2 { + type Output = Vec2; + fn mul(self, s: f32) -> Vec2 { + Vec2::new(self.x * s, self.y * s) + } +} +impl Neg for Vec2 { + type Output = Vec2; + fn neg(self) -> Vec2 { + Vec2::new(-self.x, -self.y) + } +} + +/// Axis-aligned rectangle (min inclusive, max exclusive in raster use). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Rect { + pub min: Vec2, + pub max: Vec2, +} + +impl Rect { + /// The empty rectangle: union identity. + pub const EMPTY: Rect = Rect { + min: Vec2 { x: f32::INFINITY, y: f32::INFINITY }, + max: Vec2 { x: f32::NEG_INFINITY, y: f32::NEG_INFINITY }, + }; + + pub fn new(x0: f32, y0: f32, x1: f32, y1: f32) -> Self { + Rect { min: Vec2::new(x0.min(x1), y0.min(y1)), max: Vec2::new(x0.max(x1), y0.max(y1)) } + } + pub fn from_points(a: Vec2, b: Vec2) -> Self { + Rect::new(a.x, a.y, b.x, b.y) + } + pub fn is_empty(&self) -> bool { + !(self.max.x > self.min.x && self.max.y > self.min.y) + } + pub fn width(&self) -> f32 { + (self.max.x - self.min.x).max(0.0) + } + pub fn height(&self) -> f32 { + (self.max.y - self.min.y).max(0.0) + } + pub fn center(&self) -> Vec2 { + (self.min + self.max) * 0.5 + } + pub fn include(&mut self, p: Vec2) { + self.min.x = self.min.x.min(p.x); + self.min.y = self.min.y.min(p.y); + self.max.x = self.max.x.max(p.x); + self.max.y = self.max.y.max(p.y); + } + pub fn union(&self, o: &Rect) -> Rect { + Rect { + min: Vec2::new(self.min.x.min(o.min.x), self.min.y.min(o.min.y)), + max: Vec2::new(self.max.x.max(o.max.x), self.max.y.max(o.max.y)), + } + } + pub fn intersect(&self, o: &Rect) -> Rect { + Rect { + min: Vec2::new(self.min.x.max(o.min.x), self.min.y.max(o.min.y)), + max: Vec2::new(self.max.x.min(o.max.x), self.max.y.min(o.max.y)), + } + } + pub fn inflate(&self, d: f32) -> Rect { + Rect { min: self.min - Vec2::new(d, d), max: self.max + Vec2::new(d, d) } + } + pub fn contains(&self, p: Vec2) -> bool { + p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y + } + /// Bounds of this rectangle after a transform. + pub fn transformed(&self, m: &Affine) -> Rect { + if self.is_empty() { + return *self; + } + let mut r = Rect::EMPTY; + for p in [self.min, Vec2::new(self.max.x, self.min.y), self.max, Vec2::new(self.min.x, self.max.y)] { + r.include(m.apply(p)); + } + r + } +} + +/// Linear interpolation of scalars. +pub fn lerp(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rect_union_and_intersect() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(5.0, 5.0, 20.0, 20.0); + assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 20.0, 20.0)); + assert_eq!(a.intersect(&b), Rect::new(5.0, 5.0, 10.0, 10.0)); + assert!(Rect::EMPTY.is_empty()); + assert_eq!(Rect::EMPTY.union(&a), a); + } + + #[test] + fn vec_ops() { + let v = Vec2::new(3.0, 4.0); + assert_eq!(v.length(), 5.0); + assert_eq!(v.perp().dot(v), 0.0); + assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO); + } +} diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs new file mode 100644 index 00000000..5c29dd2f --- /dev/null +++ b/crates/geom/src/path.rs @@ -0,0 +1,577 @@ +//! Bézier paths, adaptive flattening (Wang's formula) and winding-number hit testing. + +use crate::{Affine, Rect, Vec2}; +use serde::{Deserialize, Serialize}; + +/// Fill rule for closed regions. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum FillRule { + #[default] + NonZero, + EvenOdd, +} + +/// One path command. Coordinates are in the element's local space. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub enum PathCmd { + MoveTo(Vec2), + LineTo(Vec2), + QuadTo(Vec2, Vec2), + CubicTo(Vec2, Vec2, Vec2), + Close, +} + +/// A sequence of subpaths. +/// +/// Serialized as compact SVG path data (`"M0 0L10 0Q5 5 0 10Z"`, absolute commands only), which +/// is about four times smaller than a tagged JSON list and readable by people and tools. The +/// legacy `{"cmds": [...]}` form is still accepted when reading. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Path { + pub cmds: Vec, +} + +/// Largest path accepted from a file. +pub const MAX_PATH_CMDS: usize = 4_000_000; + +impl Path { + /// SVG path data with shortest round-trip number formatting. + pub fn to_svg(&self) -> String { + use std::fmt::Write; + let mut s = String::with_capacity(self.cmds.len() * 16); + let pt = |s: &mut String, p: Vec2| { + let _ = write!(s, "{} {}", p.x, p.y); + }; + for c in &self.cmds { + match *c { + PathCmd::MoveTo(p) => { + s.push('M'); + pt(&mut s, p); + } + PathCmd::LineTo(p) => { + s.push('L'); + pt(&mut s, p); + } + PathCmd::QuadTo(a, p) => { + s.push('Q'); + pt(&mut s, a); + s.push(' '); + pt(&mut s, p); + } + PathCmd::CubicTo(a, b, p) => { + s.push('C'); + pt(&mut s, a); + s.push(' '); + pt(&mut s, b); + s.push(' '); + pt(&mut s, p); + } + PathCmd::Close => s.push('Z'), + } + } + s + } + + /// Parses the absolute-command subset written by [`Path::to_svg`] (M, L, Q, C, Z; numbers + /// separated by spaces or commas). Never panics; rejects non-finite numbers. + pub fn from_svg(src: &str) -> Result { + let mut cmds = Vec::new(); + let mut it = src.char_indices().peekable(); + let mut nums: Vec = Vec::with_capacity(6); + let mut cur: Option = None; + let flush = |cur: Option, nums: &mut Vec, cmds: &mut Vec| -> Result<(), String> { + let Some(c) = cur else { + return if nums.is_empty() { Ok(()) } else { Err("number before the first command".into()) }; + }; + let need = match c { + 'M' | 'L' => 2, + 'Q' => 4, + 'C' => 6, + _ => 0, + }; + if c == 'Z' { + if !nums.is_empty() { + return Err("Z takes no numbers".into()); + } + cmds.push(PathCmd::Close); + return Ok(()); + } + if nums.is_empty() || !nums.len().is_multiple_of(need) { + return Err(format!("{c} needs a multiple of {need} numbers, got {}", nums.len())); + } + for g in nums.chunks(need) { + let v = |i: usize| Vec2::new(g[i], g[i + 1]); + cmds.push(match c { + 'M' => PathCmd::MoveTo(v(0)), + 'L' => PathCmd::LineTo(v(0)), + 'Q' => PathCmd::QuadTo(v(0), v(2)), + _ => PathCmd::CubicTo(v(0), v(2), v(4)), + }); + } + nums.clear(); + if cmds.len() > MAX_PATH_CMDS { + return Err(format!("path has more than {MAX_PATH_CMDS} commands")); + } + Ok(()) + }; + while let Some(&(i, ch)) = it.peek() { + match ch { + 'M' | 'L' | 'Q' | 'C' | 'Z' | 'z' => { + flush(cur, &mut nums, &mut cmds)?; + cur = Some(ch.to_ascii_uppercase()); + it.next(); + } + ' ' | ',' | '\n' | '\t' | '\r' => { + it.next(); + } + '-' | '+' | '.' | '0'..='9' => { + let start = i; + let mut end = i + ch.len_utf8(); + it.next(); + while let Some(&(j, c2)) = it.peek() { + let exp_sign = (c2 == '-' || c2 == '+') && matches!(src.get(..j).and_then(|s| s.chars().last()), Some('e' | 'E')); + if c2.is_ascii_digit() || c2 == '.' || c2 == 'e' || c2 == 'E' || exp_sign { + end = j + c2.len_utf8(); + it.next(); + } else { + break; + } + } + let tok = src.get(start..end).unwrap_or(""); + let v: f32 = tok.parse().map_err(|_| format!("bad number '{tok}'"))?; + if !v.is_finite() { + return Err(format!("number '{tok}' is not finite")); + } + nums.push(v); + if nums.len() > 6 { + // repeated implicit commands: emit as we go to bound memory + let c = cur.ok_or("number before the first command")?; + let need = match c { + 'M' | 'L' => 2, + 'Q' => 4, + 'C' => 6, + _ => return Err("Z takes no numbers".into()), + }; + if nums.len().is_multiple_of(need) { + flush(cur, &mut nums, &mut cmds)?; + } + } + } + other => return Err(format!("unexpected character '{other}' in path data")), + } + } + flush(cur, &mut nums, &mut cmds)?; + Ok(Path { cmds }) + } +} + +impl Serialize for Path { + fn serialize(&self, s: S) -> Result { + s.serialize_str(&self.to_svg()) + } +} + +impl<'de> Deserialize<'de> for Path { + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Repr { + Svg(String), + Legacy { cmds: Vec }, + } + match Repr::deserialize(d)? { + Repr::Svg(s) => Path::from_svg(&s).map_err(serde::de::Error::custom), + Repr::Legacy { cmds } => { + if cmds.len() > MAX_PATH_CMDS { + return Err(serde::de::Error::custom("path is too long")); + } + Ok(Path { cmds }) + } + } + } +} + +/// A flattened subpath. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Polyline { + pub points: Vec, + pub closed: bool, +} + +/// Hard cap on segments per curve, so a hostile curve cannot allocate unboundedly. +const MAX_SEGMENTS_PER_CURVE: usize = 1024; +/// Bézier circle constant. +const KAPPA: f32 = 0.552_284_8; + +impl Path { + pub fn new() -> Self { + Self::default() + } + pub fn move_to(&mut self, p: Vec2) -> &mut Self { + self.cmds.push(PathCmd::MoveTo(p)); + self + } + pub fn line_to(&mut self, p: Vec2) -> &mut Self { + self.cmds.push(PathCmd::LineTo(p)); + self + } + pub fn quad_to(&mut self, c: Vec2, p: Vec2) -> &mut Self { + self.cmds.push(PathCmd::QuadTo(c, p)); + self + } + pub fn cubic_to(&mut self, c1: Vec2, c2: Vec2, p: Vec2) -> &mut Self { + self.cmds.push(PathCmd::CubicTo(c1, c2, p)); + self + } + pub fn close(&mut self) -> &mut Self { + self.cmds.push(PathCmd::Close); + self + } + + /// Axis-aligned rectangle, clockwise on a y-down screen. + pub fn rect(x: f32, y: f32, w: f32, h: f32) -> Path { + let mut p = Path::new(); + p.move_to(Vec2::new(x, y)) + .line_to(Vec2::new(x + w, y)) + .line_to(Vec2::new(x + w, y + h)) + .line_to(Vec2::new(x, y + h)) + .close(); + p + } + + /// Rectangle with rounded corners (radius clamped to half the shorter side). + pub fn rounded_rect(x: f32, y: f32, w: f32, h: f32, r: f32) -> Path { + let r = r.max(0.0).min(w.abs() * 0.5).min(h.abs() * 0.5); + if r <= 0.0 { + return Path::rect(x, y, w, h); + } + let k = r * (1.0 - KAPPA); + let (x1, y1) = (x + w, y + h); + let mut p = Path::new(); + p.move_to(Vec2::new(x + r, y)) + .line_to(Vec2::new(x1 - r, y)) + .cubic_to(Vec2::new(x1 - k, y), Vec2::new(x1, y + k), Vec2::new(x1, y + r)) + .line_to(Vec2::new(x1, y1 - r)) + .cubic_to(Vec2::new(x1, y1 - k), Vec2::new(x1 - k, y1), Vec2::new(x1 - r, y1)) + .line_to(Vec2::new(x + r, y1)) + .cubic_to(Vec2::new(x + k, y1), Vec2::new(x, y1 - k), Vec2::new(x, y1 - r)) + .line_to(Vec2::new(x, y + r)) + .cubic_to(Vec2::new(x, y + k), Vec2::new(x + k, y), Vec2::new(x + r, y)) + .close(); + p + } + + /// Ellipse centred at `(cx, cy)` built from four cubic arcs. + pub fn ellipse(cx: f32, cy: f32, rx: f32, ry: f32) -> Path { + let (kx, ky) = (rx * KAPPA, ry * KAPPA); + let mut p = Path::new(); + p.move_to(Vec2::new(cx + rx, cy)) + .cubic_to(Vec2::new(cx + rx, cy + ky), Vec2::new(cx + kx, cy + ry), Vec2::new(cx, cy + ry)) + .cubic_to(Vec2::new(cx - kx, cy + ry), Vec2::new(cx - rx, cy + ky), Vec2::new(cx - rx, cy)) + .cubic_to(Vec2::new(cx - rx, cy - ky), Vec2::new(cx - kx, cy - ry), Vec2::new(cx, cy - ry)) + .cubic_to(Vec2::new(cx + kx, cy - ry), Vec2::new(cx + rx, cy - ky), Vec2::new(cx + rx, cy)) + .close(); + p + } + + /// Star (or polygon when `inner == outer`) with `points` tips, first tip pointing up. + pub fn star(cx: f32, cy: f32, outer: f32, inner: f32, points: u32) -> Path { + let n = points.clamp(3, 256) as usize; + let mut p = Path::new(); + for i in 0..n * 2 { + let r = if i % 2 == 0 { outer } else { inner }; + let a = -std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::PI / n as f32; + let v = Vec2::new(cx + r * a.cos(), cy + r * a.sin()); + if i == 0 { + p.move_to(v); + } else { + p.line_to(v); + } + } + p.close(); + p + } + + /// Open two-point line. + pub fn line(a: Vec2, b: Vec2) -> Path { + let mut p = Path::new(); + p.move_to(a).line_to(b); + p + } + + pub fn is_empty(&self) -> bool { + self.cmds.is_empty() + } + + /// Control-point bounds (a superset of the exact curve bounds). + pub fn bounds(&self) -> Rect { + let mut r = Rect::EMPTY; + for c in &self.cmds { + match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => r.include(p), + PathCmd::QuadTo(a, p) => { + r.include(a); + r.include(p); + } + PathCmd::CubicTo(a, b, p) => { + r.include(a); + r.include(b); + r.include(p); + } + PathCmd::Close => {} + } + } + r + } + + /// Path with every point transformed. + pub fn transformed(&self, m: &Affine) -> Path { + let t = |p: Vec2| m.apply(p); + Path { + cmds: self + .cmds + .iter() + .map(|c| match *c { + PathCmd::MoveTo(p) => PathCmd::MoveTo(t(p)), + PathCmd::LineTo(p) => PathCmd::LineTo(t(p)), + PathCmd::QuadTo(a, p) => PathCmd::QuadTo(t(a), t(p)), + PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(t(a), t(b), t(p)), + PathCmd::Close => PathCmd::Close, + }) + .collect(), + } + } + + /// Point-wise interpolation for shape tweens. `None` when the command structures differ. + pub fn lerp(&self, o: &Path, t: f32) -> Option { + if self.cmds.len() != o.cmds.len() { + return None; + } + let l = |a: Vec2, b: Vec2| a.lerp(b, t); + let mut cmds = Vec::with_capacity(self.cmds.len()); + for (a, b) in self.cmds.iter().zip(&o.cmds) { + cmds.push(match (*a, *b) { + (PathCmd::MoveTo(p), PathCmd::MoveTo(q)) => PathCmd::MoveTo(l(p, q)), + (PathCmd::LineTo(p), PathCmd::LineTo(q)) => PathCmd::LineTo(l(p, q)), + (PathCmd::QuadTo(p1, p), PathCmd::QuadTo(q1, q)) => PathCmd::QuadTo(l(p1, q1), l(p, q)), + (PathCmd::CubicTo(p1, p2, p), PathCmd::CubicTo(q1, q2, q)) => PathCmd::CubicTo(l(p1, q1), l(p2, q2), l(p, q)), + (PathCmd::Close, PathCmd::Close) => PathCmd::Close, + _ => return None, + }); + } + Some(Path { cmds }) + } + + /// Flattens under `m` into polylines whose deviation from the true curve is at most + /// `tolerance` (in output units). Non-finite points are dropped. + pub fn flatten(&self, m: &Affine, tolerance: f32) -> Vec { + let tol = if tolerance.is_finite() && tolerance > 1e-4 { tolerance } else { 0.1 }; + let mut out: Vec = Vec::new(); + let mut cur = Polyline::default(); + let mut start = Vec2::ZERO; + let mut last = Vec2::ZERO; + let flush = |cur: &mut Polyline, out: &mut Vec| { + if cur.points.len() >= 2 { + out.push(std::mem::take(cur)); + } else { + cur.points.clear(); + cur.closed = false; + } + }; + for c in &self.cmds { + match *c { + PathCmd::MoveTo(p) => { + flush(&mut cur, &mut out); + let p = m.apply(p); + start = p; + last = p; + push_finite(&mut cur.points, p); + } + PathCmd::LineTo(p) => { + let p = m.apply(p); + if cur.points.is_empty() { + push_finite(&mut cur.points, last); + } + push_finite(&mut cur.points, p); + last = p; + } + PathCmd::QuadTo(c1, p) => { + let (c1, p) = (m.apply(c1), m.apply(p)); + if cur.points.is_empty() { + push_finite(&mut cur.points, last); + } + let dd = (last - c1 * 2.0 + p).length(); + let n = segments(0.25 * dd, tol); + for i in 1..=n { + let t = i as f32 / n as f32; + let mt = 1.0 - t; + let q = last * (mt * mt) + c1 * (2.0 * mt * t) + p * (t * t); + push_finite(&mut cur.points, q); + } + last = p; + } + PathCmd::CubicTo(c1, c2, p) => { + let (c1, c2, p) = (m.apply(c1), m.apply(c2), m.apply(p)); + if cur.points.is_empty() { + push_finite(&mut cur.points, last); + } + let dd = (last - c1 * 2.0 + c2).length().max((c1 - c2 * 2.0 + p).length()); + let n = segments(0.75 * dd, tol); + for i in 1..=n { + let t = i as f32 / n as f32; + let mt = 1.0 - t; + let q = last * (mt * mt * mt) + c1 * (3.0 * mt * mt * t) + c2 * (3.0 * mt * t * t) + p * (t * t * t); + push_finite(&mut cur.points, q); + } + last = p; + } + PathCmd::Close => { + cur.closed = true; + flush(&mut cur, &mut out); + last = start; + } + } + } + flush(&mut cur, &mut out); + out + } + + /// Whether `p` (in the same space as `m`'s output) is inside the filled path. + pub fn contains(&self, p: Vec2, m: &Affine, rule: FillRule) -> bool { + let mut winding = 0i32; + for pl in self.flatten(m, 0.25) { + let pts = &pl.points; + let n = pts.len(); + for i in 0..n { + let a = pts[i]; + let b = pts[(i + 1) % n]; + if a.y <= p.y { + if b.y > p.y && (b - a).cross(p - a) > 0.0 { + winding += 1; + } + } else if b.y <= p.y && (b - a).cross(p - a) < 0.0 { + winding -= 1; + } + } + } + match rule { + FillRule::NonZero => winding != 0, + FillRule::EvenOdd => winding % 2 != 0, + } + } + + /// Distance from `p` to the nearest flattened edge (for stroke hit testing). + pub fn distance_to_edge(&self, p: Vec2, m: &Affine) -> f32 { + let mut best = f32::INFINITY; + for pl in self.flatten(m, 0.25) { + let n = pl.points.len(); + let segs = if pl.closed { n } else { n.saturating_sub(1) }; + for i in 0..segs { + let a = pl.points[i]; + let b = pl.points[(i + 1) % n]; + best = best.min(segment_distance(p, a, b)); + } + } + best + } +} + +fn push_finite(v: &mut Vec, p: Vec2) { + if p.is_finite() { + v.push(p); + } +} + +fn segments(scaled_dd: f32, tol: f32) -> usize { + let n = (scaled_dd / tol).sqrt().ceil(); + if n.is_finite() && n >= 1.0 { (n as usize).min(MAX_SEGMENTS_PER_CURVE) } else { 1 } +} + +/// Distance from point `p` to segment `ab`. +pub fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 { + let ab = b - a; + let len2 = ab.dot(ab); + let t = if len2 > 1e-12 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(a + ab * t) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flatten_rect_is_closed_polygon() { + let pls = Path::rect(0.0, 0.0, 10.0, 5.0).flatten(&Affine::IDENTITY, 0.1); + assert_eq!(pls.len(), 1); + assert!(pls[0].closed); + assert_eq!(pls[0].points.len(), 4); + } + + #[test] + fn ellipse_flatten_within_tolerance() { + let r = 100.0; + let pls = Path::ellipse(0.0, 0.0, r, r).flatten(&Affine::IDENTITY, 0.1); + for p in &pls[0].points { + assert!((p.length() - r).abs() < 0.2, "{}", p.length()); + } + // tighter tolerance yields more points + let fine = Path::ellipse(0.0, 0.0, r, r).flatten(&Affine::IDENTITY, 0.01); + assert!(fine[0].points.len() > pls[0].points.len()); + } + + #[test] + fn contains_respects_fill_rule() { + let mut p = Path::rect(0.0, 0.0, 10.0, 10.0); + p.cmds.extend(Path::rect(2.0, 2.0, 6.0, 6.0).cmds); // same winding → hole only with even-odd + let c = Vec2::new(5.0, 5.0); + assert!(p.contains(c, &Affine::IDENTITY, FillRule::NonZero)); + assert!(!p.contains(c, &Affine::IDENTITY, FillRule::EvenOdd)); + assert!(!p.contains(Vec2::new(11.0, 5.0), &Affine::IDENTITY, FillRule::NonZero)); + } + + #[test] + fn hostile_curves_are_bounded() { + let mut p = Path::new(); + p.move_to(Vec2::ZERO).cubic_to(Vec2::new(1e30, 0.0), Vec2::new(f32::NAN, 1.0), Vec2::new(1.0, 1.0)); + let pls = p.flatten(&Affine::IDENTITY, 0.1); + assert!(pls.iter().all(|pl| pl.points.len() <= MAX_SEGMENTS_PER_CURVE + 1)); + } + + #[test] + fn svg_round_trip_is_exact() { + let mut p = Path::rounded_rect(-1.5, 2.25, 100.0, 33.333, 7.0); + p.cmds.extend(Path::star(1e-7, -3e5, 12.0, 5.0, 7).cmds); + p.quad_to(Vec2::new(0.1, 0.2), Vec2::new(1.0 / 3.0, -0.0)); + let s = p.to_svg(); + assert_eq!(Path::from_svg(&s).unwrap(), p); + assert!(s.starts_with('M')); + } + + #[test] + fn svg_parser_rejects_garbage_without_panicking() { + for bad in ["L", "M 1", "Z 3", "12 M", "M1 2 x", "M nan 1", "M 1e99 1", "M1 2L", "C1 2 3 4 5"] { + assert!(Path::from_svg(bad).is_err(), "{bad}"); + } + assert_eq!(Path::from_svg("").unwrap(), Path::new()); + assert_eq!(Path::from_svg("M1,2 L3,4 5,6 z").unwrap().cmds.len(), 4); + assert_eq!(Path::from_svg("M1e-3 2E+2").unwrap().cmds[0], PathCmd::MoveTo(Vec2::new(1e-3, 200.0))); + } + + #[test] + fn legacy_json_paths_still_load() { + let legacy = r#"{"cmds":[{"MoveTo":{"x":1.0,"y":2.0}},{"LineTo":{"x":3.0,"y":4.0}},"Close"]}"#; + let p: Path = serde_json::from_str(legacy).unwrap(); + assert_eq!(p.cmds.len(), 3); + let s = serde_json::to_string(&p).unwrap(); + assert_eq!(s, "\"M1 2L3 4Z\""); + } + + #[test] + fn lerp_requires_matching_structure() { + let a = Path::rect(0.0, 0.0, 10.0, 10.0); + let b = Path::rect(10.0, 10.0, 20.0, 20.0); + let m = a.lerp(&b, 0.5).unwrap(); + assert_eq!(m.bounds(), Rect::new(5.0, 5.0, 20.0, 20.0)); + assert!(a.lerp(&Path::ellipse(0.0, 0.0, 1.0, 1.0), 0.5).is_none()); + } +} diff --git a/crates/geom/src/svg.rs b/crates/geom/src/svg.rs new file mode 100644 index 00000000..505d13d5 --- /dev/null +++ b/crates/geom/src/svg.rs @@ -0,0 +1,302 @@ +//! Full SVG path data (SVG 1.1 §8.3 / SVG 2 "paths"): every command in absolute and relative +//! form (M L H V C S Q T A Z), implicit repeats, packed numbers and arc flags. +//! +//! [`crate::Path::from_svg`] stays the strict parser for AniCraft's own file format; this one +//! reads SVG written by other tools (icon sets now, SVG import later). Elliptical arcs become +//! cubic Béziers using the endpoint-to-centre conversion of the SVG implementation notes +//! (W3C SVG 1.1 Appendix F.6, Royalty-Free Patent Policy), at most a quarter turn per cubic. +//! Never panics; non-finite numbers and oversized paths are errors. + +use crate::path::MAX_PATH_CMDS; +use crate::{Path, Vec2}; + +struct Cursor<'a> { + s: &'a [u8], + i: usize, +} + +impl Cursor<'_> { + fn skip(&mut self) { + while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace() || *c == b',') { + self.i += 1; + } + } + fn letter(&mut self) -> Option { + self.skip(); + self.s.get(self.i).copied().filter(u8::is_ascii_alphabetic).filter(|c| !matches!(c, b'e' | b'E')) + } + fn number(&mut self) -> Result { + self.skip(); + let start = self.i; + let at = |i: usize| self.s.get(i).copied(); + let mut i = self.i; + if matches!(at(i), Some(b'+' | b'-')) { + i += 1; + } + let mut digits = false; + while at(i).is_some_and(|c| c.is_ascii_digit()) { + i += 1; + digits = true; + } + if at(i) == Some(b'.') { + i += 1; + while at(i).is_some_and(|c| c.is_ascii_digit()) { + i += 1; + digits = true; + } + } + if !digits { + return Err(format!("expected a number at byte {start}")); + } + if matches!(at(i), Some(b'e' | b'E')) { + let mut j = i + 1; + if matches!(at(j), Some(b'+' | b'-')) { + j += 1; + } + if at(j).is_some_and(|c| c.is_ascii_digit()) { + while at(j).is_some_and(|c| c.is_ascii_digit()) { + j += 1; + } + i = j; + } + } + let tok = std::str::from_utf8(self.s.get(start..i).unwrap_or_default()).unwrap_or(""); + let v: f64 = tok.parse().map_err(|_| format!("bad number '{tok}'"))?; + if !v.is_finite() { + return Err(format!("number '{tok}' is not finite")); + } + self.i = i; + Ok(v) + } + /// An arc flag: a single `0` or `1`, which may be packed against the next number. + fn flag(&mut self) -> Result { + self.skip(); + match self.s.get(self.i) { + Some(b'0') => { + self.i += 1; + Ok(false) + } + Some(b'1') => { + self.i += 1; + Ok(true) + } + _ => Err(format!("expected an arc flag (0 or 1) at byte {}", self.i)), + } + } + fn done(&mut self) -> bool { + self.skip(); + self.i >= self.s.len() + } +} + +#[derive(Clone, Copy)] +struct P(f64, f64); + +impl P { + fn v(self) -> Vec2 { + Vec2::new(self.0 as f32, self.1 as f32) + } +} + +/// Parses SVG path data (`d` attribute) into a [`Path`]. +pub fn parse_path_data(d: &str) -> Result { + let mut c = Cursor { s: d.as_bytes(), i: 0 }; + let mut path = Path::new(); + let (mut cur, mut start) = (P(0.0, 0.0), P(0.0, 0.0)); + // The last control point of a C/S (for S) or Q/T (for T), for reflection. + let (mut last_cubic, mut last_quad): (Option

, Option

) = (None, None); + let mut cmd: Option = None; + while !c.done() { + if let Some(l) = c.letter() { + c.i += 1; + cmd = Some(l); + } + let Some(k) = cmd else { return Err("path data must start with a command".into()) }; + let rel = k.is_ascii_lowercase(); + let off = |p: P, cur: P| if rel { P(p.0 + cur.0, p.1 + cur.1) } else { p }; + let pt = |c: &mut Cursor| -> Result { Ok(P(c.number()?, c.number()?)) }; + let (mut nc, mut nq) = (None, None); + match k.to_ascii_uppercase() { + b'M' => { + let p = off(pt(&mut c)?, cur); + path.move_to(p.v()); + cur = p; + start = p; + // Further pairs after a moveto are linetos. + cmd = Some(if rel { b'l' } else { b'L' }); + } + b'L' => { + cur = off(pt(&mut c)?, cur); + path.line_to(cur.v()); + } + b'H' => { + let x = c.number()?; + cur = P(if rel { cur.0 + x } else { x }, cur.1); + path.line_to(cur.v()); + } + b'V' => { + let y = c.number()?; + cur = P(cur.0, if rel { cur.1 + y } else { y }); + path.line_to(cur.v()); + } + b'C' => { + let (c1, c2, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur), off(pt(&mut c)?, cur)); + path.cubic_to(c1.v(), c2.v(), p.v()); + nc = Some(c2); + cur = p; + } + b'S' => { + let c1 = last_cubic.map_or(cur, |l| P(2.0 * cur.0 - l.0, 2.0 * cur.1 - l.1)); + let (c2, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur)); + path.cubic_to(c1.v(), c2.v(), p.v()); + nc = Some(c2); + cur = p; + } + b'Q' => { + let (q, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur)); + path.quad_to(q.v(), p.v()); + nq = Some(q); + cur = p; + } + b'T' => { + let q = last_quad.map_or(cur, |l| P(2.0 * cur.0 - l.0, 2.0 * cur.1 - l.1)); + let p = off(pt(&mut c)?, cur); + path.quad_to(q.v(), p.v()); + nq = Some(q); + cur = p; + } + b'A' => { + let (rx, ry, rot) = (c.number()?, c.number()?, c.number()?); + let (large, sweep) = (c.flag()?, c.flag()?); + let p = off(pt(&mut c)?, cur); + arc_to(&mut path, cur, rx, ry, rot, large, sweep, p); + cur = p; + } + b'Z' => { + path.close(); + cur = start; + // Numbers may not follow Z without a new command. + cmd = None; + } + other => return Err(format!("unknown path command '{}'", other as char)), + } + last_cubic = nc; + last_quad = nq; + if path.cmds.len() > MAX_PATH_CMDS { + return Err(format!("path has more than {MAX_PATH_CMDS} commands")); + } + } + Ok(path) +} + +/// Appends the SVG elliptical arc from `p0` to `p1` as cubics (F.6.5 / F.6.6). +#[allow(clippy::too_many_arguments)] +fn arc_to(path: &mut Path, p0: P, rx: f64, ry: f64, rot_deg: f64, large: bool, sweep: bool, p1: P) { + if (p0.0 - p1.0).abs() < 1e-12 && (p0.1 - p1.1).abs() < 1e-12 { + return; + } + let (mut rx, mut ry) = (rx.abs(), ry.abs()); + if rx < 1e-12 || ry < 1e-12 { + path.line_to(p1.v()); + return; + } + let (sin, cos) = rot_deg.to_radians().sin_cos(); + let (dx, dy) = ((p0.0 - p1.0) * 0.5, (p0.1 - p1.1) * 0.5); + let (x1, y1) = (cos * dx + sin * dy, -sin * dx + cos * dy); + // Radii too small to reach: scale them up (F.6.6). + let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); + if lambda > 1.0 { + let s = lambda.sqrt(); + rx *= s; + ry *= s; + } + let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1; + let den = rx * rx * y1 * y1 + ry * ry * x1 * x1; + let mut coef = if den > 0.0 { (num / den).max(0.0).sqrt() } else { 0.0 }; + if large == sweep { + coef = -coef; + } + let (cxp, cyp) = (coef * rx * y1 / ry, -coef * ry * x1 / rx); + let (cx, cy) = (cos * cxp - sin * cyp + (p0.0 + p1.0) * 0.5, sin * cxp + cos * cyp + (p0.1 + p1.1) * 0.5); + let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy); + let (ux, uy) = ((x1 - cxp) / rx, (y1 - cyp) / ry); + let (vx, vy) = ((-x1 - cxp) / rx, (-y1 - cyp) / ry); + let theta1 = angle(1.0, 0.0, ux, uy); + let mut delta = angle(ux, uy, vx, vy); + let tau = std::f64::consts::TAU; + if !sweep && delta > 0.0 { + delta -= tau; + } else if sweep && delta < 0.0 { + delta += tau; + } + let n = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().clamp(1.0, 4.0) as usize; + let step = delta / n as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + // A point / tangent on the unit circle, mapped onto the rotated ellipse. + let map = |x: f64, y: f64| P(cx + rx * cos * x - ry * sin * y, cy + rx * sin * x + ry * cos * y); + let mut t = theta1; + for i in 0..n { + let (s0, c0) = t.sin_cos(); + let t1 = t + step; + let (s1, c1) = t1.sin_cos(); + let a = map(c0 - k * s0, s0 + k * c0); + let b = map(c1 + k * s1, s1 - k * c1); + // Land exactly on the requested end point. + let e = if i + 1 == n { p1 } else { map(c1, s1) }; + path.cubic_to(a.v(), b.v(), e.v()); + t = t1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PathCmd; + + fn ends(p: &Path) -> Vec { + p.anchors().into_iter().map(|(_, a)| a).collect() + } + + #[test] + fn relative_and_shorthand_commands() { + let p = parse_path_data("m10 10 h5 v5 H10 z m 1,1 l2-2").unwrap(); + assert_eq!(ends(&p), vec![Vec2::new(10.0, 10.0), Vec2::new(15.0, 10.0), Vec2::new(15.0, 15.0), Vec2::new(10.0, 15.0), Vec2::new(11.0, 11.0), Vec2::new(13.0, 9.0)]); + assert!(matches!(p.cmds[4], PathCmd::Close)); + // Implicit lineto after moveto, packed negative numbers. + let q = parse_path_data("M0 0 10 0-5.5.5").unwrap(); + assert_eq!(ends(&q), vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(-5.5, 0.5)]); + // S reflects the previous control point. + let s = parse_path_data("M0 0 C 0 10 10 10 10 0 S 20 -10 20 0").unwrap(); + assert!(matches!(s.cmds[2], PathCmd::CubicTo(c1, _, _) if (c1 - Vec2::new(10.0, -10.0)).length() < 1e-5)); + } + + #[test] + fn arcs_land_on_the_ellipse() { + // A half circle of radius 5 from (0,0) to (10,0), sweeping through (5,-5) or (5,5). + for (sweep, mid_y) in [("1", -5.0), ("0", 5.0)] { + let p = parse_path_data(&format!("M0 0 A5 5 0 0 {sweep} 10 0")).unwrap(); + let lines = p.flatten(&crate::Affine::IDENTITY, 0.01); + let pts = &lines[0].points; + assert!(pts.iter().all(|q| (q.distance(Vec2::new(5.0, 0.0)) - 5.0).abs() < 0.05), "on the circle"); + assert!(pts.iter().any(|q| (q.y - mid_y).abs() < 0.05), "through the right side ({sweep})"); + assert_eq!(pts.last().copied(), Some(Vec2::new(10.0, 0.0))); + } + // Packed flags as icon sets write them, and radii too small get scaled up. + let p = parse_path_data("M2 2a1 1 0 011 1a.1.1 0 0 0 4 0").unwrap(); + assert_eq!(ends(&p).last().copied(), Some(Vec2::new(7.0, 3.0))); + // A real icon outline (rounded square corner arcs). + let lock = parse_path_data("M7 11V7a5 5 0 0 1 10 0v4").unwrap(); + assert_eq!(ends(&lock).last().copied(), Some(Vec2::new(17.0, 11.0))); + } + + #[test] + fn bad_input_is_an_error() { + for bad in ["", "10 10", "M", "M 1", "M0 0 A1 1 0 2 0 3 3", "M0 0 Z 4 4", "M0 0 L1e999 0", "M0 0 X1 1"] { + if bad.is_empty() { + assert!(parse_path_data(bad).unwrap().is_empty()); + continue; + } + assert!(parse_path_data(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/geom/src/trace.rs b/crates/geom/src/trace.rs new file mode 100644 index 00000000..1015ebf7 --- /dev/null +++ b/crates/geom/src/trace.rs @@ -0,0 +1,148 @@ +//! Mask → outlines: closed iso-contours of a grid of values (Paint Bucket regions). +//! +//! Marching squares at level 0.5 over cell centres, with linear interpolation along cell edges +//! and saddles resolved by the cell average, gives closed, non-intersecting loops: outer +//! boundaries and holes, which fill correctly with the even-odd rule whatever their direction. +//! +//! Ported from PhotoCraft's mask tracer (`vector::trace::contours`, same project family, MIT OR +//! Apache-2.0) and reviewed: values are read through a bounds-checked accessor (no indexing that +//! a bad size could push out of range), the grid size is validated, and points come back in +//! cell units for the caller to map. Curve fitting is `crate::fit_curve`. + +use crate::Vec2; +use std::collections::HashMap; + +/// Largest grid traced (cells). +pub const MAX_CELLS: usize = 16_000_000; + +/// Closed contours at level 0.5 of `values` (row-major, `w × h`); cell `(x, y)` has its centre +/// at `(x + 0.5, y + 0.5)`. Values outside the grid count as 0. Empty when the sizes disagree. +pub fn contours(values: &[f32], w: usize, h: usize) -> Vec> { + if w == 0 || h == 0 || w.saturating_mul(h) != values.len() || values.len() > MAX_CELLS { + return Vec::new(); + } + let (wi, hi) = (w as i64, h as i64); + let get = |x: i64, y: i64| -> f32 { + if x < 0 || y < 0 || x >= wi || y >= hi { + return 0.0; + } + values.get((y * wi + x) as usize).copied().unwrap_or(0.0) + }; + let lvl = 0.5f32; + let point = |a: (i64, i64), b: (i64, i64)| -> Vec2 { + let (va, vb) = (get(a.0, a.1), get(b.0, b.1)); + let t = if (vb - va).abs() > 1e-9 { ((lvl - va) / (vb - va)).clamp(0.0, 1.0) } else { 0.5 }; + let (ax, ay) = (a.0 as f32 + 0.5, a.1 as f32 + 0.5); + let (bx, by) = (b.0 as f32 + 0.5, b.1 as f32 + 0.5); + Vec2::new(ax + (bx - ax) * t, ay + (by - ay) * t) + }; + // Edge ids: horizontal edge between (x,y)-(x+1,y) = (x, y, 0); vertical (x,y)-(x,y+1) = (x, y, 1). + // Segments go edge → edge with the inside on the left (y down). + let mut next: HashMap<(i64, i64, u8), (i64, i64, u8)> = HashMap::new(); + for cy in -1..hi { + for cx in -1..wi { + let tl = get(cx, cy) >= lvl; + let tr = get(cx + 1, cy) >= lvl; + let br = get(cx + 1, cy + 1) >= lvl; + let bl = get(cx, cy + 1) >= lvl; + let idx = u8::from(tl) | (u8::from(tr) << 1) | (u8::from(br) << 2) | (u8::from(bl) << 3); + if idx == 0 || idx == 15 { + continue; + } + let top = (cx, cy, 0u8); + let bottom = (cx, cy + 1, 0u8); + let left = (cx, cy, 1u8); + let right = (cx + 1, cy, 1u8); + let centre = || (get(cx, cy) + get(cx + 1, cy) + get(cx + 1, cy + 1) + get(cx, cy + 1)) / 4.0 >= lvl; + let mut seg = |a, b| { + next.insert(a, b); + }; + match idx { + 1 => seg(left, top), + 2 => seg(top, right), + 3 => seg(left, right), + 4 => seg(right, bottom), + 5 => { + if centre() { + seg(left, bottom); + seg(right, top); + } else { + seg(left, top); + seg(right, bottom); + } + } + 6 => seg(top, bottom), + 7 => seg(left, bottom), + 8 => seg(bottom, left), + 9 => seg(bottom, top), + 10 => { + if centre() { + seg(top, left); + seg(bottom, right); + } else { + seg(top, right); + seg(bottom, left); + } + } + 11 => seg(bottom, right), + 12 => seg(right, left), + 13 => seg(right, top), + 14 => seg(top, left), + _ => {} + } + } + } + let edge_point = |e: (i64, i64, u8)| if e.2 == 0 { point((e.0, e.1), (e.0 + 1, e.1)) } else { point((e.0, e.1), (e.0, e.1 + 1)) }; + let mut keys: Vec<(i64, i64, u8)> = next.keys().copied().collect(); + keys.sort_unstable_by_key(|k| (k.1, k.0, k.2)); + let mut out = Vec::new(); + for start in keys { + if !next.contains_key(&start) { + continue; + } + let mut lp = Vec::new(); + let mut cur = start; + while let Some(n) = next.remove(&cur) { + lp.push(edge_point(cur)); + cur = n; + if cur == start { + break; + } + } + // Drop consecutive duplicates (interpolation can land on a corner). + lp.dedup_by(|a, b| a.distance(*b) < 1e-6); + if lp.len() >= 3 { + out.push(lp); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn grid(w: usize, h: usize, inside: impl Fn(usize, usize) -> bool) -> Vec { + (0..w * h).map(|i| if inside(i % w, i / w) { 1.0 } else { 0.0 }).collect() + } + + #[test] + fn a_square_and_a_ring() { + let sq = grid(10, 10, |x, y| (2..8).contains(&x) && (2..8).contains(&y)); + let loops = contours(&sq, 10, 10); + assert_eq!(loops.len(), 1); + let xs: Vec = loops[0].iter().map(|p| p.x).collect(); + let (lo, hi) = (xs.iter().copied().fold(f32::INFINITY, f32::min), xs.iter().copied().fold(0.0, f32::max)); + assert!((lo - 2.0).abs() < 0.01 && (hi - 8.0).abs() < 0.01, "{lo}..{hi}: edges halfway between cells"); + // A ring has an outer boundary and a hole. + let ring = grid(20, 20, |x, y| (2..18).contains(&x) && (2..18).contains(&y) && !((7..13).contains(&x) && (7..13).contains(&y))); + assert_eq!(contours(&ring, 20, 20).len(), 2); + } + + #[test] + fn mismatched_sizes_are_empty_not_a_panic() { + assert!(contours(&[1.0; 10], 3, 3).is_empty()); + assert!(contours(&[], 0, 0).is_empty()); + assert_eq!(contours(&[1.0], 1, 1).len(), 1, "a single cell touching the border"); + } +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml new file mode 100644 index 00000000..8d6932f1 --- /dev/null +++ b/crates/render/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "anicraft-render" +description = "AniCraft L2: deterministic CPU oracle renderer (analytic coverage rasterizer, paints, compositor, PNG)" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[dependencies] +anicraft-geom.workspace = true +anicraft-doc.workspace = true +rayon.workspace = true +png.workspace = true +thiserror.workspace = true + +[lints] +workspace = true diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs new file mode 100644 index 00000000..d5d23975 --- /dev/null +++ b/crates/render/src/lib.rs @@ -0,0 +1,610 @@ +//! AniCraft CPU oracle renderer (layer L2). +//! +//! Deterministic: the same display list and view always produce the same bytes, whatever the +//! thread count. Each output row is written by exactly one task and shapes composite in order. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod paint; +pub mod raster; +pub mod stroke; + +use anicraft_doc::{ColorEffect, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate}; +use anicraft_geom::{Affine, FillRule, Rect, Vec2}; +use paint::{Premul, Shader, premultiply}; +use raster::{Coverage, IRect}; +use rayon::prelude::*; + +/// Largest surface we allocate (pixels): 4096 × 4096. +pub const MAX_PIXELS: u64 = 4096 * 4096; +/// Flattening tolerance in output pixels. +pub const TOLERANCE: f32 = 0.1; + +#[derive(Debug, thiserror::Error)] +pub enum RenderError { + #[error("image {0}×{1} is too large (limit {MAX_PIXELS} pixels)")] + TooLarge(u32, u32), + #[error("PNG encoding failed: {0}")] + Png(String), + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), +} + +/// Premultiplied f32 RGBA surface. +#[derive(Clone, Debug, PartialEq)] +pub struct Pixmap { + pub width: u32, + pub height: u32, + pub data: Vec, +} + +impl Pixmap { + pub fn new(width: u32, height: u32) -> Result { + let n = u64::from(width) * u64::from(height); + if n > MAX_PIXELS { + return Err(RenderError::TooLarge(width, height)); + } + Ok(Pixmap { width, height, data: vec![[0.0; 4]; n as usize] }) + } + + pub fn fill(&mut self, c: Rgba) { + let p = premultiply(c); + self.data.fill(p); + } + + /// Straight-alpha 8-bit RGBA bytes. + pub fn to_rgba8(&self) -> Vec { + let mut out = Vec::with_capacity(self.data.len() * 4); + for p in &self.data { + let a = p[3].clamp(0.0, 1.0); + let un = |v: f32| if a > 1e-6 { (v / a).clamp(0.0, 1.0) } else { 0.0 }; + let q = |v: f32| (v * 255.0 + 0.5) as u8; + out.extend_from_slice(&[q(un(p[0])), q(un(p[1])), q(un(p[2])), q(a)]); + } + out + } + + /// Premultiplied 8-bit RGBA (what GPU textures with premultiplied alpha expect). + pub fn to_premul_rgba8(&self) -> Vec { + let mut out = Vec::with_capacity(self.data.len() * 4); + for p in &self.data { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + out.extend_from_slice(&[q(p[0]), q(p[1]), q(p[2]), q(p[3])]); + } + out + } + + pub fn encode_png(&self) -> Result, RenderError> { + encode_png(self.width, self.height, &self.to_rgba8()) + } + + pub fn pixel(&self, x: u32, y: u32) -> Option { + if x >= self.width || y >= self.height { + return None; + } + self.data.get(y as usize * self.width as usize + x as usize).copied() + } +} + +/// Encodes straight-alpha RGBA8 as PNG. +pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, RenderError> { + let mut buf = Vec::new(); + { + let mut enc = png::Encoder::new(&mut buf, width, height); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + let mut w = enc.write_header().map_err(|e| RenderError::Png(e.to_string()))?; + w.write_image_data(rgba).map_err(|e| RenderError::Png(e.to_string()))?; + } + Ok(buf) +} + +/// Where and how to draw. +#[derive(Clone, Copy, Debug)] +pub struct View { + /// Stage → pixel transform. + pub transform: Affine, + pub width: u32, + pub height: u32, + /// Fill colour before drawing (`None` = transparent). + pub background: Option, +} + +impl View { + /// The whole stage at `scale`. + pub fn stage(doc: &Document, scale: f32) -> View { + let s = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; + View { + transform: Affine::scale(s, s), + width: ((doc.stage.width as f32 * s).round() as u32).max(1), + height: ((doc.stage.height as f32 * s).round() as u32).max(1), + background: Some(doc.stage.background), + } + } +} + +/// Statistics from one render (for the status bar and perf logs). +#[derive(Clone, Copy, Debug, Default)] +pub struct RenderStats { + pub items: usize, + pub drawn: usize, + /// Items skipped because they lie outside the view. + pub culled: usize, + pub edges: usize, + pub pixels_touched: u64, +} + +/// Renders frame `frame` of `doc` at `scale` with the stage background. +pub fn render_frame(doc: &Document, frame: u32, scale: f32) -> Result { + let dl = evaluate(doc, frame); + render(&dl, &View::stage(doc, scale)).map(|(p, _)| p) +} + +/// Renders a display list. +pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), RenderError> { + let mut pm = Pixmap::new(view.width, view.height)?; + if let Some(bg) = view.background { + pm.fill(bg); + } + let surface = IRect { x0: 0, y0: 0, x1: view.width as i32, y1: view.height as i32 }; + + // Phase 1 (parallel over items): cull, flatten, stroke and build shaders. Output keeps + // display-list order. + let prepared: Vec> = dl.items.par_iter().map(|item| prepare(item, &view.transform, surface)).collect(); + let mut stats = RenderStats { items: dl.items.len(), ..Default::default() }; + let mut ops: Vec = Vec::with_capacity(prepared.len()); + let mut mask_ops: Vec = Vec::new(); + for p in prepared { + if p.is_empty() { + stats.culled += 1; + } + for op in p { + if op.masks.is_some() { mask_ops.push(op) } else { ops.push(op) } + } + } + let clips = Clips::new(&dl.clip_parents, mask_ops); + // A clipped op can only touch its clip's area; an op whose clip is empty draws nothing. + ops.retain_mut(|op| { + let Some(c) = op.clip else { return true }; + op.bounds = op.bounds.intersect(&clips.bounds(c)); + !op.bounds.is_empty() + }); + stats.drawn = ops.len(); + for op in &ops { + stats.edges += op.polys.iter().map(Vec::len).sum::(); + stats.pixels_touched += (op.bounds.width() * op.bounds.height()) as u64; + } + + // Phase 2 (parallel over horizontal bands): each band rasterizes every op that touches + // it, in order, into its own rows. A row is owned by exactly one band, so the result is + // identical to a serial render whatever the thread count. + let w = view.width as usize; + pm.data.par_chunks_mut(BAND_ROWS * w.max(1)).enumerate().for_each(|(bi, rows)| { + let y0 = (bi * BAND_ROWS) as i32; + let band = IRect { x0: 0, y0, x1: surface.x1, y1: (y0 + BAND_ROWS as i32).min(surface.y1) }; + let mut cov = Coverage::new(IRect { x0: 0, y0: 0, x1: 0, y1: 0 }); + let mut row = Vec::new(); + let mut band_clips = BandClips::default(); + for op in &ops { + let b = IRect { x0: op.bounds.x0, y0: op.bounds.y0.max(band.y0), x1: op.bounds.x1, y1: op.bounds.y1.min(band.y1) }; + if b.is_empty() { + continue; + } + let mask = op.clip.map(|c| band_clips.get(&clips, c, band, w, &mut cov, &mut row)); + cov.reset(b); + for poly in &op.polys { + cov.add_polygon(poly); + } + composite(&cov, op, b, band.y0, w, rows, &mut row, mask.as_deref().map(Vec::as_slice)); + } + }); + Ok((pm, stats)) +} + +/// Rows per parallel band. +const BAND_ROWS: usize = 32; + +/// One fill operation, ready to rasterize: polygons in pixel space, its paint and bounds. +struct Prepared { + polys: Vec>, + rule: FillRule, + shader: Shader, + bounds: IRect, + /// Drawn only inside this clip. + clip: Option, + /// Mask artwork for this clip (not drawn). + masks: Option, +} + +/// The clips of a display list: their mask artwork and where each can be non-zero. +struct Clips { + parents: Vec>, + /// Mask artwork, grouped by clip. + art: Vec>, + bounds: Vec, +} + +const NO_PIXELS: IRect = IRect { x0: 0, y0: 0, x1: 0, y1: 0 }; + +impl Clips { + fn new(parents: &[Option], mask_ops: Vec) -> Clips { + let n = parents.len(); + let mut art: Vec> = (0..n).map(|_| Vec::new()).collect(); + for op in mask_ops { + if let Some(a) = op.masks.and_then(|c| art.get_mut(c as usize)) { + a.push(op); + } + } + // A parent always precedes its children, so one pass in order intersects the chain. + // A malformed parent link (not earlier in the list) masks everything out. + let mut bounds: Vec = Vec::with_capacity(n); + let mut clean: Vec> = Vec::with_capacity(n); + for (i, a) in art.iter().enumerate() { + let own = a.iter().fold(NO_PIXELS, |r, op| r.union(&op.bounds)); + let parent = parents.get(i).copied().flatten(); + let b = match parent { + None => own, + Some(p) => bounds.get(p as usize).filter(|_| (p as usize) < i).map_or(NO_PIXELS, |pb| own.intersect(pb)), + }; + bounds.push(b); + clean.push(parent.filter(|&p| (p as usize) < i)); + } + Clips { parents: clean, art, bounds } + } + + fn bounds(&self, c: u32) -> IRect { + self.bounds.get(c as usize).copied().unwrap_or(NO_PIXELS) + } +} + +/// Clip coverage for one band, computed on first use: `w × band height` values in `0..=1`. +#[derive(Default)] +struct BandClips { + cov: Vec>>>, +} + +impl BandClips { + fn get(&mut self, clips: &Clips, c: u32, band: IRect, w: usize, cov: &mut Coverage, row: &mut Vec) -> std::rc::Rc> { + let i = c as usize; + if self.cov.len() < clips.parents.len() { + self.cov.resize(clips.parents.len(), None); + } + if let Some(Some(done)) = self.cov.get(i) { + return done.clone(); + } + let parent = clips.parents.get(i).copied().flatten().map(|p| self.get(clips, p, band, w, cov, row)); + let mut buf = vec![0.0f32; w * band.height()]; + // Union of the artwork's coverage (a ∪ b = a + b − ab), anti-aliased like any fill. + for op in clips.art.get(i).into_iter().flatten() { + let b = op.bounds.intersect(&band); + if b.is_empty() { + continue; + } + cov.reset(b); + for poly in &op.polys { + cov.add_polygon(poly); + } + row.clear(); + row.resize(b.width(), 0.0); + for ry in 0..b.height() { + cov.resolve_row(ry, op.rule, row); + let start = (b.y0 + ry as i32 - band.y0) as usize * w + b.x0 as usize; + let Some(dst) = buf.get_mut(start..start + b.width()) else { continue }; + for (d, &k) in dst.iter_mut().zip(row.iter()) { + let k = k.clamp(0.0, 1.0); + *d = *d + k - *d * k; + } + } + } + if let Some(p) = parent { + for (d, m) in buf.iter_mut().zip(p.iter()) { + *d *= m; + } + } + let buf = std::rc::Rc::new(buf); + if let Some(slot) = self.cov.get_mut(i) { + *slot = Some(buf.clone()); + } + buf + } +} + +/// Turns a display item into fill operations (fill, then stroke), or none when culled. +fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { + let mut out = Vec::new(); + let m = view.mul(&item.transform); + if !m.is_finite() { + return out; + } + // Mask artwork is its fill area only: no strokes, no opacity (as animators expect). + let is_mask = item.masks.is_some(); + if is_mask && item.fill.is_none() { + return out; + } + // Cull before flattening: control-point bounds are a cheap, conservative superset. + let pad = if is_mask { 1.0 } else { item.stroke.map_or(0.0, |s| s.width * 0.5) + 1.0 }; + let bounds = item.path.bounds().inflate(pad).transformed(&m); + let surface_rect = Rect::new(0.0, 0.0, surface.x1 as f32, surface.y1 as f32); + if bounds.is_empty() || bounds.intersect(&surface_rect).is_empty() { + return out; + } + let lines = item.path.flatten(&m, TOLERANCE); + if lines.is_empty() { + return out; + } + let (clip, masks) = (item.clip, item.masks); + let mut push = |polys: Vec>, rule, shader: Shader| { + if shader.is_solid().is_some_and(|c| c[3] <= 0.0) { + return; + } + if let Some(b) = pixel_bounds(&polys, surface) { + out.push(Prepared { polys, rule, shader, bounds: b, clip, masks }); + } + }; + + if is_mask { + push(lines.iter().map(|l| l.points.clone()).collect(), item.fill_rule, Shader::Solid([1.0; 4])); + return out; + } + if let Some(color) = item.outline { + // Outline mode: hairline in the layer colour, no fill. + push(stroke::stroke_polygons(&lines, 0.5), FillRule::NonZero, Shader::Solid(premultiply(color))); + return out; + } + if let Some(fill) = &item.fill { + let polys: Vec> = lines.iter().map(|l| l.points.clone()).collect(); + push(polys, item.fill_rule, Shader::new(fill, &m, &item.color)); + } + if let Some(st) = item.stroke { + let mut fx: ColorEffect = item.color; + let mut pw = st.width * m.mean_scale(); + if pw.is_finite() && pw > 0.0 { + if pw < 1.0 { + // Thin strokes: keep a 1 px footprint and fade by width (avoids dropouts). + fx.alpha *= pw; + pw = 1.0; + } + push(stroke::stroke_polygons(&lines, pw * 0.5), FillRule::NonZero, Shader::new(&Paint::Solid(st.color), &m, &fx)); + } + } + out +} + +fn pixel_bounds(polys: &[Vec], surface: IRect) -> Option { + let mut r = Rect::EMPTY; + for p in polys.iter().flatten() { + r.include(*p); + } + if !(r.max.x >= r.min.x && r.max.y >= r.min.y) { + return None; // no points + } + let b = IRect { + x0: (r.min.x.floor().max(surface.x0 as f32)) as i32, + y0: (r.min.y.floor().max(surface.y0 as f32)) as i32, + x1: (r.max.x.ceil().min(surface.x1 as f32)) as i32, + y1: (r.max.y.ceil().min(surface.y1 as f32)) as i32, + }; + (!b.is_empty()).then_some(b) +} + +/// Composites coverage `cov` (over `b`) of `op` into the band whose first row is `band_y0`, +/// scaled by the band's clip coverage `mask` when the op is clipped. +#[allow(clippy::too_many_arguments)] +fn composite(cov: &Coverage, op: &Prepared, b: IRect, band_y0: i32, w: usize, rows: &mut [Premul], c: &mut Vec, mask: Option<&[f32]>) { + let bw = b.width(); + c.clear(); + c.resize(bw, 0.0); + let solid = op.shader.is_solid(); + for ry in 0..b.height() { + cov.resolve_row(ry, op.rule, c); + let py = b.y0 + ry as i32; + let start = (py - band_y0) as usize * w + b.x0 as usize; + if let Some(mask) = mask { + let Some(m) = mask.get(start..start + bw) else { continue }; + for (k, m) in c.iter_mut().zip(m) { + *k *= m; + } + } + let Some(dst) = rows.get_mut(start..start + bw) else { continue }; + for (i, (d, &k)) in dst.iter_mut().zip(c.iter()).enumerate() { + if k <= 1e-4 { + continue; + } + let s = match solid { + Some(s) => s, + None => op.shader.at(b.x0 + i as i32, py), + }; + let sa = s[3] * k; + let inv = 1.0 - sa; + d[0] = s[0] * k + d[0] * inv; + d[1] = s[1] * k + d[1] * inv; + d[2] = s[2] * k + d[2] * inv; + d[3] = sa + d[3] * inv; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_doc::{ElementId, LayerId, sample}; + use anicraft_geom::Path; + use std::sync::Arc; + + fn item(path: Path, fill: Paint) -> DisplayItem { + DisplayItem { + path: Arc::new(path), + transform: Affine::IDENTITY, + fill: Some(fill), + stroke: None, + fill_rule: FillRule::NonZero, + color: ColorEffect::default(), + layer: LayerId(0), + element: ElementId(0), + outline: None, + clip: None, + masks: None, + } + } + + fn list(items: Vec) -> DisplayList { + DisplayList { items, clip_parents: Vec::new() } + } + + #[test] + fn mask_reveals_only_its_fill_area() { + // A 40 × 40 square masked by a circle of radius 10: only the circle's area shows, in + // the square's colour; the mask's own colour, stroke and opacity play no part. + let mut square = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); + square.clip = Some(0); + let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2))); + mask.masks = Some(0); + mask.stroke = Some(anicraft_doc::Stroke { color: Rgba::BLACK, width: 8.0 }); + let dl = DisplayList { items: vec![square, mask], clip_parents: vec![None] }; + let (pm, _) = render(&dl, &view(40, 40)).unwrap(); + // Pixel for pixel, the same as the circle drawn in the square's colour. + let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); + let (plain, _) = render(&list(vec![circle]), &view(40, 40)).unwrap(); + assert!(pm.data.iter().zip(&plain.data).all(|(a, b)| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5))); + let area = alpha_sum(&plain); + assert_eq!(pm.pixel(20, 20).unwrap(), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(pm.pixel(2, 2).unwrap()[3], 0.0); + // Two overlapping mask shapes reveal their union, not a cancelled overlap. + let mut dl2 = dl.clone(); + let mut m2 = item(Path::rect(20.0, 0.0, 20.0, 40.0), Paint::Solid(Rgba::WHITE)); + m2.masks = Some(0); + dl2.items.push(m2); + let (pm2, _) = render(&dl2, &view(40, 40)).unwrap(); + assert_eq!(pm2.pixel(25, 20).unwrap()[3], 1.0); + assert_eq!(pm2.pixel(35, 2).unwrap()[3], 1.0); + assert!((alpha_sum(&pm2) - (800.0 + area / 2.0)).abs() < 8.0, "{}", alpha_sum(&pm2)); + } + + #[test] + fn empty_mask_hides_everything_and_unclipped_items_are_untouched() { + let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)); + clipped.clip = Some(0); + let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK)); + let (pm, st) = render(&DisplayList { items: vec![clipped, free.clone()], clip_parents: vec![None] }, &view(8, 8)).unwrap(); + assert_eq!(st.drawn, 1); + assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0); + } + + #[test] + fn nested_clips_intersect_and_bad_links_draw_nothing() { + let mut fill = item(Path::rect(0.0, 0.0, 64.0, 64.0), Paint::Solid(Rgba::BLACK)); + fill.clip = Some(1); + let mut outer = item(Path::rect(0.0, 0.0, 32.0, 64.0), Paint::Solid(Rgba::BLACK)); + outer.masks = Some(0); + let mut inner = item(Path::rect(0.0, 16.0, 64.0, 32.0), Paint::Solid(Rgba::BLACK)); + inner.masks = Some(1); + let items = vec![fill, outer, inner]; + // Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives. + let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: vec![None, Some(0)] }, &view(64, 64)).unwrap(); + assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm)); + // A parent link pointing forward (malformed) or out of range masks everything out. + for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] { + let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: parents }, &view(64, 64)).unwrap(); + assert_eq!(alpha_sum(&pm), 0.0); + } + } + + fn view(w: u32, h: u32) -> View { + View { transform: Affine::IDENTITY, width: w, height: h, background: None } + } + + fn alpha_sum(p: &Pixmap) -> f32 { + p.data.iter().map(|c| c[3]).sum() + } + + #[test] + fn circle_area_matches_pi_r2() { + let r = 40.0; + let dl = list(vec![item(Path::ellipse(50.0, 50.0, r, r), Paint::Solid(Rgba::BLACK))]); + let (pm, _) = render(&dl, &view(100, 100)).unwrap(); + let area = std::f32::consts::PI * r * r; + let err = (alpha_sum(&pm) - area).abs() / area; + assert!(err < 0.005, "relative error {err}"); + } + + #[test] + fn rect_is_pixel_exact_and_clipped() { + let dl = list(vec![item(Path::rect(-10.0, 2.0, 15.0, 3.0), Paint::Solid(Rgba::WHITE))]); + let (pm, _) = render(&dl, &view(8, 8)).unwrap(); + assert_eq!(pm.pixel(0, 2).unwrap(), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(pm.pixel(4, 4).unwrap(), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(pm.pixel(5, 3).unwrap()[3], 0.0); + assert_eq!(pm.pixel(0, 1).unwrap()[3], 0.0); + assert!((alpha_sum(&pm) - 15.0).abs() < 1e-3); + } + + #[test] + fn stroke_covers_expected_area() { + let mut it = item(Path::line(Vec2::new(10.0, 20.0), Vec2::new(90.0, 20.0)), Paint::Solid(Rgba::BLACK)); + it.fill = None; + it.stroke = Some(anicraft_doc::Stroke { color: Rgba::BLACK, width: 4.0 }); + let (pm, _) = render(&list(vec![it]),&view(100, 40)).unwrap(); + // 80 × 4 body plus two round caps (π · 2²) + let expected = 80.0 * 4.0 + std::f32::consts::PI * 4.0; + assert!((alpha_sum(&pm) - expected).abs() / expected < 0.01, "{}", alpha_sum(&pm)); + } + + #[test] + fn src_over_order() { + let a = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0))); + let b = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 0.5))); + let (pm, _) = render(&list(vec![a, b]),&view(4, 4)).unwrap(); + let p = pm.pixel(1, 1).unwrap(); + assert!((p[0] - 0.5).abs() < 1e-5 && (p[2] - 0.5).abs() < 1e-5 && (p[3] - 1.0).abs() < 1e-5); + } + + #[test] + fn demo_renders_deterministically() { + let d = sample::demo(); + let a = render_frame(&d, 7, 0.5).unwrap(); + let b = render_frame(&d, 7, 0.5).unwrap(); + assert_eq!(a.to_rgba8(), b.to_rgba8()); + assert_eq!((a.width, a.height), (640, 360)); + // Frames differ because things move. + let c = render_frame(&d, 20, 0.5).unwrap(); + assert_ne!(a.to_rgba8(), c.to_rgba8()); + let png = a.encode_png().unwrap(); + assert_eq!(&png[1..4], b"PNG"); + } + + #[test] + fn offscreen_items_are_culled_without_changing_pixels() { + let on = item(Path::rect(2.0, 2.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)); + let off = item(Path::ellipse(500.0, 500.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK)); + let (a, sa) = render(&list(vec![on.clone(), off]),&view(16, 16)).unwrap(); + let (b, _) = render(&list(vec![on]),&view(16, 16)).unwrap(); + assert_eq!(sa.culled, 1); + assert_eq!(sa.drawn, 1); + assert_eq!(a, b); + } + + #[test] + fn band_boundaries_do_not_change_coverage() { + // A rectangle with fractional edges spanning three 32-row bands keeps its exact area. + let dl = list(vec![item(Path::rect(3.25, 20.5, 40.0, 61.75), Paint::Solid(Rgba::BLACK))]); + let (pm, _) = render(&dl, &view(64, 100)).unwrap(); + assert!((alpha_sum(&pm) - 40.0 * 61.75).abs() < 1e-2, "{}", alpha_sum(&pm)); + // and a full row inside the shape is fully covered on both sides of a band edge + for y in [31, 32] { + assert_eq!(pm.pixel(10, y).unwrap()[3], 1.0); + } + } + + #[test] + fn many_shapes_render_identically_across_runs() { + let d = sample::stress(4, 300, 24); + let a = render_frame(&d, 5, 0.5).unwrap(); + for _ in 0..3 { + assert_eq!(render_frame(&d, 5, 0.5).unwrap(), a); + } + } + + #[test] + fn huge_surface_is_refused() { + assert!(matches!(Pixmap::new(100_000, 100_000), Err(RenderError::TooLarge(..)))); + } +} diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs new file mode 100644 index 00000000..18e10228 --- /dev/null +++ b/crates/render/src/paint.rs @@ -0,0 +1,122 @@ +//! Paint shaders: solid colours and gradients evaluated per pixel through a 256-entry LUT. + +use anicraft_doc::{ColorEffect, GradientStop, Paint, Rgba}; +use anicraft_geom::{Affine, Vec2}; + +/// Premultiplied RGBA. +pub type Premul = [f32; 4]; + +pub fn premultiply(c: Rgba) -> Premul { + let c = c.sanitized(); + [c.r * c.a, c.g * c.a, c.b * c.a, c.a] +} + +const LUT: usize = 256; + +pub enum Shader { + Solid(Premul), + Linear { inv: Affine, start: Vec2, dir: Vec2, lut: Box<[Premul; LUT]> }, + Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> }, +} + +fn sample_stops(stops: &[GradientStop], t: f32) -> Rgba { + let Some(first) = stops.first() else { return Rgba::TRANSPARENT }; + if t <= first.offset { + return first.color; + } + for w in stops.windows(2) { + let (a, b) = (w[0], w[1]); + if t <= b.offset { + let span = b.offset - a.offset; + let k = if span > 1e-6 { (t - a.offset) / span } else { 1.0 }; + return a.color.lerp(b.color, k); + } + } + stops.last().map_or(first.color, |s| s.color) +} + +fn build_lut(stops: &[GradientStop], fx: &ColorEffect) -> Box<[Premul; LUT]> { + let mut sorted: Vec = stops.iter().copied().filter(|s| s.offset.is_finite()).collect(); + sorted.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + let mut lut = Box::new([[0.0; 4]; LUT]); + for (i, slot) in lut.iter_mut().enumerate() { + let t = i as f32 / (LUT - 1) as f32; + *slot = premultiply(fx.apply(sample_stops(&sorted, t))); + } + lut +} + +impl Shader { + /// `to_pixel` maps the paint's local space to pixels. + pub fn new(paint: &Paint, to_pixel: &Affine, fx: &ColorEffect) -> Shader { + let inv = to_pixel.inverse(); + match (paint, inv) { + (Paint::Solid(c), _) => Shader::Solid(premultiply(fx.apply(*c))), + (Paint::Linear { start, end, stops }, Some(inv)) => { + let d = *end - *start; + let len2 = d.dot(d); + if len2 < 1e-12 { + return Shader::Solid(premultiply(fx.apply(stops.last().map_or(Rgba::TRANSPARENT, |s| s.color)))); + } + Shader::Linear { inv, start: *start, dir: d * (1.0 / len2), lut: build_lut(stops, fx) } + } + (Paint::Radial { center, radius, stops }, Some(inv)) => { + if !(radius.is_finite() && *radius > 1e-6) { + return Shader::Solid(premultiply(fx.apply(stops.last().map_or(Rgba::TRANSPARENT, |s| s.color)))); + } + Shader::Radial { inv, center: *center, inv_radius: 1.0 / radius, lut: build_lut(stops, fx) } + } + (p, None) => Shader::Solid(premultiply(fx.apply(p.primary_color()))), + } + } + + #[inline] + pub fn is_solid(&self) -> Option { + match self { + Shader::Solid(c) => Some(*c), + _ => None, + } + } + + /// Colour at pixel centre `(x + 0.5, y + 0.5)`. + #[inline] + pub fn at(&self, x: i32, y: i32) -> Premul { + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let lookup = |lut: &[Premul; LUT], t: f32| { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + lut[(t * (LUT - 1) as f32 + 0.5) as usize & (LUT - 1)] + }; + match self { + Shader::Solid(c) => *c, + Shader::Linear { inv, start, dir, lut } => lookup(lut, (inv.apply(p) - *start).dot(*dir)), + Shader::Radial { inv, center, inv_radius, lut } => lookup(lut, (inv.apply(p) - *center).length() * inv_radius), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn linear_gradient_endpoints() { + let paint = Paint::Linear { + start: Vec2::new(0.0, 0.0), + end: Vec2::new(100.0, 0.0), + stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }], + }; + let s = Shader::new(&paint, &Affine::IDENTITY, &ColorEffect::default()); + assert!(s.at(0, 0)[0] < 0.02); + assert!(s.at(99, 0)[0] > 0.98); + assert!((s.at(49, 0)[0] - 0.5).abs() < 0.02); + // gradient follows the transform + let s2 = Shader::new(&paint, &Affine::scale(2.0, 1.0), &ColorEffect::default()); + assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02); + } + + #[test] + fn alpha_effect_premultiplies() { + let s = Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect { alpha: 0.5, ..Default::default() }); + assert_eq!(s.at(0, 0), [0.5, 0.5, 0.5, 0.5]); + } +} diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs new file mode 100644 index 00000000..8763d973 --- /dev/null +++ b/crates/render/src/raster.rs @@ -0,0 +1,272 @@ +//! Signed-area coverage accumulation rasterizer. +//! +//! Each edge deposits the signed area it sweeps into a per-pixel accumulation buffer; a running +//! sum along a row then yields exact analytic coverage (no supersampling). The buffer covers only +//! the shape's pixel bounding box. Edges left of the box collapse onto its left edge, which keeps +//! the winding of every pixel to their right correct. + +use anicraft_geom::{FillRule, Vec2}; + +/// Integer pixel rectangle `[x0, x1) × [y0, y1)`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IRect { + pub x0: i32, + pub y0: i32, + pub x1: i32, + pub y1: i32, +} + +impl IRect { + pub fn width(&self) -> usize { + (self.x1 - self.x0).max(0) as usize + } + pub fn height(&self) -> usize { + (self.y1 - self.y0).max(0) as usize + } + pub fn is_empty(&self) -> bool { + self.x1 <= self.x0 || self.y1 <= self.y0 + } + pub fn intersect(&self, o: &IRect) -> IRect { + IRect { x0: self.x0.max(o.x0), y0: self.y0.max(o.y0), x1: self.x1.min(o.x1), y1: self.y1.min(o.y1) } + } + /// Smallest rectangle holding both (an empty side is ignored). + pub fn union(&self, o: &IRect) -> IRect { + if self.is_empty() { + return *o; + } + if o.is_empty() { + return *self; + } + IRect { x0: self.x0.min(o.x0), y0: self.y0.min(o.y0), x1: self.x1.max(o.x1), y1: self.y1.max(o.y1) } + } +} + +/// Coverage accumulation buffer over a pixel rectangle. +pub struct Coverage { + pub bounds: IRect, + stride: usize, + acc: Vec, +} + +impl Coverage { + pub fn new(bounds: IRect) -> Coverage { + let stride = bounds.width() + 2; + Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()] } + } + + /// Re-targets the buffer at `bounds`, reusing its allocation (one buffer per render band). + pub fn reset(&mut self, bounds: IRect) { + self.bounds = bounds; + self.stride = bounds.width() + 2; + self.acc.clear(); + self.acc.resize(self.stride * bounds.height(), 0.0); + } + + /// Adds one edge, in pixel coordinates of the target surface. + pub fn add_line(&mut self, a: Vec2, b: Vec2) { + if !(a.is_finite() && b.is_finite()) { + return; + } + let o = Vec2::new(self.bounds.x0 as f32, self.bounds.y0 as f32); + let (a, b) = (a - o, b - o); + if a.y == b.y { + return; + } + let w = self.bounds.width() as f32; + // Split at x = 0 and x = w so every piece lies fully inside or outside [0, w]. + let mut ts = [0.0f32, 1.0, 1.0, 1.0]; + let mut n = 1; + let dx = b.x - a.x; + if dx != 0.0 { + for edge in [0.0, w] { + let t = (edge - a.x) / dx; + if t > 0.0 && t < 1.0 { + ts[n] = t; + n += 1; + } + } + } + ts[n] = 1.0; + let (head, _) = ts.split_at_mut(n + 1); + head.sort_by(f32::total_cmp); + let clamp = |p: Vec2| Vec2::new(p.x.clamp(0.0, w), p.y); + for win in head.windows(2) { + let (t0, t1) = (win[0], win[1]); + if t1 <= t0 { + continue; + } + self.raw_line(clamp(a.lerp(b, t0)), clamp(a.lerp(b, t1))); + } + } + + #[inline] + fn deposit(&mut self, row: usize, xi: i64, v: f32) { + if xi >= 0 + && (xi as usize) < self.stride + && let Some(cell) = self.acc.get_mut(row + xi as usize) + { + *cell += v; + } + } + + fn raw_line(&mut self, p0: Vec2, p1: Vec2) { + if (p0.y - p1.y).abs() < 1e-9 { + return; + } + let (dir, p0, p1) = if p0.y < p1.y { (1.0f32, p0, p1) } else { (-1.0f32, p1, p0) }; + let h = self.bounds.height(); + let hf = h as f32; + if p1.y <= 0.0 || p0.y >= hf { + return; + } + let dxdy = (p1.x - p0.x) / (p1.y - p0.y); + let mut x = p0.x; + let ystart = if p0.y < 0.0 { + x -= p0.y * dxdy; + 0 + } else { + p0.y as usize + }; + let yend = (p1.y.ceil() as usize).min(h); + for y in ystart..yend { + let row = y * self.stride; + let dy = ((y + 1) as f32).min(p1.y) - (y as f32).max(p0.y); + let xnext = x + dxdy * dy; + let d = dy * dir; + let (x0, x1) = if x < xnext { (x, xnext) } else { (xnext, x) }; + let x0floor = x0.floor(); + let x0i = x0floor as i64; + let x1ceil = x1.ceil(); + let x1i = x1ceil as i64; + if x1i <= x0i + 1 { + let xmf = 0.5 * (x + xnext) - x0floor; + self.deposit(row, x0i, d - d * xmf); + self.deposit(row, x0i + 1, d * xmf); + } else { + let s = 1.0 / (x1 - x0); + let x0f = x0 - x0floor; + let a0 = 0.5 * s * (1.0 - x0f) * (1.0 - x0f); + let x1f = x1 - x1ceil + 1.0; + let am = 0.5 * s * x1f * x1f; + self.deposit(row, x0i, d * a0); + if x1i == x0i + 2 { + self.deposit(row, x0i + 1, d * (1.0 - a0 - am)); + } else { + let a1 = s * (1.5 - x0f); + self.deposit(row, x0i + 1, d * (a1 - a0)); + for xi in x0i + 2..x1i - 1 { + self.deposit(row, xi, d * s); + } + let a2 = a1 + (x1i - x0i - 3) as f32 * s; + self.deposit(row, x1i - 1, d * (1.0 - a2 - am)); + } + self.deposit(row, x1i, d * am); + } + x = xnext; + } + } + + /// Adds a closed polygon (the closing edge is implicit). + pub fn add_polygon(&mut self, pts: &[Vec2]) { + let n = pts.len(); + if n < 2 { + return; + } + for i in 0..n { + let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % n)) else { continue }; + self.add_line(a, b); + } + } + + /// Resolves row `y` (relative to the bounds) into coverage values in `out` (len = width). + pub fn resolve_row(&self, y: usize, rule: FillRule, out: &mut [f32]) { + let start = y * self.stride; + let Some(row) = self.acc.get(start..start + self.stride) else { + out.fill(0.0); + return; + }; + let mut sum = 0.0f32; + for (o, a) in out.iter_mut().zip(row) { + sum += a; + *o = fold(sum, rule); + } + } +} + +#[inline] +fn fold(winding: f32, rule: FillRule) -> f32 { + match rule { + FillRule::NonZero => winding.abs().min(1.0), + FillRule::EvenOdd => { + let t = winding.abs() % 2.0; + if t > 1.0 { 2.0 - t } else { t } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn total(c: &Coverage, rule: FillRule) -> f32 { + let mut row = vec![0.0; c.bounds.width()]; + let mut s = 0.0; + for y in 0..c.bounds.height() { + c.resolve_row(y, rule, &mut row); + s += row.iter().sum::(); + } + s + } + + fn rect(x0: f32, y0: f32, x1: f32, y1: f32) -> Vec { + vec![Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)] + } + + #[test] + fn rect_coverage_is_exact() { + let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 20, y1: 20 }); + c.add_polygon(&rect(2.25, 3.5, 12.75, 9.0)); + let area = 10.5 * 5.5; + assert!((total(&c, FillRule::NonZero) - area).abs() < 1e-3); + } + + #[test] + fn partial_pixel_is_fractional() { + let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 4, y1: 1 }); + c.add_polygon(&rect(1.0, 0.0, 2.5, 1.0)); + let mut row = vec![0.0; 4]; + c.resolve_row(0, FillRule::NonZero, &mut row); + assert!((row[0]).abs() < 1e-5); + assert!((row[1] - 1.0).abs() < 1e-5); + assert!((row[2] - 0.5).abs() < 1e-5); + assert!((row[3]).abs() < 1e-5); + } + + #[test] + fn shapes_left_of_bounds_keep_winding() { + // Rectangle starting far left of the buffer: pixels inside must be fully covered. + let mut c = Coverage::new(IRect { x0: 10, y0: 0, x1: 20, y1: 2 }); + c.add_polygon(&rect(-100.0, 0.0, 15.0, 2.0)); + let mut row = vec![0.0; 10]; + c.resolve_row(0, FillRule::NonZero, &mut row); + assert!(row[..5].iter().all(|v| (v - 1.0).abs() < 1e-4), "{row:?}"); + assert!(row[5..].iter().all(|v| v.abs() < 1e-4), "{row:?}"); + } + + #[test] + fn even_odd_hole() { + let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 10, y1: 10 }); + c.add_polygon(&rect(0.0, 0.0, 10.0, 10.0)); + c.add_polygon(&rect(2.0, 2.0, 8.0, 8.0)); + assert!((total(&c, FillRule::EvenOdd) - 64.0).abs() < 1e-2); + assert!((total(&c, FillRule::NonZero) - 100.0).abs() < 1e-2); + } + + #[test] + fn non_finite_edges_ignored() { + let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 4, y1: 4 }); + c.add_line(Vec2::new(f32::NAN, 0.0), Vec2::new(1.0, 3.0)); + c.add_line(Vec2::new(0.0, -1e30), Vec2::new(1e30, 1e30)); + assert!(total(&c, FillRule::NonZero).is_finite()); + } +} diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs new file mode 100644 index 00000000..f2ef3e4a --- /dev/null +++ b/crates/render/src/stroke.rs @@ -0,0 +1,106 @@ +//! Stroker: polylines → positively-wound polygons (segment quads plus round joins and caps). +//! +//! Every emitted polygon has the same orientation, so overlaps only add winding and the +//! non-zero rule gives a seamless union without computing an outline offset. + +use anicraft_geom::{Polyline, Vec2}; + +fn signed_area(p: &[Vec2]) -> f32 { + let n = p.len(); + let mut a = 0.0; + for i in 0..n { + let (Some(u), Some(v)) = (p.get(i), p.get((i + 1) % n)) else { continue }; + a += u.cross(*v); + } + a * 0.5 +} + +fn oriented(mut poly: Vec) -> Vec { + if signed_area(&poly) < 0.0 { + poly.reverse(); + } + poly +} + +/// Polygon approximating a circle within ~0.1 px. +fn disc(c: Vec2, r: f32) -> Vec { + let tol = 0.1f32; + let n = if r > tol { (std::f32::consts::PI / (1.0 - tol / r).clamp(-1.0, 1.0).acos()).ceil() as usize } else { 6 }; + let n = n.clamp(6, 96); + (0..n) + .map(|i| { + let a = i as f32 * std::f32::consts::TAU / n as f32; + Vec2::new(c.x + r * a.cos(), c.y + r * a.sin()) + }) + .collect() +} + +/// Polygons covering the stroke of `lines` with half-width `hw` (pixels). +pub fn stroke_polygons(lines: &[Polyline], hw: f32) -> Vec> { + let mut out = Vec::new(); + if !(hw.is_finite() && hw > 0.0) { + return out; + } + for pl in lines { + let pts = &pl.points; + let n = pts.len(); + if n < 2 { + continue; + } + let segs = if pl.closed { n } else { n - 1 }; + for i in 0..segs { + let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % n)) else { continue }; + let d = b - a; + if d.length() < 1e-6 { + continue; + } + let nrm = d.normalized().perp() * hw; + out.push(oriented(vec![a + nrm, b + nrm, b - nrm, a - nrm])); + } + // Round joins at interior vertices (all vertices when closed) and round caps at ends. + for (i, &p) in pts.iter().enumerate() { + let interior = pl.closed || (i > 0 && i + 1 < n); + let is_end = !pl.closed && (i == 0 || i + 1 == n); + if interior { + // Skip joins on nearly straight runs (common on flattened curves): the quads + // already overlap seamlessly there. + let prev = pts.get(if i == 0 { n - 1 } else { i - 1 }); + let next = pts.get((i + 1) % n); + if let (Some(&a), Some(&b)) = (prev, next) { + let (u, v) = ((p - a).normalized(), (b - p).normalized()); + // the uncovered outer wedge is about hw · sin(turn) wide + if u.dot(v) > 0.0 && u.cross(v).abs() * hw < 0.05 { + continue; + } + } + } + if interior || is_end { + out.push(oriented(disc(p, hw))); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn all_polygons_positive() { + let pl = Polyline { points: vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0)], closed: false }; + let polys = stroke_polygons(&[pl], 2.0); + assert!(polys.len() >= 4); + assert!(polys.iter().all(|p| signed_area(p) > 0.0)); + } + + #[test] + fn degenerate_inputs() { + assert!(stroke_polygons(&[], 1.0).is_empty()); + let pl = Polyline { points: vec![Vec2::ZERO, Vec2::ZERO], closed: false }; + assert!(stroke_polygons(std::slice::from_ref(&pl), f32::NAN).is_empty()); + // zero-length segment still yields caps, no NaN + let polys = stroke_polygons(&[pl], 1.0); + assert!(polys.iter().flatten().all(|p| p.is_finite())); + } +} diff --git a/crates/xfl/Cargo.toml b/crates/xfl/Cargo.toml new file mode 100644 index 00000000..8fd96658 --- /dev/null +++ b/crates/xfl/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "anicraft-xfl" +description = "AniCraft XFL/FLA import: Animate documents (DOMDocument.xml, library symbols, shape edges) into the AniCraft document model" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[dependencies] +anicraft-geom.workspace = true +anicraft-doc.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 + +[lints] +workspace = true \ No newline at end of file diff --git a/crates/xfl/src/edges.rs b/crates/xfl/src/edges.rs new file mode 100644 index 00000000..4f847fbd --- /dev/null +++ b/crates/xfl/src/edges.rs @@ -0,0 +1,231 @@ +//! XFL shape edges → AniCraft paths. +//! +//! A `DOMShape` stores its outline as `` elements. Each carries an `edges` string of +//! drawing commands in twips (1/20 px): `!x y` moves, `|x y` or `/x y` draws a line, `[cx cy x y` +//! or `]cx cy x y` draws a quadratic curve; `Sn` marks selection state and is skipped. Numbers +//! are decimal, or `#` hex fixed point (signed 24.8). An edge names the fill style on its +//! left (`fillStyle0`) and right (`fillStyle1`) and an optional stroke style. +//! +//! Fill regions are rebuilt per fill style: its right-side edges as drawn, its left-side edges +//! reversed, then chained end to start into closed loops. Strokes are the stroked edges in +//! drawing order. Written from the public description of the format; no Animate code involved. + +use anicraft_geom::{Path, Vec2}; +use std::collections::HashMap; + +/// One segment in pixels: a line (`ctrl` = None) or a quadratic curve. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Seg { + pub from: Vec2, + pub ctrl: Option, + pub to: Vec2, +} + +impl Seg { + fn reversed(self) -> Seg { + Seg { from: self.to, ctrl: self.ctrl, to: self.from } + } +} + +/// An ``: its fill styles (left, right), stroke style and segments. +#[derive(Clone, Debug, Default)] +pub struct Edge { + pub fill_left: u32, + pub fill_right: u32, + pub stroke: u32, + pub segs: Vec, +} + +const TWIPS: f32 = 20.0; +const MAX_SEGS: usize = 2_000_000; + +fn number(s: &[u8], i: &mut usize) -> Option { + while s.get(*i).is_some_and(|c| c.is_ascii_whitespace()) { + *i += 1; + } + let start = *i; + if s.get(*i) == Some(&b'#') { + *i += 1; + let h0 = *i; + while s.get(*i).is_some_and(u8::is_ascii_hexdigit) { + *i += 1; + } + let int = std::str::from_utf8(s.get(h0..*i)?).ok()?; + let mut frac = 0u32; + if s.get(*i) == Some(&b'.') { + *i += 1; + let f0 = *i; + while s.get(*i).is_some_and(u8::is_ascii_hexdigit) && *i - f0 < 2 { + *i += 1; + } + let f = std::str::from_utf8(s.get(f0..*i)?).ok()?; + // One digit means sixteenths of 256ths: "#A.8" = 10.5. + frac = u32::from_str_radix(f, 16).ok()? << (if f.len() == 1 { 4 } else { 0 }); + } + let v = u32::from_str_radix(if int.is_empty() { "0" } else { int }, 16).ok()?; + let fixed = (v.wrapping_shl(8) | frac) as i32; + return Some(fixed as f32 / 256.0); + } + if matches!(s.get(*i), Some(b'-' | b'+')) { + *i += 1; + } + while s.get(*i).is_some_and(|c| c.is_ascii_digit() || *c == b'.' || *c == b'e' || *c == b'E') { + *i += 1; + } + std::str::from_utf8(s.get(start..*i)?).ok()?.parse::().ok().filter(|v| v.is_finite()) +} + +/// Decodes an `edges` attribute into segments (pixels). Stops quietly at anything it can't +/// read, keeping what came before. +pub fn parse(s: &str) -> Vec { + let b = s.as_bytes(); + let mut i = 0; + let mut cur = Vec2::ZERO; + let mut out = Vec::new(); + let pt = |b: &[u8], i: &mut usize| -> Option { Some(Vec2::new(number(b, i)? / TWIPS, number(b, i)? / TWIPS)) }; + while let Some(&c) = b.get(i) { + i += 1; + match c { + b'!' => match pt(b, &mut i) { + Some(p) => cur = p, + None => break, + }, + b'|' | b'/' => match pt(b, &mut i) { + Some(p) => { + out.push(Seg { from: cur, ctrl: None, to: p }); + cur = p; + } + None => break, + }, + b'[' | b']' => match (pt(b, &mut i), pt(b, &mut i)) { + (Some(q), Some(p)) => { + out.push(Seg { from: cur, ctrl: Some(q), to: p }); + cur = p; + } + _ => break, + }, + b'S' => { + while b.get(i).is_some_and(u8::is_ascii_digit) { + i += 1; + } + } + c if c.is_ascii_whitespace() => {} + _ => break, + } + if out.len() >= MAX_SEGS { + break; + } + } + out +} + +/// Hash key for an end point (to 1/100 px, which absorbs the format's rounding). +fn key(p: Vec2) -> (i64, i64) { + ((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64) +} + +fn push_seg(path: &mut Path, s: &Seg) { + match s.ctrl { + Some(q) => path.quad_to(q, s.to), + None => path.line_to(s.to), + }; +} + +/// The region of fill style `style`, as closed loops. +pub fn fill_path(edges: &[Edge], style: u32) -> Path { + let mut segs: Vec = Vec::new(); + for e in edges { + if e.fill_right == style { + segs.extend(e.segs.iter().copied()); + } + if e.fill_left == style { + segs.extend(e.segs.iter().rev().map(|s| s.reversed())); + } + } + let mut by_start: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, s) in segs.iter().enumerate() { + // Zero-length segments carry no area and would confuse the chaining. + if key(s.from) != key(s.to) { + by_start.entry(key(s.from)).or_default().push(i); + } + } + let mut used = vec![false; segs.len()]; + let mut path = Path::new(); + for first in 0..segs.len() { + if used.get(first).copied().unwrap_or(true) || segs.get(first).is_some_and(|s| key(s.from) == key(s.to)) { + continue; + } + let Some(&start) = segs.get(first) else { continue }; + path.move_to(start.from); + let mut at = first; + while let Some(s) = segs.get(at).copied() { + if let Some(u) = used.get_mut(at) { + *u = true; + } + push_seg(&mut path, &s); + if key(s.to) == key(start.from) { + break; + } + let next = by_start.get(&key(s.to)).and_then(|v| v.iter().copied().find(|&j| !used.get(j).copied().unwrap_or(true))); + match next { + Some(j) => at = j, + None => break, + } + } + path.close(); + } + path +} + +/// The stroked edges of stroke style `style`, in drawing order. +pub fn stroke_path(edges: &[Edge], style: u32) -> Path { + let mut path = Path::new(); + let mut last: Option = None; + for e in edges.iter().filter(|e| e.stroke == style) { + for s in &e.segs { + if last.is_none_or(|l| key(l) != key(s.from)) { + path.move_to(s.from); + } + push_seg(&mut path, s); + last = Some(s.to); + } + } + path +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decodes_commands_and_numbers() { + let s = parse("!0 0|200 0[400 0 400 200S2/0 200!#A.8 -20"); + assert_eq!(s.len(), 3); + assert_eq!(s[0].to, Vec2::new(10.0, 0.0), "twips to pixels"); + assert_eq!(s[1].ctrl, Some(Vec2::new(20.0, 0.0))); + assert_eq!(s[2], Seg { from: Vec2::new(20.0, 10.0), ctrl: None, to: Vec2::new(0.0, 10.0) }); + // Hex fixed point: #A.8 = 10.5 twips; a negative two's-complement value. + let mut i = 0; + assert_eq!(number(b"#A.8", &mut i), Some(10.5)); + let mut i = 0; + assert_eq!(number(b"#FFFFFF.80", &mut i), Some(-0.5)); + assert!(parse("!1 2|x").is_empty(), "stops at garbage, never panics"); + } + + #[test] + fn a_square_split_into_edges_with_fills_on_either_side() { + // Top and right drawn clockwise with the fill on the right; bottom and left drawn the + // other way with the fill on the left. Both describe the same square. + let e = |l, r, d: &str| Edge { fill_left: l, fill_right: r, stroke: 1, segs: parse(d) }; + let edges = vec![e(0, 1, "!0 0|200 0|200 200"), e(1, 0, "!0 0|0 200|200 200")]; + let p = fill_path(&edges, 1); + let lines = p.flatten(&anicraft_geom::Affine::IDENTITY, 0.1); + assert_eq!(lines.len(), 1, "one closed loop"); + assert!(lines[0].closed); + assert!(p.contains(Vec2::new(5.0, 5.0), &anicraft_geom::Affine::IDENTITY, anicraft_geom::FillRule::EvenOdd)); + assert!(!p.contains(Vec2::new(15.0, 5.0), &anicraft_geom::Affine::IDENTITY, anicraft_geom::FillRule::EvenOdd)); + let st = stroke_path(&edges, 1); + assert_eq!(st.anchors().len(), 6, "two runs of two segments each, plus their starts"); + assert!(fill_path(&edges, 7).is_empty()); + } +} diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs new file mode 100644 index 00000000..aa59f59a --- /dev/null +++ b/crates/xfl/src/import.rs @@ -0,0 +1,382 @@ +//! XFL document → AniCraft document. +//! +//! What maps (first slice of M4): stage size, frame rate and colour; the first scene's +//! layers (name, colour, visibility, lock, outline; guide layers; folders flattened); frames +//! and keyframes with durations, labels and classic tweens with their ease; shapes (solid, +//! linear and radial fills, solid strokes), groups (flattened), rectangle and oval +//! 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. Everything else (bitmaps, text, sound, masks, motion tweens with property curves, +//! filters) is counted in the report instead of guessed at. + +use crate::edges::{self, Edge}; +use crate::xml::{self, Element as X}; +use anicraft_doc::{ + ColorEffect, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, + SymbolKind, Timeline, Tween, +}; +use anicraft_geom::{Affine, FillRule, Path, Vec2}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::Arc; + +#[derive(Debug, thiserror::Error)] +pub enum XflError { + #[error("{0}")] + Xml(#[from] xml::XmlError), + #[error("{0}")] + Zip(#[from] crate::zip::ZipError), + #[error("I/O: {0}")] + Io(#[from] std::io::Error), + #[error("this isn't an Animate document: {0}")] + NotXfl(String), +} + +/// What the import couldn't bring across, by kind ("3 bitmaps"). +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Report { + pub skipped: BTreeMap, + pub notes: Vec, +} + +impl Report { + 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." + pub fn summary(&self) -> String { + if self.skipped.is_empty() && self.notes.is_empty() { + return "Imported everything in the file.".into(); + } + let mut parts: Vec = self.skipped.iter().map(|(k, n)| format!("{n} {k}")).collect(); + parts.extend(self.notes.iter().cloned()); + format!("Imported. Not yet supported: {}.", parts.join(", ")) + } +} + +/// Reads files of the XFL package by their path inside it (`DOMDocument.xml`, `LIBRARY/x.xml`). +pub type Reader<'a> = dyn Fn(&str) -> Result>, XflError> + 'a; + +const MAX_SYMBOLS: usize = 20_000; +const MAX_LAYERS: usize = 5_000; +const MAX_FRAME: u32 = 100_000; + +struct Builder<'a> { + doc: Document, + read: &'a Reader<'a>, + /// Library item name → symbol id (allocated before timelines are built, so instances can + /// refer to any symbol). + ids: HashMap, + /// Parsed symbol files waiting to be built. + pending: Vec<(SymbolId, String, SymbolKind, X)>, + report: Report, +} + +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)) +} + +fn matrix(el: &X) -> Affine { + let Some(m) = el.child("matrix").and_then(|m| m.child("Matrix")) else { return Affine::IDENTITY }; + let a = Affine { m: [m.f32("a").unwrap_or(1.0), m.f32("b").unwrap_or(0.0), m.f32("c").unwrap_or(0.0), m.f32("d").unwrap_or(1.0), m.f32("tx").unwrap_or(0.0), m.f32("ty").unwrap_or(0.0)] }; + if a.is_finite() { a } else { Affine::IDENTITY } +} + +/// Half the side of the square XFL gradients are defined on, in pixels (16384 twips / 20). +const GRADIENT_HALF: f32 = 819.2; + +/// A fill definition (`SolidColor`, `LinearGradient`, `RadialGradient`) as a paint. +fn paint(def: &X, report: &mut Report) -> Option { + match def.name.as_str() { + "SolidColor" => Some(Paint::Solid(color(def, "color", "alpha"))), + "LinearGradient" | "RadialGradient" => { + let m = matrix(def); + let stops: Vec = def.children.iter().filter(|c| c.name == "GradientEntry").map(|g| GradientStop { offset: g.f32("ratio").unwrap_or(0.0).clamp(0.0, 1.0), color: color(g, "color", "alpha") }).collect(); + if stops.is_empty() { + return None; + } + Some(if def.name == "LinearGradient" { + Paint::Linear { start: m.apply(Vec2::new(-GRADIENT_HALF, 0.0)), end: m.apply(Vec2::new(GRADIENT_HALF, 0.0)), stops } + } else { + let c = m.apply(Vec2::ZERO); + let r = (m.apply_vector(Vec2::new(GRADIENT_HALF, 0.0)).length() + m.apply_vector(Vec2::new(0.0, GRADIENT_HALF)).length()) * 0.5; + Paint::Radial { center: c, radius: r, stops } + }) + } + "BitmapFill" => { + report.skip("bitmap fills"); + None + } + _ => None, + } +} + +/// A stroke definition (`SolidStroke` and friends) as a stroke: weight and its fill colour. +fn stroke(def: &X, report: &mut Report) -> Option { + if !matches!(def.name.as_str(), "SolidStroke" | "DashedStroke" | "DottedStroke" | "RaggedStroke" | "StippleStroke" | "HatchedStroke") { + return None; + } + if def.name != "SolidStroke" { + report.skip("stroke styles drawn as solid"); + } + let width = def.f32("weight").unwrap_or(1.0).clamp(0.05, 1000.0); + let fill = def.child("fill").and_then(|f| f.children.first()); + let c = fill.map_or(Rgba::BLACK, |f| if f.name == "SolidColor" { color(f, "color", "alpha") } else { paint(f, report).map_or(Rgba::BLACK, |p| p.primary_color()) }); + Some(Stroke { color: c, width }) +} + +impl<'a> Builder<'a> { + fn element(&mut self, kind: ElementKind, transform: Affine, color: ColorEffect) -> Arc { + Arc::new(Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform, color, kind }) + } + + /// Shapes for one `DOMShape`: a fill-only shape per fill style (bottom), then a stroke-only + /// shape per stroke style, as Animate draws them. + fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec>) { + let m = parent.mul(&matrix(el)); + let fills: Vec<(u32, Option)> = el.list("fills").iter().map(|f| (f.u32("index").unwrap_or(0), f.children.first().and_then(|d| paint(d, &mut self.report)))).collect(); + let strokes: Vec<(u32, Option)> = el.list("strokes").iter().map(|s| (s.u32("index").unwrap_or(0), s.children.first().and_then(|d| stroke(d, &mut self.report)))).collect(); + let edges: Vec = el + .list("edges") + .iter() + .filter(|e| e.name == "Edge") + .map(|e| Edge { fill_left: e.u32("fillStyle0").unwrap_or(0), fill_right: e.u32("fillStyle1").unwrap_or(0), stroke: e.u32("strokeStyle").unwrap_or(0), segs: e.attr("edges").map(edges::parse).unwrap_or_default() }) + .collect(); + for (index, p) in fills { + let (Some(p), true) = (p, index > 0) else { continue }; + let path = edges::fill_path(&edges, index); + if !path.is_empty() { + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd }), m, ColorEffect::default())); + } + } + for (index, s) in strokes { + let (Some(s), true) = (s, index > 0) else { continue }; + let path = edges::stroke_path(&edges, index); + if !path.is_empty() { + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero }), m, ColorEffect::default())); + } + } + } + + /// Rectangle and oval primitives. + fn primitive(&mut self, el: &X, parent: &Affine, out: &mut Vec>) { + let (x, y) = (el.f32("x").unwrap_or(0.0), el.f32("y").unwrap_or(0.0)); + let (w, h) = (el.f32("objectWidth").unwrap_or(0.0), el.f32("objectHeight").unwrap_or(0.0)); + if !(w > 0.0 && h > 0.0) { + return; + } + let path = if el.name == "DOMOvalObject" { Path::ellipse(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0) } else { Path::rounded_rect(x, y, w, h, el.f32("topLeftRadius").unwrap_or(0.0).max(0.0)) }; + let fill = el.child("fill").and_then(|f| f.children.first()).and_then(|d| paint(d, &mut self.report)); + let stroke = el.child("stroke").and_then(|s| s.children.first()).and_then(|d| stroke(d, &mut self.report)); + if fill.is_some() || stroke.is_some() { + let m = parent.mul(&matrix(el)); + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill, stroke, fill_rule: FillRule::NonZero }), m, ColorEffect::default())); + } + } + + fn instance(&mut self, el: &X, parent: &Affine, out: &mut Vec>) { + let Some(&symbol) = el.attr("libraryItemName").and_then(|n| self.ids.get(n)) else { + self.report.skip("instances of missing symbols"); + return; + }; + let loop_mode = match el.attr("loop") { + Some("play once") => LoopMode::PlayOnce, + Some("single frame") => LoopMode::SingleFrame, + _ => LoopMode::Loop, + }; + let first_frame = el.u32("firstFrame").unwrap_or(0).min(MAX_FRAME); + let mut fx = ColorEffect::default(); + if let Some(c) = el.child("color").and_then(|c| c.child("Color")) { + fx.alpha = c.f32("alphaMultiplier").unwrap_or(1.0).clamp(0.0, 1.0); + if let Some(t) = c.f32("tintMultiplier") { + fx.tint = color(c, "tintColor", "__none"); + fx.tint_amount = t.clamp(0.0, 1.0); + } + } + let m = parent.mul(&matrix(el)); + out.push(self.element(ElementKind::Symbol { symbol, loop_mode, first_frame }, m, fx)); + } + + fn elements(&mut self, list: &[X], parent: &Affine, out: &mut Vec>, depth: usize) { + if depth > 64 { + return; + } + for el in list { + match el.name.as_str() { + "DOMShape" => self.shape(el, parent, out), + "DOMGroup" => { + let m = parent.mul(&matrix(el)); + self.elements(el.list("members"), &m, out, depth + 1); + } + "DOMSymbolInstance" => self.instance(el, parent, out), + "DOMRectangleObject" | "DOMOvalObject" => self.primitive(el, parent, out), + "DOMBitmapInstance" => self.report.skip("bitmaps"), + "DOMStaticText" | "DOMDynamicText" | "DOMInputText" => self.report.skip("text fields"), + "DOMVideoInstance" => self.report.skip("videos"), + _ => self.report.skip("other elements"), + } + } + } + + fn timeline(&mut self, tl: &X) -> Timeline { + let mut layers = Vec::new(); + // Mask layers by their position in the file's layer list (`parentLayerIndex` points at + // a layer's folder or mask; folders are flattened away). + let mut masks: Vec> = Vec::new(); + for l in tl.list("layers").iter().filter(|l| l.name == "DOMLayer").take(MAX_LAYERS) { + masks.push(None); + let kind = match l.attr("layerType") { + Some("folder") => continue, + Some("guide") => LayerKind::Guide, + Some("mask") => LayerKind::Mask, + _ => LayerKind::Normal, + }; + let id = LayerId(self.doc.alloc_id()); + let mut layer = Layer::new(id, l.attr("name").unwrap_or("Layer")); + layer.kind = kind; + if kind == LayerKind::Mask + && let Some(slot) = masks.last_mut() + { + *slot = Some(id); + } + if kind == LayerKind::Normal { + layer.parent = l.u32("parentLayerIndex").and_then(|i| masks.get(i as usize).copied().flatten()); + } + layer.visible = l.bool("visible").unwrap_or(true); + layer.locked = l.bool("locked").unwrap_or(false); + layer.outline = l.bool("outline").unwrap_or(false); + layer.color = color(l, "color", "__none"); + let mut keys = Vec::new(); + for f in l.list("frames").iter().filter(|f| f.name == "DOMFrame") { + let start = f.u32("index").unwrap_or(0).min(MAX_FRAME); + let duration = f.u32("duration").unwrap_or(1).clamp(1, MAX_FRAME); + let mut k = Keyframe::new(start, duration); + k.label = f.attr("name").unwrap_or("").chars().take(256).collect(); + match f.attr("tweenType") { + Some("motion") => { + let acc = f.f32("acceleration").unwrap_or(0.0).clamp(-100.0, 100.0); + k.tween = Some(Tween { easing: if acc == 0.0 { Easing::Linear } else { Easing::Classic(acc) } }); + } + Some("motion object") => self.report.skip("motion tweens (kept as keyframes)"), + Some("shape") => self.report.skip("shape tweens (kept as keyframes)"), + _ => {} + } + let mut els = Vec::new(); + self.elements(f.list("elements"), &Affine::IDENTITY, &mut els, 0); + k.elements = els; + keys.push(Arc::new(k)); + } + if !keys.is_empty() { + layer.keyframes = keys; + } + layer.normalize(); + layers.push(Arc::new(layer)); + } + if layers.is_empty() { + layers.push(Arc::new(Layer::new(LayerId(self.doc.alloc_id()), "Layer 1"))); + } + let mut tl = Timeline { layers }; + // Links that do not form an unbroken run under their mask are dropped. + tl.repair_masks(); + tl + } + + /// Allocates ids for every symbol the document lists, parsing their files. + fn register_symbols(&mut self, root: &X) -> Result<(), XflError> { + let mut seen = HashSet::new(); + for inc in root.list("symbols").iter().filter(|i| i.name == "Include").take(MAX_SYMBOLS) { + let Some(href) = inc.attr("href") else { continue }; + if !seen.insert(href.to_string()) { + continue; + } + let Some(bytes) = (self.read)(&format!("LIBRARY/{href}"))? else { + self.report.skip("missing library files"); + continue; + }; + let item = xml::parse(&bytes)?; + if item.name != "DOMSymbolItem" { + continue; + } + let name = item.attr("name").map(str::to_string).unwrap_or_else(|| href.trim_end_matches(".xml").to_string()); + let kind = match item.attr("symbolType") { + Some("movie clip") => SymbolKind::MovieClip, + Some("button") => SymbolKind::Button, + _ => SymbolKind::Graphic, + }; + let id = SymbolId(self.doc.alloc_id()); + self.ids.insert(name.clone(), id); + self.pending.push((id, name, kind, item)); + } + Ok(()) + } + + fn build_symbols(&mut self) { + for (id, name, kind, item) in std::mem::take(&mut self.pending) { + let timeline = match item.child("timeline").and_then(|t| t.child("DOMTimeline")) { + Some(tl) => self.timeline(tl), + None => Timeline { layers: vec![Arc::new(Layer::new(LayerId(self.doc.alloc_id()), "Layer 1"))] }, + }; + let short = name.rsplit('/').next().unwrap_or(&name).to_string(); + self.doc.library.push(Arc::new(Symbol { id, name: short, kind, timeline })); + } + } +} + +/// Imports an XFL package through `read` (paths inside the package). +pub fn import_with(read: &Reader<'_>) -> 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(), report: Report::default() }; + b.doc.library.clear(); + b.doc.timeline.layers.clear(); + b.doc.stage = Stage { + width: root.f32("width").unwrap_or(550.0).clamp(1.0, 8192.0) as u32, + height: root.f32("height").unwrap_or(400.0).clamp(1.0, 8192.0) as u32, + fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0), + background: color(&root, "backgroundColor", "__none"), + }; + b.register_symbols(&root)?; + b.build_symbols(); + let scenes: Vec<&X> = root.list("timelines").iter().filter(|t| t.name == "DOMTimeline").collect(); + if scenes.len() > 1 { + b.report.notes.push(format!("scenes after the first ({} more)", scenes.len() - 1)); + } + match scenes.first() { + Some(tl) => b.doc.timeline = b.timeline(tl), + None => b.doc.timeline = Timeline { layers: vec![Arc::new(Layer::new(LayerId(b.doc.alloc_id()), "Layer 1"))] }, + } + Ok((b.doc, b.report)) +} + +/// Imports from disk: an XFL folder, its `.xfl` file, or a `.fla` archive. +pub fn import_path(path: &std::path::Path) -> Result<(Document, Report), XflError> { + let meta = std::fs::metadata(path)?; + let is_fla = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("fla")); + if meta.is_file() && is_fla { + if meta.len() as usize > crate::zip::MAX_ENTRY * 4 { + return Err(XflError::NotXfl("the file is too large".into())); + } + let data = std::fs::read(path)?; + let archive = crate::zip::Archive::open(&data)?; + let read = |p: &str| -> Result>, XflError> { Ok(archive.read(p)?) }; + return import_with(&read); + } + let dir = if meta.is_dir() { path.to_path_buf() } else { path.parent().map(std::path::Path::to_path_buf).unwrap_or_default() }; + let read = |p: &str| -> Result>, XflError> { + // Only plain relative paths inside the package. + if p.split('/').any(|c| c == ".." || c.is_empty()) || p.contains(':') { + return Ok(None); + } + let full = dir.join(p); + match std::fs::read(&full) { + Ok(b) if b.len() <= xml::MAX_INPUT => Ok(Some(b)), + Ok(_) => Err(XflError::NotXfl(format!("{p} is too large"))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } + }; + import_with(&read) +} diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs new file mode 100644 index 00000000..c04cb2ea --- /dev/null +++ b/crates/xfl/src/lib.rs @@ -0,0 +1,17 @@ +//! AniCraft XFL import (between `doc` and `engine`): opens Animate documents, as an XFL folder +//! or a `.fla` archive, into the AniCraft document model. +//! +//! Clean room: written from the publicly documented structure of XFL (an XML package: +//! `DOMDocument.xml`, `LIBRARY/*.xml`) and the published ZIP format. No Animate code, and no +//! third-party converter code. The test corpus is self-authored. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod edges; +pub mod import; +pub mod xml; +pub mod zip; + +pub use import::{Report, XflError, import_path, import_with}; + +#[cfg(test)] +mod tests; diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs new file mode 100644 index 00000000..41a077b8 --- /dev/null +++ b/crates/xfl/src/tests.rs @@ -0,0 +1,178 @@ +//! Import tests on a small, self-authored XFL package. + +use crate::import::{XflError, import_with}; +use anicraft_doc::{ElementKind, LayerKind, LoopMode, Paint, Rgba, SymbolKind, evaluate}; +use std::collections::HashMap; + +const DOC: &str = r##" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"##; + +const BALL: &str = r##" + + + +"##; + +fn package() -> HashMap<&'static str, &'static str> { + HashMap::from([("DOMDocument.xml", DOC), ("LIBRARY/Characters/Ball.xml", BALL)]) +} + +fn import(files: &HashMap<&'static str, &'static str>) -> Result<(anicraft_doc::Document, crate::Report), XflError> { + let read = |p: &str| -> Result>, XflError> { Ok(files.get(p).map(|s| s.as_bytes().to_vec())) }; + import_with(&read) +} + +#[test] +fn stage_layers_frames_and_tweens() { + let (doc, report) = import(&package()).unwrap(); + assert_eq!((doc.stage.width, doc.stage.height, doc.stage.fps), (640, 360, 30.0)); + assert_eq!(doc.stage.background, Rgba::hex(0x336699)); + let names: Vec<&str> = doc.timeline.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Ball", "Ground", "Notes"], "folders are flattened away, order kept (top first)"); + let ball = &doc.timeline.layers[0]; + assert_eq!(ball.keyframes.len(), 2); + assert_eq!((ball.keyframes[0].start, ball.keyframes[0].duration), (0, 10)); + assert_eq!(ball.keyframes[0].label, "start"); + assert!(matches!(ball.keyframes[0].tween.map(|t| t.easing), Some(anicraft_doc::Easing::Classic(e)) if e == -50.0)); + assert!(doc.timeline.layers[1].locked); + assert_eq!(doc.timeline.layers[2].kind, LayerKind::Guide); + assert_eq!(doc.frame_count(), 15); + // What couldn't come across is reported, not guessed. + assert_eq!(report.skipped.get("text fields"), Some(&1)); + assert_eq!(report.skipped.get("bitmaps"), Some(&1)); + assert_eq!(report.skipped.get("missing library files"), Some(&1)); + assert!(report.summary().contains("scenes after the first (1 more)")); +} + +#[test] +fn mask_layers_mask_the_layers_that_point_at_them() { + // A mask inside a folder: `parentLayerIndex` counts every layer in the file, folders too. + let shape = r##" + "##; + let layer = |attrs: &str| format!(r#"{shape}"#); + let doc = format!( + r#" + {}{}{}{}"#, + layer(r#"name="Spot" layerType="mask" parentLayerIndex="0""#), + layer(r#"name="Ball" layerType="masked" parentLayerIndex="1""#), + layer(r#"name="Ring" parentLayerIndex="1""#), + layer(r#"name="Sky" parentLayerIndex="0""#), + ); + let doc: &'static str = Box::leak(doc.into_boxed_str()); + let (d, report) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap(); + let l = &d.timeline.layers; + assert_eq!(l.iter().map(|l| l.name.as_str()).collect::>(), ["Spot", "Ball", "Ring", "Sky"]); + assert_eq!(l[0].kind, LayerKind::Mask); + assert_eq!((l[1].parent, l[2].parent, l[3].parent), (Some(l[0].id), Some(l[0].id), None), "in the folder, not masked"); + assert!(report.skipped.keys().all(|k| !k.contains("mask"))); + let dl = evaluate(&d, 0); + assert_eq!(dl.clip_parents.len(), 1); + assert_eq!(dl.items.iter().filter(|i| i.clip == Some(0)).count(), 2); + assert_eq!(dl.items.iter().filter(|i| i.masks == Some(0)).count(), 1); +} + +#[test] +fn symbols_instances_and_the_tween_between_them() { + let (doc, _) = import(&package()).unwrap(); + assert_eq!(doc.library.len(), 1); + let sym = &doc.library[0]; + assert_eq!((sym.name.as_str(), sym.kind), ("Ball", SymbolKind::MovieClip)); + let inst = &doc.timeline.layers[0].keyframes[0].elements[0]; + let ElementKind::Symbol { symbol, loop_mode, first_frame } = &inst.kind else { panic!("an instance") }; + assert_eq!((*symbol, *loop_mode, *first_frame), (sym.id, LoopMode::PlayOnce, 2)); + assert_eq!(inst.transform.m, [2.0, 0.0, 0.0, 2.0, 100.0, 50.0]); + assert_eq!(inst.color.alpha, 0.5); + // Half-way through the tween (eased), the ball is between its two positions. + let dl = evaluate(&doc, 5); + let ball = dl.items.iter().find(|i| matches!(i.fill, Some(Paint::Solid(c)) if c == Rgba::hex(0xff0000))).expect("the ball renders"); + let x = ball.transform.translation().x; + assert!(x > 100.0 && x < 300.0, "{x}"); +} + +#[test] +fn shapes_become_fills_and_strokes() { + let (doc, _) = import(&package()).unwrap(); + let els = &doc.timeline.layers[1].keyframes[0].elements; + assert_eq!(els.len(), 2, "one fill (style 2 has no edges), one stroke"); + let ElementKind::Shape(fill) = &els[0].kind else { panic!() }; + assert_eq!(fill.fill, Some(Paint::Solid(Rgba::hex(0x00aa00)))); + let b = fill.path.bounds(); + assert!((b.min.y - 300.0).abs() < 0.01 && (b.max.x - 640.0).abs() < 0.01 && (b.max.y - 360.0).abs() < 0.01, "{b:?}: twips to pixels"); + let ElementKind::Shape(st) = &els[1].kind else { panic!() }; + assert_eq!(st.stroke.map(|s| (s.color, s.width)), Some((Rgba::hex(0x112233), 3.0))); + assert!(st.fill.is_none()); +} + +#[test] +fn a_fla_archive_imports_the_same() { + let z = crate::zip::tests::make_zip(&[("DOMDocument.xml", DOC.as_bytes(), true), ("LIBRARY/Characters/Ball.xml", BALL.as_bytes(), true)]); + let dir = std::env::temp_dir().join(format!("anicraft-xfl-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fla = dir.join("scene.fla"); + std::fs::write(&fla, &z).unwrap(); + let (doc, _) = crate::import_path(&fla).unwrap(); + assert_eq!(doc.timeline.layers.len(), 3); + assert_eq!(doc.library.len(), 1); + std::fs::remove_file(&fla).ok(); + std::fs::remove_dir(&dir).ok(); +} + +#[test] +fn hostile_packages_fail_cleanly() { + let mut files = package(); + files.insert("DOMDocument.xml", ""); + let (doc, _) = import(&files).unwrap(); + assert!(doc.frame_count() <= 100_001); + files.insert("DOMDocument.xml", ""); + assert!(matches!(import(&files), Err(XflError::NotXfl(_)))); + files.insert("DOMDocument.xml", ""); + assert!(matches!(import(&files), Err(XflError::Xml(_)))); + assert!(import(&HashMap::new()).is_err(), "no DOMDocument.xml"); +} diff --git a/crates/xfl/src/xml.rs b/crates/xfl/src/xml.rs new file mode 100644 index 00000000..3ac1c724 --- /dev/null +++ b/crates/xfl/src/xml.rs @@ -0,0 +1,285 @@ +//! A small, strict-enough XML reader for XFL documents. +//! +//! XFL stores everything that matters in elements and attributes (even shape geometry is 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 +//! element count keep a hostile file from exhausting memory or the stack. Never panics. + +use std::collections::HashMap; + +/// Largest document read (bytes). +pub const MAX_INPUT: usize = 256 * 1024 * 1024; +const MAX_DEPTH: usize = 256; +const MAX_ELEMENTS: usize = 4_000_000; + +#[derive(Debug, Default, Clone)] +pub struct Element { + pub name: String, + pub attrs: HashMap, + pub children: Vec, +} + +impl Element { + pub fn attr(&self, name: &str) -> Option<&str> { + self.attrs.get(name).map(String::as_str) + } + pub fn f32(&self, name: &str) -> Option { + self.attr(name).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) + } + pub fn u32(&self, name: &str) -> Option { + self.attr(name).and_then(|v| v.trim().parse::().ok()) + } + pub fn bool(&self, name: &str) -> Option { + self.attr(name).map(|v| v.trim() == "true") + } + /// The first child named `name`. + pub fn child(&self, name: &str) -> Option<&Element> { + self.children.iter().find(|c| c.name == name) + } + /// Children of the first child named `name` (XFL wraps lists: `…`). + pub fn list(&self, name: &str) -> &[Element] { + self.child(name).map_or(&[], |c| c.children.as_slice()) + } +} + +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum XmlError { + #[error("the XML is too large")] + TooLarge, + #[error("the XML is nested too deeply")] + TooDeep, + #[error("the XML has too many elements")] + TooMany, + #[error("malformed XML at byte {0}: {1}")] + Syntax(usize, &'static str), +} + +struct P<'a> { + s: &'a [u8], + i: usize, + count: usize, +} + +impl P<'_> { + fn err(&self, what: &'static str) -> Result { + Err(XmlError::Syntax(self.i, what)) + } + fn peek(&self) -> Option { + self.s.get(self.i).copied() + } + fn starts(&self, pat: &[u8]) -> bool { + self.s.get(self.i..).is_some_and(|r| r.starts_with(pat)) + } + fn skip_ws(&mut self) { + while self.peek().is_some_and(|c| c.is_ascii_whitespace()) { + self.i += 1; + } + } + /// Skips past `end` (used for comments, CDATA, PIs, doctype). + fn skip_until(&mut self, end: &[u8]) -> Result<(), XmlError> { + let rest = self.s.get(self.i..).unwrap_or_default(); + match rest.windows(end.len()).position(|w| w == end) { + Some(p) => { + self.i += p + end.len(); + Ok(()) + } + None => self.err("unterminated construct"), + } + } + fn name(&mut self) -> Result { + let start = self.i; + while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.' | b':') || c >= 0x80) { + self.i += 1; + } + if self.i == start { + return self.err("expected a name"); + } + 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> { + loop { + while self.peek().is_some_and(|c| c != b'<') { + self.i += 1; + } + if self.starts(b"")?; + } else if self.starts(b"")?; + } else if self.starts(b"")?; + } else if self.starts(b"")?; + } else { + return Ok(()); + } + } + } + fn element(&mut self, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err(XmlError::TooDeep); + } + self.count += 1; + if self.count > MAX_ELEMENTS { + return Err(XmlError::TooMany); + } + if self.peek() != Some(b'<') { + return self.err("expected '<'"); + } + self.i += 1; + let mut el = Element { name: self.name()?, ..Element::default() }; + loop { + self.skip_ws(); + match self.peek() { + Some(b'/') => { + self.i += 1; + if self.peek() != Some(b'>') { + return self.err("expected '>' after '/'"); + } + self.i += 1; + return Ok(el); + } + Some(b'>') => { + self.i += 1; + break; + } + Some(_) => { + let k = self.name()?; + self.skip_ws(); + if self.peek() != Some(b'=') { + return self.err("expected '=' in an attribute"); + } + self.i += 1; + self.skip_ws(); + let q = match self.peek() { + Some(q @ (b'"' | b'\'')) => q, + _ => return self.err("expected a quoted attribute value"), + }; + self.i += 1; + let start = self.i; + while self.peek().is_some_and(|c| c != q) { + self.i += 1; + } + if self.peek().is_none() { + return self.err("unterminated attribute value"); + } + let raw = String::from_utf8_lossy(self.s.get(start..self.i).unwrap_or_default()).into_owned(); + self.i += 1; + el.attrs.insert(k, unescape(&raw)); + } + None => return self.err("unexpected end inside a tag"), + } + } + // Content: children until the matching end tag. + loop { + self.skip_misc()?; + if self.peek().is_none() { + return self.err("missing end tag"); + } + if self.starts(b"') || n != el.name { + return self.err("mismatched end tag"); + } + self.i += 1; + return Ok(el); + } + el.children.push(self.element(depth + 1)?); + } + } +} + +fn unescape(s: &str) -> String { + if !s.contains('&') { + return s.to_string(); + } + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(rest.get(..i).unwrap_or("")); + let tail = rest.get(i..).unwrap_or(""); + let Some(end) = tail.find(';').filter(|e| *e <= 12) else { + out.push('&'); + rest = tail.get(1..).unwrap_or(""); + continue; + }; + let ent = tail.get(1..end).unwrap_or(""); + let ch = match ent { + "lt" => Some('<'), + "gt" => Some('>'), + "amp" => Some('&'), + "quot" => Some('"'), + "apos" => Some('\''), + _ => ent + .strip_prefix("#x") + .or_else(|| ent.strip_prefix("#X")) + .and_then(|h| u32::from_str_radix(h, 16).ok()) + .or_else(|| ent.strip_prefix('#').and_then(|d| d.parse::().ok())) + .and_then(char::from_u32), + }; + match ch { + Some(c) => { + out.push(c); + rest = tail.get(end + 1..).unwrap_or(""); + } + None => { + out.push('&'); + rest = tail.get(1..).unwrap_or(""); + } + } + } + out.push_str(rest); + out +} + +/// Parses a document and returns its root element. +pub fn parse(src: &[u8]) -> Result { + if src.len() > MAX_INPUT { + return Err(XmlError::TooLarge); + } + // 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()?; + if p.peek().is_none() { + return p.err("no root element"); + } + p.element(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn elements_attributes_and_entities() { + let x = br#" + + + + ]]> + text is ignored +"#; + let root = parse(x).unwrap(); + assert_eq!(root.name, "DOMDocument"); + assert_eq!(root.f32("width"), Some(640.0)); + assert_eq!(root.u32("frameRate"), Some(30)); + 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"); + } + + #[test] + fn malformed_input_is_an_error_not_a_panic() { + for bad in [&b""[..], b"<", b"", b" { + data: &'a [u8], + entries: HashMap, +} + +fn u16_at(d: &[u8], i: usize) -> Option { + Some(u16::from_le_bytes(d.get(i..i + 2)?.try_into().ok()?)) +} +fn u32_at(d: &[u8], i: usize) -> Option { + Some(u32::from_le_bytes(d.get(i..i + 4)?.try_into().ok()?)) +} + +impl<'a> Archive<'a> { + pub fn open(data: &'a [u8]) -> Result, ZipError> { + // The end record is in the last 22 + 65535 bytes (it may carry a comment). + let lo = data.len().saturating_sub(22 + 65_535); + let eocd = (lo..data.len().saturating_sub(21)).rev().find(|&i| u32_at(data, i) == Some(0x0605_4b50)).ok_or(ZipError::NotZip)?; + let count = u16_at(data, eocd + 10).ok_or(ZipError::Damaged("end record"))? as usize; + let dir = u32_at(data, eocd + 16).ok_or(ZipError::Damaged("end record"))? as usize; + if count == 0xffff || dir == 0xffff_ffff { + return Err(ZipError::Unsupported("archive".into(), "ZIP64")); + } + let mut entries = HashMap::with_capacity(count.min(100_000)); + let mut i = dir; + for _ in 0..count { + if u32_at(data, i) != Some(0x0201_4b50) { + return Err(ZipError::Damaged("central directory")); + } + let field = |o: usize| u32_at(data, i + o).ok_or(ZipError::Damaged("central directory")); + let short = |o: usize| u16_at(data, i + o).ok_or(ZipError::Damaged("central directory")); + let (flags, method) = (short(8)?, short(10)?); + let (comp, size) = (field(20)? as usize, field(24)? as usize); + let (nlen, xlen, clen) = (short(28)? as usize, short(30)? as usize, short(32)? as usize); + let offset = field(42)? as usize; + let name = data.get(i + 46..i + 46 + nlen).ok_or(ZipError::Damaged("entry name"))?; + let name = String::from_utf8_lossy(name).replace('\\', "/"); + entries.insert(name, Entry { method, flags, comp, size, offset }); + i += 46 + nlen + xlen + clen; + } + Ok(Archive { data, entries }) + } + + pub fn names(&self) -> impl Iterator { + self.entries.keys().map(String::as_str) + } + + /// The bytes of entry `name` (path inside the archive, `/`-separated). + pub fn read(&self, name: &str) -> Result>, ZipError> { + let Some(e) = self.entries.get(name) else { return Ok(None) }; + if e.flags & 1 != 0 { + return Err(ZipError::Unsupported(name.into(), "encryption")); + } + if e.size > MAX_ENTRY || e.comp > MAX_ENTRY { + return Err(ZipError::TooLarge(name.into())); + } + let d = self.data; + if u32_at(d, e.offset) != Some(0x0403_4b50) { + return Err(ZipError::Damaged("local header")); + } + let nlen = u16_at(d, e.offset + 26).ok_or(ZipError::Damaged("local header"))? as usize; + let xlen = u16_at(d, e.offset + 28).ok_or(ZipError::Damaged("local header"))? as usize; + let start = e.offset + 30 + nlen + xlen; + let raw = d.get(start..start + e.comp).ok_or(ZipError::Damaged("entry data"))?; + match e.method { + 0 => Ok(Some(raw.to_vec())), + 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.clamp(1, MAX_ENTRY)).map(Some).map_err(|_| ZipError::Damaged("deflate data")), + _ => Err(ZipError::Unsupported(name.into(), "compression method")), + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// Builds a zip with stored and deflated entries (for tests). + pub fn make_zip(files: &[(&str, &[u8], bool)]) -> Vec { + let mut out = Vec::new(); + let mut dir = Vec::new(); + for (name, body, deflate) in files { + let data = if *deflate { miniz_oxide::deflate::compress_to_vec(body, 6) } else { body.to_vec() }; + let offset = out.len() as u32; + let method: u16 = if *deflate { 8 } else { 0 }; + out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); + out.extend_from_slice(&[20, 0, 0, 0]); + out.extend_from_slice(&method.to_le_bytes()); + out.extend_from_slice(&[0; 8]); // time, date, crc (not checked) + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(&data); + dir.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); + dir.extend_from_slice(&[20, 0, 20, 0, 0, 0]); + dir.extend_from_slice(&method.to_le_bytes()); + dir.extend_from_slice(&[0; 8]); + dir.extend_from_slice(&(data.len() as u32).to_le_bytes()); + dir.extend_from_slice(&(body.len() as u32).to_le_bytes()); + dir.extend_from_slice(&(name.len() as u16).to_le_bytes()); + dir.extend_from_slice(&[0; 12]); + dir.extend_from_slice(&offset.to_le_bytes()); + dir.extend_from_slice(name.as_bytes()); + } + let dir_at = out.len() as u32; + out.extend_from_slice(&dir); + out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(dir.len() as u32).to_le_bytes()); + out.extend_from_slice(&dir_at.to_le_bytes()); + out.extend_from_slice(&[0, 0]); + out + } + + #[test] + fn reads_stored_and_deflated_entries() { + let z = make_zip(&[("DOMDocument.xml", b"", true), ("LIBRARY\\Ball.xml", b"", false)]); + let a = Archive::open(&z).unwrap(); + assert_eq!(a.read("DOMDocument.xml").unwrap().unwrap(), b""); + assert_eq!(a.read("LIBRARY/Ball.xml").unwrap().unwrap(), b"", "backslashes normalised"); + assert_eq!(a.read("missing").unwrap(), None); + } + + #[test] + fn damaged_archives_are_errors() { + assert_eq!(Archive::open(b"not a zip").err(), Some(ZipError::NotZip)); + let mut z = make_zip(&[("a", b"hello", true)]); + let n = z.len(); + // Point the directory past the end. + z[n - 6] = 0xff; + assert!(Archive::open(&z).is_err()); + } +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 00000000..d0de3539 --- /dev/null +++ b/deny.toml @@ -0,0 +1,49 @@ +# cargo-deny policy: every dependency must be permissively licensed, come from crates.io and +# carry no copyleft obligation on AniCraft. Run: cargo deny check licenses bans sources +# (and `cargo deny check advisories` when online). See docs/legal/compliance.md. + +[graph] +# Check every platform we ship (Windows, macOS, Linux, wasm), not just the host. +all-features = false + +[licenses] +# Permissive licenses only. Where a crate offers a choice ("MIT OR GPL"), cargo-deny picks the +# permissive one; nothing in our tree is accepted under a copyleft term. +allow = [ + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "Zlib", + "0BSD", + "BSL-1.0", + "Unicode-3.0", + "Unlicense", +] +confidence-threshold = 0.93 + +# Font licenses are allowed only for the crate that embeds egui's default UI fonts. +[[licenses.exceptions]] +crate = "epaint_default_fonts" +allow = ["OFL-1.1", "Ubuntu-font-1.0"] + +[licenses.private] +# Our own workspace crates are MIT OR Apache-2.0 (checked by `cargo deny` like any other crate). +ignore = false + +[bans] +multiple-versions = "allow" +# Path dependencies inside the workspace have no version; that is fine for unpublished crates. +wildcards = "deny" +allow-wildcard-paths = true + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] + +[advisories] +# Fetched from the RustSec database when online. +yanked = "warn" diff --git a/docs/adr/0001-undo-persistent-snapshots.md b/docs/adr/0001-undo-persistent-snapshots.md new file mode 100644 index 00000000..d36dfb24 --- /dev/null +++ b/docs/adr/0001-undo-persistent-snapshots.md @@ -0,0 +1,51 @@ +# ADR 0001: Undo/redo on persistent (structurally shared) document snapshots + +* Status: accepted (2026-10-28) +* Supersedes: the M0 full-document-clone history + +## Context + +AniCraft must handle large files: Animate projects with hundreds of layers, thousands of +keyframes and hundreds of thousands of element instances once XFL import lands. Undo has to be +exact (it is the user's safety net), memory-bounded, cheap per edit, and it must not slow down +interactive gestures such as dragging. + +## Options considered + +| Option | Exactness | Per-edit cost | Engineering risk | +|---|---|---|---| +| A. Full-document clone per step (M0) | exact by construction | O(document) time and memory | none, but unusable at scale | +| B. Command pattern (each command records its inverse) | only as good as every hand-written inverse | O(change) | high: dozens of commands, each needing a correct inverse, and every new command adds risk | +| C. Diff/patch of serialized states | exact | O(document) to diff | medium; slow on big files | +| **D. Persistent document + snapshot per step** | exact by construction | O(path to the change) | low: one rule (mutate through `Arc::make_mut`) | + +## Decision + +**D.** The document is a persistent tree: `Timeline.layers: Vec>`, +`Layer.keyframes: Vec>`, `Keyframe.elements: Vec>`, +`Shape.path: Arc`, `library: Vec>`. Mutation goes through `Arc::make_mut`, +which copies only the nodes on the path to the change (copy-on-write). + +* **Snapshot** = `Document::clone()` = O(layers + symbols) pointer copies (0.4 µs measured on + a 200k-instance document). +* **Change detection** = `PartialEq` that compares `Arc`s by pointer first (`arc_eq`), so it is + O(changed), not O(document). +* **History** (`engine/src/history.rs`) stores snapshots and an *estimate of unique bytes* per + step (memory not shared with the neighbouring state). It is bounded by a byte budget + (default 512 MB) plus a step cap, evicting the oldest steps first. +* **State ids**: every committed change gets a process-unique `StateId`. Undo returns to the + earlier id. The save point is a state id, so undoing back to the saved state makes the + document clean again. Render caches key on state ids, so undo is a cache hit. +* **Gestures** coalesce a drag (or a slider scrub) into one undo step. +* **Atomic commands**: a failing command restores the pre-command snapshot. That is free with D. + +## Consequences + +* A rule every contributor must follow: never get `&mut` into the document except through + `Arc::make_mut` (`Timeline::layer_mut`, `Layer::keyframe_mut`, + `Keyframe::elements_mut_where`). Touch only what changes. For example, `Layer::normalize` + only un-shares keyframes whose duration actually changes. +* The same sharing makes render-thread hand-off O(1)-ish (ADR 0002) and lets F6 keyframe + copies share elements. +* Measured (release, 50 layers × 200 shapes × 240 frames = 200k instances): edit 0.011 ms, + undo 0.009 ms, about 2.7 KB of history per nudge. diff --git a/docs/adr/0002-render-pipeline.md b/docs/adr/0002-render-pipeline.md new file mode 100644 index 00000000..70cb4557 --- /dev/null +++ b/docs/adr/0002-render-pipeline.md @@ -0,0 +1,45 @@ +# ADR 0002: Render pipeline: background worker, frame cache, band parallelism, culling + +* Status: accepted (2026-10-28) + +## Context + +In M0 the stage rasterized on the UI thread, one shape at a time, with row parallelism only for +big shapes. A synthetic 10k-visible-shape frame took 92 ms at 1080p on 32 threads, and the UI +would freeze for that long on every edit. + +## Decision + +1. **The UI thread never rasterizes.** `engine::render_service::RenderService` owns a worker + thread. The stage asks for a frame by key and keeps showing the newest finished picture, + placed by the stage area it covers so pan and zoom stay smooth, until the new one arrives. + Policy: one *urgent* slot (latest wins, so a drag never builds a backlog) plus a *prefetch* + queue, replaced wholesale. During playback the stage prefetches the next 12 frames. +2. **Frame cache keyed by content.** `frame_key(state id, frame, view, onion)`, LRU-bounded by + bytes (default 768 MB). Undo/redo and looping playback are cache hits. +3. **Two-phase, band-parallel rasterization** (`render::render`): + * Phase 1, parallel over items: cull by control-point bounds, flatten, stroke and build the + shader. Display-list order is preserved. + * Phase 2, parallel over 32-row bands: each band rasterizes every op touching it, in order, + with one reused coverage buffer. Each row belongs to exactly one band, so output is + **bit-identical** to a serial render (this keeps the oracle deterministic). +4. **Culling before flattening**, using conservative control-point bounds. +5. **Cheap hit testing**: a bounding-box test rejects items before any curve is flattened. The + session caches the display list per `(state, frame)`. +6. **Parallel PNG-sequence export** across frames (same bytes as serial export). + +## Measured (release, 32 threads, 50 layers × 200 shapes, ≈9.9k visible shapes) + +| Metric | Before | After | +|---|---|---| +| 1080p frame | 92.5 ms | 16.5 ms | +| 400% zoom frame (9.2k culled) | 58.1 ms | 10.9 ms | +| Hit test | n/a | 51 µs | + +## Consequences / next + +* GPU renderer (M3) plugs in behind the same `FrameJob → FrameImage` contract and is checked + against this CPU oracle. +* Further CPU wins, measured before adopting: a flatten cache keyed by `(Arc, transform)` + for static shapes during playback; sparse-strip coverage for very large shapes; SIMD + compositing. diff --git a/docs/adr/0003-file-format-v2.md b/docs/adr/0003-file-format-v2.md new file mode 100644 index 00000000..ad65ea51 --- /dev/null +++ b/docs/adr/0003-file-format-v2.md @@ -0,0 +1,34 @@ +# ADR 0003: `.anicraft` v2: SVG path strings, shared path table, streaming read + +* Status: accepted (2026-10-28) + +## Context + +Measuring before optimizing paid off here. The v1 writer turned an 86 MB in-memory stress +document into **782 MB** of JSON (925 ms to save, 633 ms to load). Two causes: paths shared in +memory across keyframes were repeated in every keyframe, and paths were written as verbose +tagged JSON. + +## Decision + +* `Path` serializes as compact SVG path data (`"M0 0L10 0C…Z"`) with shortest round-trip + floats. The parser is strict, bounded and never panics. +* Shared paths are written once in a top-level `paths` table; shapes store an index. + `path_table::build_table` walks the document first, so the table precedes the document in the + file. The reader streams in one pass and resolves references to shared `Arc`s, which + **restores in-memory sharing on load**. +* Small files (< 1 MB) are pretty-printed for humans and diffs; large files are compact. +* v1 files (inline legacy paths) still load; newer-than-supported versions are refused. + +## Measured (same stress document) + +| | v1 | v2 | +|---|---|---| +| File size | 782 MB | 65 MB | +| Save | 925 ms | 118 ms | +| Load | 633 ms | 142 ms | + +## Next + +A zip container for embedded media (M2); optional binary encoding if profiling shows JSON +parsing dominates on real XFL-imported files. diff --git a/docs/adr/0004-destructive-actions.md b/docs/adr/0004-destructive-actions.md new file mode 100644 index 00000000..356c3bff --- /dev/null +++ b/docs/adr/0004-destructive-actions.md @@ -0,0 +1,35 @@ +# ADR 0004: Destructive actions: tiered confirmation, enforced in the engine + +* Status: accepted (2026-10-28) + +## Context + +Requirement from the project lead: destructive actions must always have a confirmation and +must never be a single action away. The users are artists in a flow state, often driving the +app from the keyboard. + +## Options considered + +| Option | Safety | Flow | +|---|---|---| +| A. Confirm every destructive command (including deleting a shape) | high on paper; in practice users learn to click through constant dialogs ("dialog blindness"), which erodes it | poor: a modal on the most frequent edits | +| B. No confirmations, rely on undo | fine for undoable edits; **fails** for irreversible loss (discarding unsaved work, overwriting files) | best | +| **C. Tiered** (see `product-principles.md`) | irreversible loss always guarded; large undoable deletions guarded by default; routine edits protected by undo with a visible hint | good | + +## Decision + +**C.** Confirmation rules live in the engine (`engine/src/confirm.rs`, `Session::confirmation`), +not the UI, so every front end gets the same safety: + +* The desktop app shows a dialog for both guarded tiers. For irreversible actions the + destructive button must be clicked; Enter does nothing, Esc cancels. +* Irreversible commands are **refused by the engine** unless the params include + `"confirm": true`. This protects agents and scripts too. +* Closing the window with unsaved changes asks Save / Don't Save / Cancel. +* Routine deletions report "Ctrl+Z to undo" in the status bar. + +## Consequences + +* New commands that can discard content must add a rule to `confirm.rs` and a test. +* "Don't ask again" covers only the undoable tier and lasts for the session; it becomes a + preference when the settings system lands. diff --git a/docs/adr/0005-typography-and-fonts.md b/docs/adr/0005-typography-and-fonts.md new file mode 100644 index 00000000..d4ef71ec --- /dev/null +++ b/docs/adr/0005-typography-and-fonts.md @@ -0,0 +1,48 @@ +# ADR 0005: Typography roles (prose vs data) and UI typefaces + +* Status: accepted (2026-10-28) + +## Context + +* The project lead wants monospace type where the UI is "technical" (timeline ruler, seconds, + readouts), as pro audio and video tools do, but not in dialog prose. We take the idea only, + not any vendor's typeface. +* The fonts must be **permissive in use**, and either widely available as system fonts or small + enough to bundle. + +## Decision 1: semantic type roles, enforced + +`theme::Type` defines ten roles. The family follows the *kind of text*: **data** +(numbers, timecode, rulers, measurements, shortcut keys, paths, preformatted text) is +monospace; **prose** (titles, headings, names, labels, captions, menus, buttons, dialog text) +is proportional. Mixed lines split label and value. Panels use `theme::text` / +`theme::font` / `theme::with_type` only; `guidelines_tests` fails the build on raw font +families or sizes outside `theme.rs`. Rules and examples: `docs/ui-guidelines.md`. + +## Decision 2: typefaces + +| Option | Licence | Footprint | Consistency | Verdict | +|---|---|---|---|---| +| System fonts (Segoe UI / Consolas, SF / SF Mono, DejaVu…) | Proprietary on Windows/macOS: may be *used* through the OS, but not bundled | 0 KB | Different metrics on every OS: monospace widths, layouts and screenshots change per machine | No: inconsistent; tests and docs can't be pixel-stable | +| egui defaults (Ubuntu Light + Hack, + Noto Emoji, emoji-icon-font) | UFL 1.0, MIT/Bitstream Vera, OFL, MIT: permissive in use | about 1.35 MB, already embedded | Same everywhere | **Fallback**: always present, guarantees glyph coverage | +| **Inter + JetBrains Mono** | SIL OFL 1.1 (free for any use, including commercial, embedding and redistribution; no reserved font names) | 402 KB + 264 KB ≈ 0.65 MB (can subset further) | Same everywhere; the PhotoCraft pair, so the Craft family looks consistent | **Primary** | + +Both are among the most widely used open UI and code typefaces, and both are designed for +screens. JetBrains Mono has clear 0/O and 1/l/I distinctions, which suits frame numbers and +values. + +## How they are delivered + +As in PhotoCraft: **no font files are committed.** `build.rs` reads the optional +`CRAFT_FONTS_DIR` (a checkout of the shared craft-fonts repository) and embeds +`Inter-Regular.ttf` and `JetBrainsMono-Regular.ttf` when present. Official releases build with +it. Without it the app uses the egui defaults and still works (CI, Craft Anything checks, +contributors). Help › About shows which typefaces are active. + +## Consequences + +* Release packaging ships `OFL-Inter.txt` and `OFL-JetBrainsMono.txt` from craft-fonts next to + the binary (`docs/legal/compliance.md`, release checklist). +* Footprint budget for embedded fonts: ≤ 2.5 MB total (today 2.0 MB with fallbacks). A later + `slim-fonts` build can drop the egui text fonts once craft-fonts is mandatory for releases. +* Changing typefaces touches only `theme::font` and `build.rs`. diff --git a/docs/adr/0006-platforms-and-edit-latency.md b/docs/adr/0006-platforms-and-edit-latency.md new file mode 100644 index 00000000..d74ade53 --- /dev/null +++ b/docs/adr/0006-platforms-and-edit-latency.md @@ -0,0 +1,56 @@ +# ADR 0006: Platform layer (macOS, Windows, Linux) and stage edit latency + +* Status: accepted (2026-10-28) + +## 1. Edit latency: the "drag commits after a pause" report + +**Finding: not intentional, and not how the target product behaves.** Animate moves artwork live +under the pointer. Two causes, both by-products of ADR 0002's optimizations: + +1. **Missing repaint (the real bug).** egui repaints only on demand. A drag edit applied late in + a frame (after the stage had drawn) was shown only when the *next* event arrived (pointer + motion, hover timer). When the pointer paused, the last move "committed" after an unrelated + timeout. Fix: the shell requests a repaint whenever the document revision changes, and the + stage now renders *after* tool input in the same frame. +2. **Background-only rendering.** Every frame went through the worker thread, so even cheap + edits showed the previous picture for a frame or two. Fix: an adaptive policy, switchable + (View › Stage Rendering, and Preferences): + +| Mode | Edits | Navigation and playback | When to use | +|---|---|---|---| +| **Auto** (default) | Rendered immediately on the UI thread (row-parallel) while the last frame cost ≤ 12 ms; otherwise in the background, with a vector **outline preview** of the moving selection | Background worker + frame cache + look-ahead | Everyone | +| Immediate | Always immediately | Background | Fast machines, small scenes | +| Background | Always background (with outline preview) | Background | Huge scenes, weak CPUs | + +The CPU renderer stays the oracle; only *when* it runs changes. + +## 2. Platform layer (`src/platform.rs`) + +The policy is one shell with platform decisions isolated in one module, rather than three UIs. + +| Concern | macOS | Windows | Linux / BSD | +|---|---|---|---| +| Shortcuts | `Ctrl` in the registry = **⌘**; labels use Apple order and glyphs (⇧⌘S), or "Shift+Cmd+S" when the font lacks them (checked at runtime) | Ctrl labels | Ctrl labels | +| Application menu | **AniCraft** menu: About, Settings… (⌘,), Quit (⌘Q) | File › Exit (Ctrl+Q), Edit › Preferences… (Ctrl+U, as in Animate) | as Windows | +| Window chrome | Unified title bar: full-size content view, title hidden, menu row inset for the traffic lights | Native frame | Native frame (X11 or Wayland chosen by winit; app id `anicraft` for window rules and docks) | +| File dialogs | Native panels (rfd) | Common dialogs (rfd) | **XDG desktop portal** (rfd). A Preferences switch falls back to a built-in path field on desktops without a portal | +| GPU backend | wgpu → Metal | wgpu → DX12/Vulkan | wgpu → Vulkan; **automatic retry with OpenGL** (glow) if wgpu cannot start (VMs, old GPUs, missing drivers); `--renderer gl` / `ANICRAFT_RENDERER` to force | +| Settings folder | ~/Library/Application Support/AniCraft | %APPDATA%\AniCraft | $XDG_CONFIG_HOME/anicraft | +| Fonts | Bundled (ADR 0005); any installed family selectable in Settings (fontdb scans /System/Library/Fonts, ~/Library/Fonts) | Bundled; Windows\Fonts selectable | Bundled; fontconfig directories selectable | +| HiDPI | Retina scale from winit | Per-monitor DPI | Fractional scaling (Wayland) from winit; Interface scale preference on top | + +### Not done yet (needs native APIs or real-machine testing) + +* **Native macOS menu bar (NSMenu).** It needs `muda` (MIT/Apache, not in the offline cache) or + Objective-C calls behind `unsafe`, which policy allows only in an isolated crate (as with + PhotoCraft's tablet crate). Planned as `crates/macos` (M8). Until then the menu lives in the + window, following Mac conventions. +* CI on macOS and Linux runners (build, tests, `--screenshot` under Xvfb/Wayland headless). + **This build was verified on Windows only.** +* Linux performance profiling across Mesa/NVIDIA and X11/Wayland; Intel Mac and Apple Silicon + numbers for `docs/performance.md`. + +## Consequences + +* New UI code never branches on the OS itself; it asks `platform::`. +* Shortcut labels in menus, the palette and the F1 sheet go through `platform::shortcut_label`. diff --git a/docs/adr/0007-tiled-stage-rendering.md b/docs/adr/0007-tiled-stage-rendering.md new file mode 100644 index 00000000..9424fb82 --- /dev/null +++ b/docs/adr/0007-tiled-stage-rendering.md @@ -0,0 +1,49 @@ +# ADR 0007: Tiled stage rendering with batched, cached tiles + +* Status: accepted (2026-10-28) +* Extends: ADR 0002 (render pipeline), ADR 0006 (edit latency) + +## Context + +Reported: panning reveals a blank stage that fills in shortly after. Cause: the stage rendered +exactly the visible part of the stage as one picture. Any pan exposed pixels that had never been +rendered, and the new picture came one or more frames later. It wasn't CPU speed as such: any +renderer that draws only the viewport shows this. + +## Options considered + +| Option | Pan | Zoom | Memory | Verdict | +|---|---|---|---|---| +| Render the whole stage every time | never blank | re-render everything | huge at high zoom (a 1080p stage at 800% is 60 MP) | no | +| Overscan the viewport by a margin | blank after a large pan | re-render everything | moderate | half a fix | +| **Tiles on a fixed grid per zoom level, cached** | pans reuse tiles; the margin ring is prefetched | old tiles shown scaled until new ones arrive | bounded by an LRU | **chosen** (the approach used by maps and big-canvas editors) | + +## Decision + +* The stage is cut into **512 × 512 device-pixel tiles** on a grid anchored at stage (0, 0) for + the current zoom. Each tile is a `FrameJob` keyed by (state, frame, tile transform, size, + onion). +* **Batching.** Each UI frame asks for all missing visible tiles in one `request_batch`. + The worker takes up to 32 jobs, **evaluates the scene once per (state, frame, onion)** and + renders the tiles in parallel. Newer batches replace pending ones (latest wins). Edits made + during a frame are already batched: the stage renders once per frame from the final + document state, never per command. +* **Look-ahead.** The ring of tiles around the view (or, during playback, the next 12 frames' + visible tiles) goes to the prefetch queue, so normal pans reveal tiles that are already done. +* **No blank stage.** While tiles are missing, tiles from earlier zoom levels or states that + cover the area are drawn underneath, scaled. Edits still render immediately (ADR 0006), now + as one parallel batch of the visible tiles. +* **Seamless.** The stage origin is snapped to whole device pixels, so tile edges land on pixel + boundaries. A test checks that stitched tiles match a single full render to ≤ 1/255 per + channel, with differences rare: float rounding differs at anti-aliased edges when coordinates + are offset. Each tile is itself deterministic. +* **Bounded memory.** At most 192 tile textures (about 1 MB each) on the GPU, least recently + used first out. The render cache is still LRU and byte-bounded (768 MB). +* **Honest timing.** The status bar shows wall-clock time for the view (tiles render in + parallel), and that number drives Auto mode's immediate-vs-background choice. + +## Consequences + +* The GPU renderer (M3) keeps the same contract: tiles in, textures out. +* Next: drop tiles more than two zoom levels away early, and use lower-resolution + "preview" tiles first when zooming far out on huge documents. diff --git a/docs/adr/0008-visual-language.md b/docs/adr/0008-visual-language.md new file mode 100644 index 00000000..ef40fdfa --- /dev/null +++ b/docs/adr/0008-visual-language.md @@ -0,0 +1,77 @@ +# ADR 0008: Visual language — graphite, geometric, colour where it means something + +* Status: accepted (2026-10-29), revised the same day (see "Revision 1") +* Extends: ADR 0005 (typography and fonts), `docs/ui-guidelines.md` + +## Context + +The project lead asked for a more modern look: clean with a brutalist edge, gray and deep-gray +palettes, vibrant colour for things like timeline blocks, square boxes and buttons, borders where +they separate layout (not on every button), and accessible controls with click targets that are +not too small. Functionality must not change. + +The first shell used rounded corners, outlined buttons, a blue-gray palette, all-caps panel +headings and 22 px controls. It read as a generic dark toolkit theme, and several targets (layer +toggles 18 px, timeline icons 26 × 22, small buttons) were below WCAG 2.5.8's 24 px minimum. + +## Decision + +1. **Graphite neutrals** in five steps (`chrome` → `panel` → `panel_alt` → `header` → `hover`), + with inset `field`s darker than the panel. The artwork stays the most colourful thing on the + stage. +2. **Vibrant colour is spent in one place, the timeline, and always carries meaning**: mint + `span` = frames with artwork, violet `tween` = classic tween, graphite `span_empty` = empty, + red `playhead`. Marks on blocks (keyframe dots, tween arrows, labels) are `ink`, so they keep + ≥ 4.5:1 contrast. Cobalt `accent` is selection, focus and the active tool, and nothing else. +3. ~~Square everywhere, with hard offset shadows.~~ Replaced by revision 1: corners by role. +4. **Borders separate layout, not widgets**: panel edges, section headers, the timeline's + layer list and grid, popups. Buttons are flat fills; hover lightens them; pressed and + keyboard-focused widgets get a 2 px accent ring (egui styles focus as "active"). Checkboxes + and radio buttons are the exception: they keep a `control_edge` so the off state is visible. +5. **Targets**: `TARGET` = 28 px minimum, tools 40 × 40, timeline rows 28, layer toggles + 24 × 24. Timeline frame cells (12 px wide) are a dense-data exception; the ruler, rows and + keyboard offer larger ways to reach the same frames. +6. **Sentence-case headings** in bold, with a short accent bar for dock sections, instead of + all-caps labels. + +## Revision 1 (2026-10-29): selective geometry, sections, Lucide icons + +Feedback: squaring off everything is as indiscriminate as rounding everything. The geometric +look should be selective, as in well-designed audio software: rectangular controls and round +dials, with softer corners where a surface floats. Also: sections in Preferences only differed +from their content by indentation; they need a rule and should fold. And icons should come from +a mature open set. + +* **Corners by role** (`theme.rs` › `SQUARE`, `radius_control`, `radius_menu`, + `radius_window`): structure square (panels, dock bands, timeline grid and blocks, selections, + stage); controls 3 px (buttons, fields, tools, list highlights, swatches, playhead flag); + menus and tooltips 6 px; dialogs and windows 10 px. Round only where the thing is round + (keyframe dots, dials). +* **Depth instead of hard shadows** for floating surfaces: a tight, downward, soft shadow. +* **Collapsible sections** (`theme::section`): `Band` for dock sections, `Rule` (title plus a + horizontal rule across the row) for groups in Preferences, Properties and the shortcut sheet. + Whole-row target, keyboard focusable, exposed to assistive technology as a collapsing header. +* **Lucide icons** (ISC). Rendered by parsing the SVGs with a new full SVG path-data reader in + `geom` (`geom::svg`, all commands including elliptical arcs, from the W3C SVG spec) and + stroking them as vectors. Rejected: an SVG rasterizer crate (resvg and friends add a large + dependency tree to a build we keep small), and an icon font (glyph-based, no mirroring, + harder to keep only the icons we use). The SVG reader is also the basis for SVG import (M4). + +All of it lives in `src/theme.rs` and `src/icons.rs`. `guidelines_tests` fails the build on raw colours or radii +outside the theme, and checks the palette's contrast ratios and the target minimum. + +## Alternatives considered + +* **Keep the rounded, outlined look and only recolour.** Rejected: the brief asks for square, + border-light; and outlines on every button add noise without adding information. +* **A single neon accent on near-black.** Rejected: it is a cliché of current dark UIs, and one + accent cannot tell artwork, tween and selection apart on the timeline. +* **Layer colours as span colours.** Rejected for now: span colour already means state + (artwork / tween / empty), which Animate users read at a glance; layer identity stays in the + row's edge bar. + +## Consequences + +* The timeline shows fewer rows at the same height (28 px rows); the default timeline height + grew to keep five layers visible. +* Any new colour or radius needs a token, and must pass the contrast test where it holds text. diff --git a/docs/adr/0009-xfl-import.md b/docs/adr/0009-xfl-import.md new file mode 100644 index 00000000..f640d44f --- /dev/null +++ b/docs/adr/0009-xfl-import.md @@ -0,0 +1,48 @@ +# ADR 0009: XFL / FLA import + +* Status: accepted (2026-10-29) +* Relates to: roadmap M4 (the project lead's first interchange priority), ADR 0003 (file format) + +## Context + +Artists coming to AniCraft have their work in Animate documents: `.fla` files (a zip archive) +or `.xfl` packages (the same content as a folder). Opening them is the first interchange +priority. The format is an XML package: `DOMDocument.xml` (stage, scenes, layers, frames, +elements) and `LIBRARY/*.xml` (symbols), with shape geometry encoded as edge strings. + +## Decision + +1. **A separate crate, `anicraft-xfl`**, between `doc` and `engine`. It depends only on `doc`, + `geom` and `miniz_oxide` (already in the tree through `png`), so the parser is isolated, + fuzzable and testable on its own, and the engine just calls it. +2. **Own XML and zip readers.** No XML or zip crate is available offline, and XFL needs little: + elements and attributes (geometry lives in attributes), and stored/deflate zip entries. Both + readers are small, bounded (size, depth and element-count limits; zip-bomb caps) and never + panic. A full XML crate can replace ours later without touching the mapping. +3. **Clean room.** Written from the publicly documented structure of XFL and the published ZIP + specification (PKWARE APPNOTE). Shape fills are rebuilt from the edges' left/right fill + styles by chaining segments into closed loops. No Animate code, no third-party converter + code. The test corpus is self-authored. +4. **One entry point: `file.open`.** It detects `.fla`, `.xfl` and XFL folders, so menus, the + palette, the command line and agents all import the same way, and it inherits the + unsaved-work confirmation. **An imported document is untitled**: Save asks for a new + `.anicraft` name and can never write over the Animate file. +5. **Report, don't guess.** Anything not yet mapped (bitmaps, text, sound, masks, motion + tweens with property curves, shape tweens, filters, extra scenes) is counted and shown in + the status bar after opening ("Imported. Not yet supported: 2 bitmaps, 1 text field."). + +## What maps in this first slice + +Stage size, frame rate and colour; the first scene; layers (name, colour, visible, locked, +outline, guide; folders flattened); keyframes with durations and labels; classic tweens with +their ease; shapes with solid, linear and radial fills and solid strokes (other stroke styles +drawn solid); groups (flattened); rectangle and oval primitives; symbol instances with matrix, +alpha, tint, loop mode and first frame; library symbols (graphic, movie clip, button) with their +own timelines, nested to any depth. + +## Consequences + +* 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 + tweens, more scenes, and a corpus of larger self-authored files. diff --git a/docs/adr/0010-mask-layers.md b/docs/adr/0010-mask-layers.md new file mode 100644 index 00000000..135fb31c --- /dev/null +++ b/docs/adr/0010-mask-layers.md @@ -0,0 +1,43 @@ +# ADR 0010: Mask layers + +* Status: accepted (2026-10-30) +* Relates to: roadmap M2 (mask layers) and M4 (XFL masks), ADR 0002 (render pipeline), ADR 0003 + (file format), ADR 0009 (XFL import) + +## Context + +Masks are one of the most used effects in 2D animation: a shape on one layer reveals only that +area of the layers under it (spotlights, windows, wipes, text reveals). Artists coming from +Animate expect the same model: a mask layer with one or more masked layers indented under it. +Imported Animate files use masks often. + +## Decision + +1. **Model.** `LayerKind::Mask`, and an optional `Layer::parent` (the mask a layer is masked + by). This is the same parent link the XFL format uses, so layer folders can reuse it later. + The invariant (a masked layer is a normal layer in an unbroken run directly under its mask) + lives in one place, `Timeline::repair_masks`, run after layer edits, on load and on import. + Invalid links are dropped, never trusted. Files stay v2: the field is optional and older + files load unchanged. +2. **Evaluation stays pure.** `evaluate` emits clips into the display list: one per visible mask + layer per timeline instance, nested in the enclosing clip (so masks inside symbols work). + Masked items carry `clip`; the mask's own items carry `masks` and are never painted. A + hidden mask masks nothing. +3. **Rendering.** A clip is the anti-aliased union of its mask fills, intersected with its + parent clip. Strokes and opacity on mask artwork are ignored, as animators expect. Each + render band computes a clip at most once, on first use. Clipped draws are bounded by their + clip, so masks also cull. An empty mask hides everything under it. +4. **The mask always applies (what you see is what you export).** Animate shows the mask effect + only while both layers are locked, which makes the stage disagree with the output. AniCraft + always applies it, on the stage and in every export. To keep the mask editable, an unlocked + mask layer shows its shapes' edges in the layer colour, and they can be picked and reshaped. + Locking the mask hides the edge. Masked-away parts of shapes cannot be picked. +5. **Moving layers.** A layer moved in under a mask joins it, a layer moved out leaves it, and + a mask layer moves with its whole group (stepping over a neighbouring group as a unit). + +## Consequences + +* The stage never disagrees with the export, and there is no lock-to-preview step to learn. + Artists used to that step lose nothing: locking still works and also hides the edge. +* A future GPU renderer must implement the same clip semantics; the CPU tests are the oracle. +* Folders can reuse `parent` without a format change. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 00000000..ba4293f4 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,187 @@ +# AniCraft architecture + +## 1. Philosophy + +1. **The document is data; time is a function.** A document is an immutable-by-convention tree + of plain structs (stage, timelines, layers, keyframes, elements, symbols). Nothing animates by + mutating state: the picture at frame *f* is `evaluate(document, f) -> DisplayList`, a pure + function. Playback, scrubbing, export, onion skin and tests are all calls to that function. +2. **One oracle renderer.** The CPU renderer is deterministic and is the reference. Faster + renderers (wgpu, M3) must match it within a tolerance in golden tests. Agents and CI trust + CPU pixels. +3. **Everything is a command.** Every user-visible action is a `CommandSpec` in the engine + (id, label, menu path, shortcut, params doc, `run`). The egui shell, the CLI, the JSON-lines + channel and (M2) the MCP server dispatch the same ids, so headless parity holds by + construction. Menus are generated from the registry. +4. **Thin UI.** The egui layer holds only view state (zoom, pan, active tool, panel sizes, + hover). It reads the session and emits commands. No document logic lives in the UI. +5. **Layered crates, enforced.** A crate depends only on lower layers. Nothing below the shell + knows about egui, winit or the file dialog. +6. **Never crash.** Errors are values. Commands validate params; recursion (nested symbols) is + depth-limited; allocations sized by input are capped. +7. **Pay for what changes.** Cache by revision: the stage texture is re-rendered only when the + document revision, frame, zoom or viewport changes. Rasterize only shape bounding boxes, in + parallel rows. + +## 2. Crate map + +```text +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 + 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 + cli L4 `anicraft-cli`: info / render / render-seq / commands / run / serve (JSON-lines) + src/ L5 egui shell: menus (from registry), tools, stage, timeline, properties, library + docs/ requirements, architecture, roadmap +``` + +| Layer | Crate | May depend on | +|---|---|---| +| L0 | `anicraft-geom` | std, serde | +| L1 | `anicraft-doc` | geom | +| L2 | `anicraft-render` | geom, doc, rayon, png | +| L3 | `anicraft-engine` | geom, doc, render, serde_json | +| L4 | `anicraft-cli` | engine (+ lower) | +| L5 | `anicraft` (shell) | engine (+ lower), eframe/egui | + +Planned crates: `gpu` (L2, wgpu renderer), `io` (L3, XFL/SVG/Lottie/GIF), `audio` (L2), +`automation` (L4, MCP), `testkit`. + +## 3. Document model (`anicraft-doc`) + +```text +Document +├── stage: width, height, fps, background +├── timeline: Timeline (main scene; scenes list arrives in M2) +│ └── layers: [Layer] (index 0 = top of the stack, as in the timeline panel) +│ ├── name, visible, locked, outline, kind (Normal | Guide | Mask | Folder) +│ └── keyframes: [Keyframe] (sorted by start, spans do not overlap) +│ ├── start, duration (frames covered by this keyframe) +│ ├── elements: [Element] +│ │ ├── Shape { path, fill: Paint?, stroke: Stroke?, transform } +│ │ └── Symbol instance { symbol id, transform, color effect, loop mode, first frame } +│ └── tween: Tween? { kind: Classic | Shape, easing: Easing } +└── library: [Symbol { id, name, kind: Graphic | MovieClip | Button, timeline }] +``` + +### Evaluation + +`evaluate(doc, frame) -> DisplayList` walks layers bottom to top. For each visible layer it finds +the keyframe covering the frame. If that keyframe has a tween and a following keyframe exists, it +computes `t = ease((frame - start) / duration)` and interpolates element *i* of both keyframes +when they are compatible: + +* **Transforms** are decomposed into translation, scale, rotation and skew and interpolated + component-wise (rotation along the shortest arc), so a rotating tween does not shear like a + naive matrix lerp would. +* **Colour effects** (alpha multiplier, tint) and **paints** interpolate linearly in + straight-alpha sRGB, like the reference tools. +* **Shape tweens** interpolate path points when both paths have the same command structure + (M2 adds correspondence via shape hints). + +Symbol instances recurse into the symbol's timeline at the local frame given by the loop mode +(`Loop`, `PlayOnce`, `SingleFrame`) and the first frame. Recursion is limited to depth 32, so a +cyclic library in a malformed file renders what it can instead of overflowing the stack. + +### Easing + +`Easing` is `Linear`, `QuadIn/Out/InOut`, `CubicIn/Out/InOut`, `Classic(strength −100…100)` +(the traditional single-slider ease) or `CubicBezier(x1, y1, x2, y2)` solved with Newton +iterations and a bisection fallback, the same model CSS uses. + +## 4. Rendering (`anicraft-render`) + +```text +DisplayList ──► for each item: + flatten Bézier path under (view × item) transform, tolerance 0.1 px + ├─ fill: lines ──► signed-area coverage accumulator (bbox-sized) + └─ stroke: polylines ──► stroker (segment quads + round joins/caps) ──► accumulator + coverage ──► fill rule (non-zero / even-odd) ──► paint shader ──► src-over blend + (rows of the bbox in parallel with rayon) +``` + +* **Coverage accumulation.** Each line adds signed area to a per-pixel accumulation buffer; + a prefix sum along each row gives exact analytic coverage, with no supersampling. Lines are + clipped against the buffer's x range: the part left of it collapses onto the left edge, which + keeps winding correct. Cost is proportional to edge length plus bbox area. +* **Fill rules.** Non-zero is `min(1, |w|)`; even-odd folds the accumulated winding with a + triangle wave. Both are exact for non-overlapping edges inside a pixel. +* **Paints.** Solid, linear and radial gradients with pad spread. They are evaluated in the + shape's local space through the inverse transform, so gradients follow the shape's + transforms and tweens. +* **Compositing.** f32 premultiplied RGBA; src-over; conversion to 8-bit happens only at + output. Group alpha for symbols with colour effects comes in M2 (offscreen layer). +* **Determinism.** No dependence on thread scheduling: each row is written by exactly one task, + and shapes are composited in order. +* **Parallelism.** Phase 1 prepares items in parallel (cull, flatten, stroke, shader). Phase 2 + rasterizes 32-row bands in parallel, each compositing all ops that touch it, in order. + Output is bit-identical to serial. Numbers are in [performance.md](performance.md). + +Planned (see roadmap): sparse-strip coverage for huge shapes, tile binning, a glyph atlas for +text, wgpu renderer with the same coverage model, filters on Movie Clips, mask layers through +coverage multiplication. + +## 5. Engine (`anicraft-engine`) + +* `Session` owns the `Document` (a **persistent, structurally shared tree**: layers, + keyframes, elements, paths and symbols live behind `Arc`, mutated only via `Arc::make_mut`), + the content `state` id, the save point, the playhead, the active layer, the selection, a + per-`(state, frame)` display-list cache, and the `History`. +* `History` stores document snapshots (O(layers) to take) with an estimate of each step's + unique bytes, bounded by a memory budget. Drags coalesce into one step. Undoing to the saved + state makes the document clean. See [ADR 0001](adr/0001-undo-persistent-snapshots.md). +* `RenderService` renders frames on a worker thread with an LRU frame cache keyed by + `(state, frame, view)`, and prefetches during playback. See + [ADR 0002](adr/0002-render-pipeline.md). +* `CommandSpec { id, label, menu, shortcut, params, run }`. `run(&mut Session, &Value) -> + Result`. The registry (`commands()`) is the single list the shell, CLI and + agents read. `Session::execute(id, params)` handles undo snapshots for mutating commands. +* **File format** `.anicraft` v2: JSON `{ "format", "version": 2, "paths": [svg…], "document" }` + with paths as SVG path strings, shared paths written once and streamed back as shared `Arc`s. + v1 files still load; unknown fields are ignored and missing fields default. See + [ADR 0003](adr/0003-file-format-v2.md). + +## 6. Headless and agents (`anicraft-cli`) + +```text +anicraft-cli info +anicraft-cli render --frame N --out frame.png [--scale S] +anicraft-cli render-seq --out-dir dir [--from A --to B] +anicraft-cli commands # registry as JSON (id, label, menu, params) +anicraft-cli run [--save out.anicraft] +anicraft-cli serve [file] # JSON-lines: {"id":1,"cmd":"draw.rect","params":{…}} +``` + +`serve` keeps one session alive and answers each request line with +`{"id":…, "ok":true, "result":…}` or `{"id":…, "ok":false, "error":"…"}`. The MCP server (M2) +is a thin adapter over the same loop. + +## 7. Desktop shell (`anicraft`) + +Panels follow the familiar animation-tool layout. The menu bar sits on top, with an edit bar +under it. Tools are on the left, the stage in the centre over a pasteboard, and Properties and +Library on the right. The timeline at the bottom has layer rows (eye and lock toggles), a frame +grid with keyframe dots, tween spans and a playhead, plus transport controls and +fps/time readouts. Theme tokens live in `theme.rs`. + +The stage texture comes from the CPU renderer and is cached per +`(revision, frame, zoom, viewport)`. Overlays (selection boxes, drag previews, the stage frame) +are drawn with the egui painter in screen space. + +`--screenshot ` runs the normal UI for about 120 frames, then saves the window picture +and exits. CI and Craft Anything use it for visual checks. + +## 8. Testing strategy + +| Kind | Where | What | +|---|---|---| +| Unit | every crate | affine algebra, flattening tolerance, easing monotonicity and endpoints, keyframe lookup | +| Golden / analytic | render | coverage of axis-aligned rects is exact; circle area within 0.5 %; gradients hit endpoints | +| Property | geom, doc | decompose∘compose ≈ identity; tween at t=0/1 equals the keyframes | +| Robustness | engine | every command with null / wrong-type / huge params returns `Err` or `Ok`, never panics; cyclic symbols render | +| Round trip | engine | save → load → identical document; render identical before and after | +| CLI | cli | render produces a PNG of stage size with non-background pixels | +| Visual | shell | `--screenshot` produces a non-blank image | +| Perf (M2) | benches | criterion benches for flatten, rasterize, evaluate at 1080p with 1,000 shapes | diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 00000000..a873c22f --- /dev/null +++ b/docs/development.md @@ -0,0 +1,49 @@ +# Development + +## Build, run, test + +```sh +cargo build # app + CLI (debug) +cargo run # desktop app with the sample +cargo run -- --screenshot shots/now.png # draw ~120 frames, save the window, exit +cargo run -- --open --screenshot x.png # palette|shortcuts|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|prefs|licenses|zoom +cargo test # every crate +cargo clippy --all-targets -- -D warnings +cargo deny check licenses bans sources +cargo run --release -p anicraft-cli -- bench # performance probe +``` + +Fonts: builds embed Inter and JetBrains Mono when `CRAFT_FONTS_DIR` points at a craft-fonts +checkout, or when one is found next to the repository (ADR 0005). Otherwise they use the +built-in fallback fonts. + +## Build footprint (biased for disk space, then time) + +Measured on Windows, 32 threads, offline, from an empty target directory: + +| | Before (2026-10-28) | Now | +|---|---|---| +| Debug build of the workspace | 6.5–6.9 GB in `target/` (3.0 GB of it the incremental cache) | **1.04 GB** (1.08 GB with all test binaries; 1.33 GB with build + tests + clippy, measured after a clean) | +| Fresh build time | ~60 s | **44 s** (tests then add 3 s) | +| Rebuild after editing a UI file | ~2 s (incremental) | **3.8 s** | +| Rebuild after editing an engine file | ~3 s | **6.0 s** | +| Debug `anicraft.exe` | 21 MB + 200 MB PDB | 21 MB + small line-table PDB | + +What does it (in `Cargo.toml`): + +| Setting | Effect | +|---|---| +| `profile.dev.debug = "line-tables-only"` | Panics and backtraces keep file:line; full variable info (most of the PDB/DWARF size) is gone. Also avoids MSVC's PDB limit (LNK1140). Use `debug = true` locally when you need a debugger session. | +| `profile.dev.incremental = false` | The incremental cache was ~3 GB for our crates. They rebuild from scratch in seconds. | +| `profile.dev.package."*"`: `opt-level = 2, debug = false` | Dependencies are optimized once (a fast app even in debug) and carry no debug info. | +| `profile.dev.build-override`: `opt-level = 0, debug = false` | Build scripts and proc-macros compile fast and small. | +| `profile.release.strip = "debuginfo"` | Smaller release binaries. | +| eframe without default features | Drops `links` (url/idna/ICU Unicode tables) and the web-only screen-reader shim. | + +House rules: + +* **One target directory.** Never point agents or scripts at a second `CARGO_TARGET_DIR`: each + copy is another full build (1+ GB now, 3–7 GB before). +* After changing profiles or dependency features, run `cargo clean` once, so the old artifacts + don't sit next to the new ones. Close the app first: Windows can't delete a running exe. +* Clean up temporary measurement directories with `cargo clean --target-dir

`. diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md new file mode 100644 index 00000000..6e1c8b23 --- /dev/null +++ b/docs/legal/compliance.md @@ -0,0 +1,110 @@ +# Legal compliance: licences, dependencies, assets, patents and trademarks + +> This is an engineering compliance record, not legal advice. Before the first public release, +> have counsel review it, especially the patent and format sections and the open items at the +> end. + +## 1. Our licence + +AniCraft is **MIT OR Apache-2.0**, the same as its sibling PhotoCraft (`LICENSE-MIT`, +`LICENSE-APACHE`, `NOTICE`; every crate declares `license.workspace = true`). + +* Dual licensing is the Rust-ecosystem norm. It is compatible with GPLv2 users (MIT) and + provides an **express patent licence and patent-retaliation clause** (Apache-2.0 §3) from + every contributor. +* Contributions are inbound = outbound (accepted under the same dual licence; see + `docs/contributing.md` when it lands). A CLA is not needed for this model. +* All crates are `publish = false` until publishing is approved. + +## 2. Dependency policy (enforced) + +Allowed: MIT, Apache-2.0 (incl. LLVM exception), BSD-2/3-Clause, ISC, Zlib, 0BSD, BSL-1.0, +Unicode-3.0, Unlicense. Font licences (OFL-1.1, Ubuntu-font-1.0) are allowed **only** for +`epaint_default_fonts`. Copyleft (GPL, LGPL, AGPL, MPL, EPL, CDDL, SSPL), "non-commercial", +"source-available" and unknown licences are **not allowed**. Only crates.io sources are allowed +(no unknown registries or git). + +```sh +cargo deny check licenses bans sources # policy in deny.toml; must pass before every commit +cargo deny check advisories # RustSec security advisories (needs network) +``` + +### Audit result, 2026-10-28 (Cargo.lock at this commit) + +* **licenses ok, bans ok, sources ok**: about 420 crates across Windows, macOS, Linux, Android + and wasm targets. +* Every crate is permissive. Crates that *offer* a copyleft alternative are used under the + permissive one: + +| Crate | Declared | Elected | +|---|---|---| +| `self_cell` 1.3 | Apache-2.0 OR GPL-2.0-only | Apache-2.0 | +| `r-efi` 5.3 / 6.0 (UEFI target only, never compiled for our platforms) | MIT OR Apache-2.0 OR LGPL-2.1-or-later | MIT | + +* Full per-crate list: [`third-party-inventory.txt`](third-party-inventory.txt) (regenerate when + `Cargo.lock` changes). + +## 3. Fonts, graphics and other assets + +* **Fonts**: only the four fonts embedded by egui (`epaint_default_fonts`): Ubuntu Light + (Ubuntu Font Licence 1.0), Hack (MIT + Bitstream Vera), Noto Emoji (OFL 1.1) and + emoji-icon-font (MIT). All permit embedding and redistribution in commercial and + non-commercial software. Restrictions apply only to *modifying and renaming the fonts*, + which we do not do. Their licence texts ship in `licenses/fonts/`. + * Primary UI typefaces (ADR 0005): Inter and JetBrains Mono, SIL OFL 1.1, embedded from the + shared `craft-fonts` build input (`CRAFT_FONTS_DIR`), as in PhotoCraft. Font rule: fonts must + be permissive in use (OFL, MIT, Apache, UFL-style), bundled rather than relying on system + fonts, and small (≤ 2.5 MB embedded in total). **No font files are committed to this + repository.** +* **User-selected system fonts** (Preferences › Appearance) are read at runtime from the user's + own OS installation and never bundled or redistributed by AniCraft, so their licences do not + bind our distribution. Enumeration uses `fontdb` (MIT). +* **Platform crates** added for ADR 0006: `rfd` (MIT, native file dialogs), eframe's `glow` + OpenGL fallback (`glow`, `glutin`: MIT OR Apache-2.0). The `directories` crate was rejected + because its dependency `option-ext` is MPL-2.0; the settings folder is resolved in our own + code. +* **Icons and UI graphics**: drawn in code by AniCraft contributors (no icon packs, no + vendor-derived glyphs). +* **Sample content**: generated in code. Screenshots in docs contain only our UI and sample. +* **Never** commit Adobe material: icons, workspace layouts copied pixel-for-pixel, preset + files, sample `.fla`, brushes or fonts. + +## 4. Patents and file formats + +| Area | Assessment | Policy | +|---|---|---| +| Rendering algorithms (coverage accumulation, Bézier flattening, Porter–Duff, gradients) | Decades-old published techniques. The coverage approach is from Apache-2.0 open source (font-rs), whose licence includes a patent grant. | Implement from public papers and permissively licensed references only; credit them in `ATTRIBUTION.md`. | +| Animation features (keyframes, classic tweens, easing, onion skin, symbols) | Long-standing prior art in animation software since the 1990s. | No feature copies a specific proprietary implementation. | +| GPU renderer (M3) | Planned design follows published, Apache/MIT-licensed work (e.g. Vello's sparse strips). | Same rule: public papers and permissive code only. | +| PNG, GIF, SVG, WebP | Royalty-free (GIF's LZW patents expired in 2003–2004). | OK to implement. | +| **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). | +| **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**. | +| 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. | + +## 5. Trademarks + +* "Adobe", "Animate" and "Flash" are Adobe trademarks. We use them only *nominatively* in docs + ("compatible with…", "competitor to…") and in the non-affiliation disclaimer of the legal + notices (`NOTICE`, Help › Licenses & Notices). Never in the product name, feature UI, icons + or marketing imagery, and never implying endorsement. +* "AniCraft": a trademark clearance search has not been done yet (open item below). + +## 6. Release checklist (before any public binary) + +1. `cargo deny check licenses bans sources advisories` passes. +2. Generate the full third-party licence texts for the shipped binary (for example with + `cargo about generate`; the tool is not yet installed here) and ship them as + `THIRD_PARTY_LICENSES.html` next to `LICENSE-*`, `NOTICE` and `licenses/`. +3. Help › Licenses & Notices in the app shows the same information (already present). +4. Re-check `ATTRIBUTION.md` against every asset in the build. +5. Counsel sign-off on the open items. + +## 7. Open items + +| Item | Status | +|---|---| +| Counsel review of this document (patents, XFL interoperability) | Open, before the first public release | +| "AniCraft" trademark clearance | Open | +| 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) | diff --git a/docs/legal/third-party-inventory.txt b/docs/legal/third-party-inventory.txt new file mode 100644 index 00000000..26bd464a --- /dev/null +++ b/docs/legal/third-party-inventory.txt @@ -0,0 +1,19 @@ +AniCraft third-party crate inventory, generated by: cargo deny list --layout license +All target platforms (Windows, macOS, Linux, Android, wasm). Regenerate when Cargo.lock changes. +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-time@1.1.0, webbrowser@1.2.5, weezl@0.1.12, wgpu@30.0.1, wgpu-core@30.0.1, wgpu-core-deps-apple@30.0.1, wgpu-core-deps-emscripten@30.0.1, wgpu-core-deps-wasm@30.0.1, wgpu-core-deps-windows-linux-android@30.0.1, wgpu-hal@30.0.1, wgpu-naga-bridge@30.0.1, wgpu-types@30.0.1, windows@0.62.2, windows-collections@0.3.2, windows-core@0.62.2, windows-future@0.3.2, windows-implement@0.60.2, windows-interface@0.59.3, windows-link@0.2.1, windows-numerics@0.3.1, windows-result@0.4.1, windows-strings@0.5.1, windows-sys@0.52.0, windows-sys@0.59.0, windows-sys@0.61.2, windows-targets@0.52.6, windows-threading@0.2.1, windows_aarch64_gnullvm@0.52.6, windows_aarch64_msvc@0.52.6, windows_i686_gnu@0.52.6, windows_i686_gnullvm@0.52.6, windows_i686_msvc@0.52.6, windows_x86_64_gnu@0.52.6, windows_x86_64_gnullvm@0.52.6, windows_x86_64_msvc@0.52.6, winit@0.30.13, wit-bindgen@0.57.1, x11rb@0.13.2, x11rb-protocol@0.13.2, xkeysym@0.2.1, zerocopy@0.8.63, zerocopy-derive@0.8.63, zune-core@0.5.3, zune-jpeg@0.5.15 +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 +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@0.14.0, tempfile@3.27.0, thiserror@1.0.69, thiserror@2.0.21, thiserror-impl@1.0.69, thiserror-impl@2.0.21, tiff@0.11.3, tinyvec@1.13.3, tokio@1.54.1, 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, tracing@0.1.44, tracing-attributes@0.1.31, tracing-core@0.1.36, ttf-parser@0.25.1, type-map@0.5.1, uds_windows@1.2.1, 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, walkdir@2.5.0, 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, wayland-backend@0.3.17, wayland-client@0.31.15, wayland-csd-frame@0.3.0, wayland-cursor@0.31.14, wayland-protocols@0.32.13, wayland-protocols-experimental@20250721.0.1, wayland-protocols-misc@0.3.12, wayland-protocols-plasma@0.3.12, wayland-protocols-wlr@0.3.12, wayland-scanner@0.31.11, wayland-sys@0.31.11, web-sys@0.3.106, web-time@1.1.0, webbrowser@1.2.5, weezl@0.1.12, wgpu@30.0.1, wgpu-core@30.0.1, wgpu-core-deps-apple@30.0.1, wgpu-core-deps-emscripten@30.0.1, wgpu-core-deps-wasm@30.0.1, wgpu-core-deps-windows-linux-android@30.0.1, wgpu-hal@30.0.1, wgpu-naga-bridge@30.0.1, wgpu-types@30.0.1, winapi-util@0.1.11, windows@0.62.2, windows-collections@0.3.2, windows-core@0.62.2, windows-future@0.3.2, windows-implement@0.60.2, windows-interface@0.59.3, windows-link@0.2.1, windows-numerics@0.3.1, windows-result@0.4.1, windows-strings@0.5.1, windows-sys@0.52.0, windows-sys@0.59.0, windows-sys@0.61.2, windows-targets@0.52.6, windows-threading@0.2.1, windows_aarch64_gnullvm@0.52.6, windows_aarch64_msvc@0.52.6, windows_i686_gnu@0.52.6, windows_i686_gnullvm@0.52.6, windows_i686_msvc@0.52.6, windows_x86_64_gnu@0.52.6, windows_x86_64_gnullvm@0.52.6, windows_x86_64_msvc@0.52.6, winnow@1.0.4, wit-bindgen@0.57.1, x11-dl@2.21.0, x11rb@0.13.2, x11rb-protocol@0.13.2, xcursor@0.3.11, xkbcommon-dl@0.4.2, xkeysym@0.2.1, xml-rs@0.8.29, zbus@5.19.0, zbus-lockstep@0.5.2, zbus-lockstep-macros@0.5.2, zbus_macros@5.19.0, zbus_names@4.3.5, zbus_xml@5.2.1, zcheapstr@1.1.0, zerocopy@0.8.63, zerocopy-derive@0.8.63, zmij@1.0.23, zune-core@0.5.3, zune-jpeg@0.5.15, zvariant@5.15.1, zvariant_derive@5.15.1, zvariant_utils@4.2.0 +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 +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 diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 00000000..5710b00a --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,41 @@ +# Performance + +Rule: **measure first, then optimize, then record the number here.** Every optimization lands +with a benchmark delta and a test that it did not change output (the CPU renderer is the +oracle; its output must stay bit-identical). + +## How to measure + +```sh +cargo run --release -p anicraft-cli -- bench # 50 layers × 200 shapes × 240 frames +cargo run --release -p anicraft-cli -- bench --layers 200 --shapes 500 --frames 600 +``` + +`bench` builds a deterministic stress document (`doc::sample::stress`) and reports file size, +save/load time, evaluate/render time per frame, zoomed render with culling, snapshot cost, +per-edit and per-undo time, history bytes per step and hit-test time. In the app, the status +bar shows render time, shapes drawn and culled, frame-cache size and hit rate, and history +memory. + +## Budgets (targets) + +| Scenario | Budget | Measured 2026-10-28 (release, 32 threads) | +|---|---|---| +| Edit command on a 200k-instance document | < 1 ms | 0.011 ms ✅ | +| Undo / redo | < 1 ms | 0.009 ms ✅ | +| Undo memory per small edit | < 16 KB | 2.7 KB ✅ | +| Document snapshot | < 50 µs | 0.4 µs ✅ | +| Evaluate one frame (200k instances) | < 4 ms | 1.5 ms ✅ | +| Render 1080p, ~10k visible shapes | < 16.7 ms (60 fps) | 16.5 ms ✅ (tight) | +| Render at 400% zoom | < 16.7 ms | 10.9 ms ✅ | +| Hit test | < 200 µs | 51 µs ✅ | +| Save / load 65 MB file | < 500 ms | 118 / 142 ms ✅ | +| UI frame while rendering | never blocked | worker thread ✅ | + +Budgets become CI-enforced once the perf harness runs on a fixed machine (roadmap M2). + +## Decisions + +* [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 diff --git a/docs/product-principles.md b/docs/product-principles.md new file mode 100644 index 00000000..ef58e0d8 --- /dev/null +++ b/docs/product-principles.md @@ -0,0 +1,51 @@ +# Product principles + +These two standing rules apply to every proposal, review and commit. + +## 1. Design like a principal engineer + +Before building anything, ask: **"Is this how a principal engineer would do it?"** If not, use +the better method, or ask the project lead when the choice changes the product. A principal +engineer: + +* **Measures before optimizing**, and records the numbers (`docs/performance.md`). +* **Prefers correctness by construction** over correctness by discipline. Examples: snapshot + undo on a persistent document instead of hand-written inverse commands (ADR 0001), and one + command registry for UI, CLI and agents. +* **Chooses the simplest design that holds at 100× scale**: virtualized lists, background + rendering, bounded memory. +* **Writes the decision down** (an ADR for anything hard to reverse) with the options + considered. +* **Ships in small, green, reversible steps** with tests that would have caught the bug. +* **Pushes back on a requirement when its literal form hurts users**, and explains the + better alternative. ADR 0004 is an example. + +## 2. Build for artists and creatives + +Our users animate 2D vector art, many of them coming from Adobe Animate. They expect a +**professional, fast, reliable and easy** tool: + +| Quality | What it means here | +|---|---| +| Professional | Familiar layout (tools left, stage centre, timeline bottom, panels right), familiar names and shortcuts (F5/F6/F7, F8, Ctrl+Z…), exact output. | +| High performance | Never block the UI. Playback at document fps. Large files open and edit instantly (budgets in `performance.md`). | +| Reliable | Never crash, never lose work. Unsaved-change guards, atomic saves, atomic commands. | +| Easy | The most common actions are one click or one key away: right-click menus on stage, timeline and layers; a command palette (Ctrl+K) for everything; a shortcut sheet (F1). | +| Smooth flow | Natural, predictable and quick. No modal interruptions for routine edits. A drag is one undo step. Selection, playhead and tool state behave the same everywhere. | + +### Power users + +* Every command has a stable id, and the important ones have shortcuts. +* **Ctrl+K** opens the command palette (fuzzy search over every command, Enter to run). +* **F1** opens the keyboard-shortcut sheet, generated from the registry so it never goes stale. +* Arrow keys nudge (Shift = 10 px). Tool keys V/R/O/P/N/H/Z. Enter plays. + +### Destructive actions (ADR 0004) + +Destructive actions are **never a single click or keystroke away from losing work**: + +| Tier | Examples | Behaviour | +|---|---|---| +| **Irreversible** (no undo can bring it back) | New/Open/Close with unsaved changes; overwriting a file on disk | Always a confirmation dialog. The destructive button must be clicked (Enter does not confirm). Agents must pass `"confirm": true`. | +| **Undoable, discards notable content** | Delete a layer with artwork; clear a keyframe with artwork; remove a frame that deletes a keyframe | Confirmation dialog by default (Enter confirms, Esc cancels), with "Don't ask again this session". | +| **Routine edit** | Delete selected shapes, move, recolour | No dialog (flow). The status bar says what happened and "Ctrl+Z to undo"; the History panel shows the step. | diff --git a/docs/release.md b/docs/release.md new file mode 100644 index 00000000..dc1b21e5 --- /dev/null +++ b/docs/release.md @@ -0,0 +1,41 @@ +# Releases and contributing flow + +## Versions + +AniCraft follows semantic versioning. Before 1.0, minor versions may change file formats and +commands, with migration on load (ADR 0003). + +| Version | Stage | Meaning | +|---|---|---| +| `0.1.0` | early alpha | M0 + M1 done: authoring core, Animate file import, GIF/PNG export, editable shortcuts. | +| `0.2.0`, … | alpha | Further milestones from `docs/roadmap.md`. | + +The version lives in one place, `[workspace.package]` in `Cargo.toml`, and the stage in +`RELEASE_STAGE` (`src/app.rs`). The About window, the CLI's `serve` handshake and the +`generator` field of saved files all read it. Every version gets a section in `CHANGELOG.md` +and an annotated tag (`v0.1.0`) on `main`. + +## How changes land + +* `main` is the development branch. It begins with one commit, "Initial commit v0.1.0 early + alpha"; `AUTHORS.md` credits everyone whose work it contains. +* Work happens on topic branches (`feat/svg-export`, `fix/…`, `docs/…`), with one roadmap step + per pull request. A PR is ready when build, tests, clippy (`-D warnings`) and + `cargo deny check licenses bans sources` pass, the screenshot check looks right, and + `docs/roadmap.md` › Honest status and `CHANGELOG.md` (Unreleased) are updated. +* PRs are merged into `main` on GitHub, and nobody commits or pushes to `main` directly (the + hooks in `scripts/git-hooks` refuse it locally; branch protection should require PRs on the + remote). + +## Before a release + +* [ ] Counsel confirm the patent posture and the clean-room approach to opening Animate files + (`docs/legal/compliance.md`). +* [ ] Counsel or a trademark search confirm the name "AniCraft". +* [ ] `cargo test`, `cargo clippy --all-targets -- -D warnings` and + `cargo deny check licenses bans sources` pass, plus screenshot checks on Windows, macOS and + Linux. +* [ ] `ATTRIBUTION.md`, `NOTICE`, `licenses/` and `docs/legal/third-party-inventory.txt` are + current. +* [ ] `CHANGELOG.md` has the version's section; the version is bumped in `Cargo.toml` through a + PR, and the merge commit on `main` is tagged. diff --git a/docs/requirements.md b/docs/requirements.md new file mode 100644 index 00000000..351a4e94 --- /dev/null +++ b/docs/requirements.md @@ -0,0 +1,104 @@ +# AniCraft: technology and requirements + +AniCraft is an open-source, native, clean-room 2D vector animation studio in the class of +Adobe Animate, written in **Rust only**. It is a sibling of PhotoCraft, LightCraft, WordCraft and +the other `{Function}Craft` apps and follows the same house rules (Rust only, no webview shells, +everything is a command, never crash, tests are the gate). + +This document fixes *what* we build and *with what*. `architecture.md` says *how the pieces fit*, +`roadmap.md` says *in which order*. + +## 1. Product scope + +### 1.1 Users and jobs + +| User | Job to be done | +|---|---| +| Motion designer / animator | Draw vector art, animate it on a timeline with keyframes, tweens and symbols, preview at the target frame rate, export video/GIF/web. | +| Game / web developer | Author sprite animations and UI motion, export sprite sheets, Lottie or HTML canvas, script interactivity. | +| Educator / hobbyist | A free, fast, cross-platform replacement for an abandoned or subscription-only tool. | +| Agent / pipeline | Create, edit, render and validate documents with no window (CLI, JSON-lines, MCP), in CI or a render farm. | + +### 1.2 Functional requirements (feature areas) + +Priority: **P0** = M0–M2 skeleton must have, **P1** = parity core, **P2** = long tail. + +| Area | Requirement | Pri | +|---|---|---| +| Document | Stage size, frame rate, background colour; multiple scenes; library of symbols and assets. | P0 | +| Timeline | Layers (normal, guide, mask, folder), frames, keyframes, blank keyframes, frame spans, labels, playhead, scrubbing, looping playback at document fps. | P0 | +| Tweens | Classic tween with easing presets and custom cubic-Bézier ease; shape tween; motion tween with property curves (Motion Editor); motion guides. | P0 / P1 | +| Symbols | Graphic (timeline-synced), Movie Clip (independent timeline), Button (Up/Over/Down/Hit); instances with transform, colour effect (alpha, tint, brightness, advanced), loop modes and first frame. | P0 / P1 | +| Drawing | Selection, Subselection, Free transform, Rectangle, Oval, PolyStar, Line, Pen, Pencil, Brush (variable width), Paint bucket, Ink bottle, Eraser, Eyedropper, Hand, Zoom; object drawing and merge drawing models. | P0 / P1 | +| Fills and strokes | Solid, linear and radial gradients, bitmap fills; stroke width, caps, joins, miter limit, variable width profiles, dashes. | P0 / P1 | +| Text | Static, dynamic and input text with font embedding policy; text on stage animates like any element. | P1 | +| Onion skin | Before/after range, tint, outlines. | P1 | +| Camera | Layer-depth camera with pan, zoom, rotate. | P2 | +| Bones / IK | Bone tool, armature poses. | P2 | +| Audio | Import WAV/OGG/MP3, stream vs event sync, waveform on timeline, scrub audio. | P1 | +| Filters / blend | Blend modes, drop shadow, blur, glow, bevel, colour adjust on Movie Clips. | P1 | +| Scripting | Frame scripts and automation (see open question U2 below). | P2 | +| Import | SVG, PNG/JPEG sequences, **XFL (uncompressed FLA XML)**, then binary FLA as a stretch goal. | P1 | +| Export | PNG / PNG sequence, animated GIF, sprite sheet + JSON, SVG (static frame), **Lottie JSON**, HTML canvas, MP4/WebM via a system encoder (ffmpeg pipe), optionally SWF. | P0 (PNG) / P1 | +| History | Unlimited undo/redo, named history entries, history is per document. | P0 | +| Headless | Every action available from the CLI, a JSON-lines control channel and an MCP server; deterministic renders. | P0 | + +### 1.3 Non-functional requirements + +| Quality | Requirement (measurable where possible) | +|---|---| +| **Never crash** | No panics in non-test code. Malformed files, bad command params and odd input return actionable errors. Every command is fuzzed with adversarial params (`panic_hunt` test). | +| **Determinism** | The same document + frame renders byte-identical PNGs on every platform with the CPU renderer (fixed-point-free f32 path, no time or thread-order dependence). This is the oracle for tests and agents. | +| **Performance** | Stage playback at document fps (24/30/60) for 1920×1080 with ≥1,000 visible shapes; scrub latency < 16 ms; open a 50 MB document < 1 s; render a 1080p frame headless < 20 ms on 8 cores. Budgets live in `perf/budgets.toml` from M2. | +| **Memory** | Documents are structurally shared (copy-on-write); an undo step costs proportional to what changed, not the document size. | +| **Fidelity** | Analytic anti-aliasing (exact area coverage), correct non-zero and even-odd fill rules, gradient spread modes, premultiplied-alpha compositing. | +| **Portability** | Windows, macOS, Linux desktop; the engine layers (L0–L5) also build for `wasm32-unknown-unknown`. | +| **Accessibility** | Keyboard reachable commands, scalable UI, high-contrast theme, screen-reader labels via AccessKit. | +| **Clean room** | Behaviour and look learned only from public documentation, public specs and observation. No proprietary code, shaders, presets or assets. | +| **Licensing** | MIT OR Apache-2.0. Every third-party asset is permissively licensed and listed in `ATTRIBUTION.md`. | + +## 2. Technology choices + +| Concern | Choice | Why | +|---|---|---| +| Language | Rust 2024 edition, stable toolchain (MSRV 1.90) | Memory safety, fearless parallelism, one language for engine, UI, CLI and web. | +| UI | **egui / eframe 0.36** (wgpu backend) | Immediate mode keeps the UI a thin function of state, matches PhotoCraft, runs native and on the web. | +| Rendering (oracle) | In-house CPU rasterizer: Bézier flattening + signed-area coverage accumulation, rayon row parallelism | Deterministic, testable, headless; the reference every other renderer is compared against. | +| Rendering (interactive, M3) | wgpu compute/fragment renderer (sparse strips or tile binning in the style of public Vello/Pathfinder papers), compared per-pixel against the CPU oracle | Fast stage at high zoom and 4K; GPU and CPU must agree within a tolerance in tests. | +| Geometry | In-house `geom` crate (affine, Bézier, flattening, hit test); `kurbo`-compatible API shape | Small, no_std-friendly, full control over tolerance and determinism. | +| Serialization | serde + serde_json for `.anicraft` (JSON manifest), zip container from M2 for embedded media | Human-diffable, agent-friendly, versioned with `#[serde(default)]`. | +| Images | `png` crate for encode/decode; GIF encoder from M1 | Minimal dependencies. | +| Parallelism | rayon | Row and tile parallelism in the renderer, batch export. | +| Errors | thiserror per crate | Typed, propagatable, no panics. | +| Audio (M5) | cpal for output, symphonia for decoding | Pure Rust, cross-platform. | +| Video export (M4) | ffmpeg as an external process (pipe raw frames) | No codec licensing in the binary. | +| Testing | `cargo test`, golden-image tests, property tests (proptest), adversarial command fuzz, criterion benches | Tests are the gate. | +| Automation | CLI (`anicraft-cli`), JSON-lines `serve` mode, MCP server (M2) over the same command registry | Headless parity with the UI by construction. | + +### Rejected options + +* **Tauri / Electron / any webview UI**: violates the Rust-only rule of the Craft family. +* **Skia / tiny-skia as the renderer of record**: good libraries, but owning the rasterizer is + central to the project's rendering and performance goals and to cross-renderer determinism. + tiny-skia stays acceptable as a *test-only* cross-check. +* **A retained-mode UI toolkit**: more state to keep in sync with the document; egui's immediate + mode plus a command engine gives one source of truth. + +## 3. Constraints and rules (inherited from the Craft family) + +1. Rust only; no unsafe (`unsafe_code = "forbid"` workspace-wide). +2. Everything a user can do is a **command** with an id, label, menu path, shortcut, params schema + and tests. UI, CLI, JSON-lines and MCP all dispatch by id. +3. The UI is thin: no document logic in `ui`. +4. Input-derived numbers are hostile: checked arithmetic, bounded allocation, bounded recursion + (symbols can nest and can be cyclic in malformed files). +5. Layering is enforced; lower layers never depend on egui/eframe/winit. +6. Every change comes with tests; renderer changes come with golden images. + +## 4. Open questions + +| 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. | +| U3 | When does the GPU renderer become primary on stage? | CPU oracle drives the stage until the GPU renderer passes golden parity tests (M3). | diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 00000000..c0b41c21 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,69 @@ +# AniCraft roadmap + +Principle: **infrastructure first, then high-traffic parity, then the long tail.** Every +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) + +| Dimension | Status | +|---|---| +| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering by convention (an xtask check is planned). | +| 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. No GPU path, filters or text 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, auto-key when editing inside a tween, frame labels, graphic-symbol nesting with loop modes, 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`. No scenes, folders, motion editor; guide layers are hidden but do not guide yet. | +| 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. No brush or merge drawing yet. | +| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). No MCP yet. | +| Files | `.anicraft` JSON load/save (v2), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping). **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 and **mask layers** (including masks in folders); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. No bitmaps, text, motion/shape tweens or extra scenes from XFL yet; no SVG/Lottie/video. | +| 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. | +| 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`. Budgets are not yet CI-enforced. | + +## Milestones + +| M | Theme | Exit criteria | +|---|---|---| +| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | +| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (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; layer folders, guide layers; ~~mask layers~~ ✅; Movie Clip and Button behaviours; group alpha / offscreen compositing; shape tween with shape hints; motion tween + Motion Editor curves; MCP server; perf budgets (criterion) with CI enforcement; `xtask layers`. | +| **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/export; Lottie export; sprite sheet + JSON; MP4/WebM via ffmpeg pipe. | +| **M5** | Rich media | Text engine (shaping via rustybuzz, glyph atlas); 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. | +| **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. | +| **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. | + +## 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`. + +## Current focus (after M0 + scale foundations) + +The person confirmed that opening Animate files (XFL) is the first interchange priority. The +undo/performance foundations it needs are in place, so XFL import (M4) can move up once the +authoring core below is solid. + +Landed in M1 so far: Free Transform, clipboard, rotate/flip, align/distribute, GIF export, and +now Subselection, Pen and Pencil on a path-editing model in the engine (points addressed by +command and slot, so XFL edge data can map onto it). The Pen's interaction and the Pencil's +curve fitter were borrowed from PhotoCraft and reviewed before porting (see +`src/pathtools.rs` and `crates/geom/src/fit.rs` for what changed and why). PolyStar no longer +has a key (P is the Pen, as in Animate). + +Next, in order: + +1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, motion tweens and shape + tweens, more scenes, bitmaps and text (with M5), and a larger self-authored corpus checked + by render tests. +2. SVG import (the full SVG path reader is in place) and export. + +## Risks + +| Risk | Mitigation | +|---|---| +| GPU and CPU renderers drift apart | Golden parity tests in CI; CPU stays the oracle. | +| XFL edge encoding is under-documented | Build a self-authored corpus; unknown elements kept verbatim; fail with readable errors. | +| egui immediate-mode cost with big timelines | Virtualise the frame grid (paint only visible cells); cache layer row summaries per revision. | +| Snapshot undo memory | `Arc` structural sharing in M2; history size cap with a preference. | diff --git a/docs/ui-guidelines.md b/docs/ui-guidelines.md new file mode 100644 index 00000000..2cc2d506 --- /dev/null +++ b/docs/ui-guidelines.md @@ -0,0 +1,165 @@ +# UI guidelines + +AniCraft's interface serves artists in a flow state (see `product-principles.md`). These rules +keep it professional, calm and predictable. **Tokens live in `src/theme.rs`**: colours in `T`, +typography in `Type`. Panels never hard-code colours, font families or font sizes; a test +(`guidelines_tests` in `src/main.rs`) fails the build if they do. + +## 1. Layout + +The layout is familiar to animators: **tools** on the left, **stage** in the centre over a darker +pasteboard, **timeline** at the bottom, **Properties / Library / History** docked on the right, +menu bar and edit bar on top, and a status bar at the bottom. + +* The most frequent actions are one click away (timeline header buttons, panel buttons) **and** + one key away (registry shortcuts). Everything is reachable from the command palette (Ctrl+K). +* Right-click offers the actions that apply to what is under the pointer (stage, frames, layer + names), with the same labels and shortcuts as the menus (`menus::cmd_item`). +* Panels virtualize long content (timeline rows and columns); nothing paints off-screen work. + +## 2. Typography: prose vs data + +Two families, chosen by **what the text is**, not by where it sits: + +| Role (`theme::Type`) | Family | Use for | Examples | +|---|---|---|---| +| `Title` | proportional 17 | Dialog titles | "Delete layer?" | +| `Heading` | proportional 12.5, bold, sentence case | Panel/section names | Properties, Timeline, Library | +| `Body` | proportional 13 | Names, list items, menu items, buttons | layer and symbol names | +| `Label` | proportional 12 | Field labels, status messages | "Position", "Saved…" | +| `Caption` | proportional 11 | Hints, explanations, footnotes | "Enter confirms · Esc cancels" | +| `Data` | **monospace** 12 | Values and readouts | X/Y, scale, rotation, sizes, fps, seconds, zoom %, cursor coordinates, render stats | +| `DataSmall` | **monospace** 10 | Dense numeric scales | timeline ruler, playhead number | +| `DataLarge` | **monospace** 14.5 | The hero number | current frame in the timeline header | +| `Key` | **monospace** 11.5 | Shortcuts and keycaps | Ctrl+Shift+S, F6 | +| `Path` | **monospace** 11 | Paths, ids, preformatted text | file locations, licence texts | + +**Why monospace for data:** fixed-width digits don't jitter while a value is scrubbed or +played back, numbers line up in columns, and technical readouts read as instruments rather than +prose. Pro audio/video tools use the same idea. We adopt the idea only; we don't copy any +vendor's typeface. + +**Never monospace:** dialog descriptions, explanations, menu and button labels, layer names, +tooltips' prose, error messages and anything a person reads as a sentence. Mixed lines keep +their label proportional and their value monospace. + +Typefaces (ADR 0005): **Inter** (prose) and **JetBrains Mono** (data), both SIL OFL 1.1, +embedded from the shared craft-fonts input (`CRAFT_FONTS_DIR`, or discovered next to the repo) +as in PhotoCraft. Users can pick any **installed system font** for the interface and any +installed **monospaced** font for data in Preferences › Appearance. Roles stay the same; only +the family changes. Interface scale 75–200% is a preference too. The fallback +is egui's bundled Ubuntu + Hack, so builds without craft-fonts still work. Fonts must be +permissive in use and small enough to bundle (≤ 2.5 MB embedded in total). Platform system fonts +are not used for UI text, because they would change metrics per OS. + +## 3. Colour (ADR 0008) + +* **Graphite neutrals**, darkest at the edges: `chrome` (menu and status bars) → `panel` → + `panel_alt` (section headers, alternate rows, windows) → `header` (buttons at rest) → `hover`. + Text and number fields are inset: `field`, darker than the panel. The artwork is the most + colourful thing on the stage. +* **Vibrant colour only where it means something, mostly on the timeline**: mint `span` = + frames with artwork, violet `tween` = classic tween, graphite `span_empty` = empty frames, + red `playhead`. Marks drawn on those blocks use `ink`. +* **One accent**, cobalt `accent`, for selection, focus and the active tool. Red only for the + playhead, errors and destructive buttons (`danger`). +* Text has three steps: `text`, `text_dim`, `text_faint`. Use the role's default colour unless + you are showing a state. +* **Contrast** (checked by `guidelines_tests`): body text ≥ 7:1 on panels; dim and faint text + ≥ 4.5:1; text on filled buttons ≥ 4.5:1; marks on timeline blocks ≥ 4.5:1; focus rings, + selection, checkbox edges and timeline blocks ≥ 3:1 against their background. +* No raw colours outside `theme.rs`: add a token. + +## 4. Shapes, borders, spacing and sizes (ADR 0008) + +* **Corners follow the role of a shape**, never one value for everything: + * *Structure is square* (`theme::SQUARE`): panels, dock bands, the timeline grid, its blocks + and selections, the stage. These tile against each other. + * *Controls are softened* (`T.rc()`, 3 px): buttons, fields, tools, list highlights, swatches, + the playhead flag. Geometric and rectangular, but not sharp. + * *Floating surfaces are rounder*: menus and tooltips 6 px, dialogs and windows 10 px, with + a soft, tight downward shadow so they lift off the work. + * *Round only where the thing is round*: keyframe dots, dials, onion-skin marks. +* **Sections** use `theme::section`: a full-width header (chevron, bold title, and in panels + and dialogs a horizontal rule across the rest of the row) that folds its content away. The + whole row is the click target, it takes keyboard focus, and assistive technology hears + "expanded/collapsed". Dock sections are `Section::Band`, groups inside a panel or dialog + `Section::Rule`. Don't separate groups by indentation alone. +* **Borders separate layout, not widgets.** Use `T.border` lines between regions (panels, + section headers, the timeline's layer list and grid, the timeline footer) and around popups. + Buttons are flat fills with no resting border; hover lightens the fill. Use `T.separator` + for fine grid lines inside a region. +* **Focus is always visible**: pressed and keyboard-focused widgets show a 2 px accent ring. +* **Checkboxes and radio buttons** go through `theme::checkbox` / `theme::radio_value`, which + give them a visible edge (`control_edge`) so the off state does not disappear. +* **Click targets** (WCAG 2.5.8): at least `theme::TARGET` (28 px) for every button, row and + field; tools `TOOL_BUTTON` (40 × 40); timeline rows 28; layer toggles 24 × 24; dialog + buttons 32 high. Don't use small buttons. Timeline frame cells (12 px wide) are a + dense-data exception: the ruler, rows and the keyboard reach the same frames. +* Item spacing 8×6, buttons pad 10×5. Panels pad 10–12 px. Align values in a column using the + `row` helper. +* Active states are solid: the active tool is an accent block with a white icon; a selected + list row is `accent_dim` with an accent edge bar; dock sections start with a short accent bar. + +## 5. Icons + +* **Lucide** (ISC licence, `assets/icons/`, credited in `ATTRIBUTION.md`): one consistent, + open outline set with icons for everything an editor needs. Use `icons::paint` with an + `icons::Icon` variant. The SVGs are parsed with the engine's own SVG path reader and stroked + as vectors at the on-screen size (crisp at any interface scale, no rasterizer dependency). +* To add an icon: copy its SVG from the Lucide set into `assets/icons/`, add a variant and its + file to `src/icons.rs`. Prefer an existing Lucide icon (mirrored if needed) to drawing one. + When none fits, draw an original `anicraft-*.svg` on the same 24 grid with 2-unit round + strokes (the Align panel's icons are such originals). +* Icons are placed on whole device pixels with whole-pixel stroke widths; tool icons are drawn + at the set's native 24 px, where they are sharpest. +* **Selection is solid, Subselection hollow** (`Icon::solid`): the two arrows must be told apart + at a glance, as animators expect. +* Forms use `theme::form_row` / `theme::form_note`: labels left-aligned in one column, controls + in the next, and explanations under the control they explain (under a checkbox or radio + button, aligned with its text), never back at the label column. +* 18–20 px glyph inside a larger target, the same colour as the text, white on an active + (accent) block, faint when it shows an "off" state. +* Every icon button has a tooltip with its name and shortcut. No icon fonts, no vendor glyphs. + +## 6. Feedback and flow + +* Every action answers in the status bar (what happened, and "Ctrl+Z to undo" for deletions). +* Long work never blocks the UI (background render, ADR 0002); show the last good state while + waiting. +* Drags are one undo step. Values scrubbed in fields are one undo step. +* Destructive actions follow ADR 0004 (tiered confirmation). Dialog buttons name the action + ("Delete Layer", not "OK"). The destructive button is red; Cancel is always available and + Esc cancels. + +## 7. Keyboard + +* Familiar animation shortcuts first (F5/F6/F7, Shift+F5/F6, F8, Ctrl+B, Enter to play, `,` `.` + to step), then the platform conventions (Ctrl+Z/S/O/N…). +* Where the industry-standard animation defaults and a generic convention disagree, the + animation default wins and the other becomes an alias (`SHORTCUT_ALIASES`): Ctrl+Y redoes, + Ctrl+Shift+Z removes a transform, Ctrl+↑/↓ arranges, Shift+`,`/`.` jump to the first/last + frame, Backspace deletes. A test fails if two commands share a chord. +* Tool keys are single letters; Shift constrains; Space pans; arrows nudge (Shift ×10). +* Scrolling follows the browser convention everywhere: the wheel scrolls vertically, Shift+wheel + (and sideways wheels or trackpad swipes) horizontally, Ctrl+wheel zooms, over the whole + panel, not only its empty parts. +* F1 shows every shortcut (generated from the registry); Ctrl+K runs anything. + +## 8. Copy and numbers + +* Sentence case for labels and titles; Title Case only for menu commands, matching familiar + tools. Buttons are verbs. No exclamation marks. +* Frames are 1-based in the UI (frame 1 is the first). Time is in seconds with two decimals + (`0.50 s`). Units follow the number with a space: `24.00 fps`, `1280 × 720 px`, `78%`. +* Use "×" for dimensions and "·" to separate inline facts. + +## 9. Checklist for a UI change + +1. Uses `theme::text(Type::…)` / `theme::font` / `with_type`, with no raw sizes or families, + and colours, radii and sizes from `theme` (`T`, `TARGET`), with no raw values. +1. Targets ≥ `TARGET`, focus visible, contrast as in section 3, corners by role (section 4), + borders only for layout, groups as collapsible `theme::section`s, Lucide icons. +2. Data in monospace, prose proportional (section 2). +3. Reachable by menu, palette and, if frequent, a shortcut and a right-click menu. +4. Screenshot checked (`cargo run -- --screenshot shots/now.png`, `--open ` for dialogs). diff --git a/licenses/fonts/LICENSE-Hack.txt b/licenses/fonts/LICENSE-Hack.txt new file mode 100644 index 00000000..b0ec7448 --- /dev/null +++ b/licenses/fonts/LICENSE-Hack.txt @@ -0,0 +1,31 @@ +The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License + +The work in the DejaVu project was committed to the public domain. + +Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera" +MIT License + +Copyright (c) 2018 Source Foundry Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +BITSTREAM VERA LICENSE + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: + +The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera". + +This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names. + +The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org. diff --git a/licenses/fonts/LICENSE-emoji-icon-font.txt b/licenses/fonts/LICENSE-emoji-icon-font.txt new file mode 100644 index 00000000..99016e12 --- /dev/null +++ b/licenses/fonts/LICENSE-emoji-icon-font.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2014 John Slegers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/fonts/OFL-1.1-NotoEmoji.txt b/licenses/fonts/OFL-1.1-NotoEmoji.txt new file mode 100644 index 00000000..d952d62c --- /dev/null +++ b/licenses/fonts/OFL-1.1-NotoEmoji.txt @@ -0,0 +1,92 @@ +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/licenses/fonts/UFL-1.0-Ubuntu-font.txt b/licenses/fonts/UFL-1.0-Ubuntu-font.txt new file mode 100644 index 00000000..ae78a8f9 --- /dev/null +++ b/licenses/fonts/UFL-1.0-Ubuntu-font.txt @@ -0,0 +1,96 @@ +------------------------------- +UBUNTU FONT LICENCE Version 1.0 +------------------------------- + +PREAMBLE +This licence allows the licensed fonts to be used, studied, modified and +redistributed freely. The fonts, including any derivative works, can be +bundled, embedded, and redistributed provided the terms of this licence +are met. The fonts and derivatives, however, cannot be released under +any other licence. The requirement for fonts to remain under this +licence does not require any document created using the fonts or their +derivatives to be published under this licence, as long as the primary +purpose of the document is not to be a vehicle for the distribution of +the fonts. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this licence and clearly marked as such. This may +include source files, build scripts and documentation. + +"Original Version" refers to the collection of Font Software components +as received under this licence. + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to +a new environment. + +"Copyright Holder(s)" refers to all individuals and companies who have a +copyright ownership of the Font Software. + +"Substantially Changed" refers to Modified Versions which can be easily +identified as dissimilar to the Font Software by users of the Font +Software comparing the Original Version with the Modified Version. + +To "Propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification and with or without charging +a redistribution fee), making available to the public, and in some +countries other activities as well. + +PERMISSION & CONDITIONS +This licence does not grant any rights under trademark law and all such +rights are reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to propagate the Font Software, subject to +the below conditions: + +1) Each copy of the Font Software must contain the above copyright +notice and this licence. These can be included either as stand-alone +text files, human-readable headers or in the appropriate machine- +readable metadata fields within text or binary files as long as those +fields can be easily viewed by the user. + +2) The font name complies with the following: +(a) The Original Version must retain its name, unmodified. +(b) Modified Versions which are Substantially Changed must be renamed to +avoid use of the name of the Original Version or similar names entirely. +(c) Modified Versions which are not Substantially Changed must be +renamed to both (i) retain the name of the Original Version and (ii) add +additional naming elements to distinguish the Modified Version from the +Original Version. The name of such Modified Versions must be the name of +the Original Version, with "derivative X" where X represents the name of +the new work, appended to that name. + +3) The name(s) of the Copyright Holder(s) and any contributor to the +Font Software shall not be used to promote, endorse or advertise any +Modified Version, except (i) as required by this licence, (ii) to +acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with +their explicit written permission. + +4) The Font Software, modified or unmodified, in part or in whole, must +be distributed entirely under this licence, and must not be distributed +under any other licence. The requirement for fonts to remain under this +licence does not affect any document created using the Font Software, +except any version of the Font Software extracted from a document +created using the Font Software may only be distributed under this +licence. + +TERMINATION +This licence becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. diff --git a/licenses/icons/LICENSE-lucide.txt b/licenses/icons/LICENSE-lucide.txt new file mode 100644 index 00000000..718bb3f0 --- /dev/null +++ b/licenses/icons/LICENSE-lucide.txt @@ -0,0 +1,43 @@ +ISC License + +Copyright (c) 2026 Lucide Icons and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--- + +The following Lucide icons are derived from the Feather project: + +airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out + +The MIT License (MIT) (for the icons listed above) + +Copyright (c) 2013-present Cole Bemis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/scripts/git-hooks/pre-commit b/scripts/git-hooks/pre-commit new file mode 100755 index 00000000..46f0ab48 --- /dev/null +++ b/scripts/git-hooks/pre-commit @@ -0,0 +1,10 @@ +#!/bin/sh +# AniCraft: `main` changes only through pull requests (docs/release.md, "How changes land"). +# Work on a topic branch: git switch -c feat/ +branch=$(git symbolic-ref --short -q HEAD) +if [ "$branch" = "main" ] && [ "$ANICRAFT_ALLOW_MAIN_COMMIT" != "1" ]; then + echo "AniCraft: commit blocked - main changes only through pull requests." >&2 + echo " Start a topic branch first: git switch -c feat/" >&2 + exit 1 +fi +exit 0 diff --git a/scripts/git-hooks/pre-push b/scripts/git-hooks/pre-push new file mode 100755 index 00000000..3233708c --- /dev/null +++ b/scripts/git-hooks/pre-push @@ -0,0 +1,29 @@ +#!/bin/sh +# AniCraft pre-push guard (docs/release.md, "How changes land"). +# * `main` changes only through pull requests: pushing to the remote `main` is refused. +# (The one-time first publish of `main` sets ANICRAFT_FIRST_PUBLISH=1.) +# * Branches listed in the local git config as hidden (`git config --add anicraft.hidden `) +# never leave this machine, nor does anything built on them. +zero=0000000000000000000000000000000000000000 +hidden=$(git config --get-all anicraft.hidden 2>/dev/null) +while read -r local_ref local_sha remote_ref remote_sha; do + [ "$local_sha" = "$zero" ] && continue # deleting a remote ref + if [ "$remote_ref" = "refs/heads/main" ] && [ "$ANICRAFT_FIRST_PUBLISH" != "1" ]; then + echo "AniCraft: push blocked - main changes only through pull requests. Push a topic branch and open a PR." >&2 + exit 1 + fi + commit=$(git rev-parse "$local_sha^{commit}" 2>/dev/null) || continue + for b in $hidden; do + if [ "$local_ref" = "refs/heads/$b" ]; then + echo "AniCraft: push blocked - $b is a hidden local branch." >&2 + exit 1 + fi + for root in $(git rev-list --max-parents=0 "refs/heads/$b" 2>/dev/null); do + if git merge-base --is-ancestor "$root" "$commit" 2>/dev/null; then + echo "AniCraft: push blocked - $local_ref contains commits of the hidden branch $b." >&2 + exit 1 + fi + done + done +done +exit 0 diff --git a/src/app.rs b/src/app.rs new file mode 100644 index 00000000..3175ea30 --- /dev/null +++ b/src/app.rs @@ -0,0 +1,1002 @@ +//! The AniCraft shell: view state plus the frame loop. Document changes go through +//! `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 std::collections::HashSet; +use anicraft_engine::{Session, commands}; +use egui::{Key, Modifiers}; +use serde_json::{Value, json}; +use std::path::PathBuf; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Tool { + Select, + Subselect, + Transform, + Pen, + Pencil, + Rect, + Oval, + Star, + Line, + PaintBucket, + InkBottle, + Hand, + Zoom, +} + +/// Paint Bucket gap size: how wide an opening in an outline still counts as closed. In screen +/// points, so it feels the same at any zoom. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum GapSize { + #[default] + None, + Small, + Medium, + Large, +} + +impl GapSize { + pub const ALL: [GapSize; 4] = [GapSize::None, GapSize::Small, GapSize::Medium, GapSize::Large]; + pub fn label(self) -> &'static str { + match self { + GapSize::None => "Don't close gaps", + GapSize::Small => "Close small gaps", + GapSize::Medium => "Close medium gaps", + GapSize::Large => "Close large gaps", + } + } + pub fn screen_px(self) -> f32 { + match self { + GapSize::None => 0.0, + GapSize::Small => 4.0, + GapSize::Medium => 10.0, + GapSize::Large => 20.0, + } + } +} + +impl Tool { + pub const ALL: [Tool; 13] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Pen, Tool::Pencil, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Hand, Tool::Zoom]; + + pub fn label(self) -> &'static str { + match self { + Tool::Select => "Selection", + Tool::Subselect => "Subselection", + Tool::Transform => "Free Transform", + Tool::Pen => "Pen", + Tool::Pencil => "Pencil", + Tool::Rect => "Rectangle", + Tool::Oval => "Oval", + Tool::Star => "PolyStar", + Tool::Line => "Line", + Tool::PaintBucket => "Paint Bucket", + Tool::InkBottle => "Ink Bottle", + Tool::Hand => "Hand", + Tool::Zoom => "Zoom", + } + } + /// Default shortcut in the command-registry notation; the live key is in `App::keymap`. + pub fn shortcut(self) -> Option<&'static str> { + match self { + Tool::Select => Some("V"), + Tool::Subselect => Some("A"), + Tool::Transform => Some("Q"), + Tool::Pen => Some("P"), + Tool::Pencil => Some("Shift+Y"), + Tool::Rect => Some("R"), + Tool::Oval => Some("O"), + Tool::Star => None, + Tool::Line => Some("N"), + Tool::PaintBucket => Some("K"), + Tool::InkBottle => Some("S"), + Tool::Hand => Some("H"), + Tool::Zoom => Some("Z"), + } + } + pub fn hint(self) -> &'static str { + match self { + Tool::Select => "Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection.", + Tool::Subselect => "Click a shape to show its points. Drag points or handles to reshape (Shift adds to the point selection, drag on empty space to marquee points). Double-click an edge to add a point; Delete removes points. Right-click to make a point smooth or a corner.", + Tool::Pen => "Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point.", + Tool::Pencil => "Drag to draw freehand. The options bar sets Smooth, Straighten or Ink.", + Tool::Transform => "Drag a corner or edge to scale (Shift keeps proportions, Alt scales from the centre), just outside a corner to rotate (Shift snaps 15°), inside to move.", + Tool::Rect => "Drag to draw a rectangle. Shift draws a square.", + Tool::Oval => "Drag to draw an oval. Shift draws a circle.", + Tool::Star => "Drag from the centre to draw a star.", + Tool::Line => "Drag to draw a line. Shift snaps to 45°.", + Tool::PaintBucket => "Click inside an outline to fill it (on the layer's lines), or on a fill to recolour it. The gap size closes small openings.", + Tool::InkBottle => "Click a shape to give it the current stroke colour and width.", + Tool::Hand => "Drag to pan the stage. Space works with any tool.", + Tool::Zoom => "Click to zoom in, Alt-click to zoom out. Ctrl+wheel zooms anywhere.", + } + } +} + +/// Stage camera. +pub struct StageView { + pub zoom: f32, + pub pan: egui::Vec2, + pub fit: bool, +} + +/// In-progress pointer gesture on the stage. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Drag { + None, + Move { last: egui::Pos2 }, + Marquee { start: egui::Pos2, cur: egui::Pos2 }, + Shape { start: egui::Pos2, cur: egui::Pos2 }, + /// Subselection: dragging the selected points (stage position of the last frame). + Points { last: egui::Pos2 }, + /// Subselection: marquee over the selected shapes' anchors. + PointMarquee { start: egui::Pos2, cur: egui::Pos2 }, + /// Pencil stroke; the samples are in `App::pencil`. + Pencil, + /// Free transform: `applied` is the transform already sent to the engine this gesture. + Transform { kind: XfKind, start: egui::Pos2, bounds: [f32; 4], applied: anicraft_engine::geom::Affine }, + Pan, +} + +/// What a free-transform drag does. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum XfKind { + Move, + /// Handle position: -1/0/1 on each axis (corner, edge or centre). + Scale { hx: i8, hy: i8 }, + Rotate, +} + +/// A small text prompt standing in for native file dialogs (M0). +pub struct Prompt { + pub title: &'static str, + pub cmd: &'static str, + pub key: &'static str, + pub text: String, +} + +pub struct Status { + pub text: String, + pub error: bool, + pub at: f64, +} + +/// `--screenshot` state. +pub struct Shot { + pub path: PathBuf, + pub frames: u32, + pub requested: bool, +} + +pub const SHOT_FRAMES: u32 = 120; + +pub struct App { + pub s: Session, + pub tool: Tool, + pub view: StageView, + pub stage_cache: stage::Cache, + pub drag: Drag, + pub playing: bool, + pub looping: bool, + play_acc: f64, + pub onion: bool, + pub status: Option, + pub prompt: Option, + pub show_about: bool, + pub show_files: bool, + pub show_licenses: bool, + pub shot: Option, + pub cursor_stage: Option, + pub tl_scroll: f32, + /// Timeline frame width (zoom), in points. + pub tl_cell_w: f32, + /// Timeline vertical scroll, in rows. + pub tl_vscroll: f32, + pub tl_last_layer: Option, + pub library_sel: Option, + pub star_points: u32, + pub rect_radius: f32, + /// Pen path being drawn (view state until it is committed as one command). + pub pen: Option, + /// Pencil samples of the stroke in progress (stage space). + pub pencil: Vec, + pub pencil_mode: pathtools::PencilMode, + pub bucket_gap: GapSize, + /// Align panel: align to the stage rather than the selection's bounds. + pub align_to_stage: bool, + /// Subselection: selected anchors and handles. + pub points: Vec, + /// Selected frames on the timeline, and the drag on the frame grid. + pub frame_sel: Option, + pub tl_drag: timeline::TlDrag, + /// 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). + pub confirm: Option, + /// Undoable-tier confirmations the user chose not to see again this session. + pub skip_confirm: HashSet, + pub palette: Option, + pub show_shortcuts: bool, + /// The window close was intercepted because of unsaved changes. + pub close_dialog: bool, + pub allow_close: bool, + /// Close the window once the pending Save As succeeds. + pub close_after_save: bool, + pub prefs: prefs::Prefs, + pub show_prefs: bool, + /// Installed fonts, scanned off the UI thread on first need. + pub system_fonts: Option>, + fonts_rx: Option>, + /// Re-check which glyphs the active fonts have (after fonts change). + glyph_check: bool, + /// Document revision at the end of the last frame (edits schedule a repaint). + last_revision: u64, + title: String, + /// Keyboard shortcuts in effect (defaults plus the user's changes) and their lookup table. + pub keymap: keymap::Keymap, + shortcuts: Vec<(Modifiers, Key, &'static str)>, + /// The shortcut editor is waiting for a key press: global shortcuts pause. + pub key_capture: Option, +} + +/// How finished this version is, shown next to the version number (docs/release.md). +pub const RELEASE_STAGE: &str = "early alpha"; + +/// View-state keys, as Animate users know them: `(keys, action)`. +pub const VIEW_SHORTCUTS: &[(&str, &str)] = &[ + ("Ctrl+2", "view.fit"), + ("Alt+Shift+O", "view.onion"), + ("Ctrl+Alt+A", "view.select_all_frames"), + ("Ctrl+Alt+8", "view.align_to_stage"), + ("Ctrl+Enter", "view.test"), +]; + +impl App { + pub fn new(cc: &eframe::CreationContext<'_>, session: Session, shot: Option) -> App { + theme::apply(&cc.egui_ctx); + let shot_mode = shot.is_some(); + // Screenshot runs use defaults so automated checks are reproducible. + let prefs = if shot_mode { prefs::Prefs::default() } else { prefs::Prefs::load() }; + let keymap = keymap::Keymap::new(&prefs.shortcuts); + let shortcuts = keymap.table(); + let mut app = App { + s: session, + tool: Tool::Select, + view: StageView { zoom: 1.0, pan: egui::Vec2::ZERO, fit: true }, + stage_cache: stage::Cache::default(), + drag: Drag::None, + playing: false, + looping: true, + play_acc: 0.0, + onion: false, + status: None, + prompt: None, + show_about: false, + show_files: false, + show_licenses: false, + shot: shot.map(|path| Shot { path, frames: 0, requested: false }), + cursor_stage: None, + tl_scroll: 0.0, + tl_cell_w: timeline::CELL_DEFAULT, + tl_vscroll: 0.0, + tl_last_layer: None, + library_sel: Some(0), + star_points: 5, + rect_radius: 0.0, + pen: None, + pencil: Vec::new(), + pencil_mode: pathtools::PencilMode::default(), + bucket_gap: GapSize::default(), + align_to_stage: false, + points: Vec::new(), + frame_sel: None, + tl_drag: timeline::TlDrag::None, + timeline_focus: false, + confirm: None, + skip_confirm: HashSet::new(), + palette: None, + show_shortcuts: false, + close_dialog: false, + allow_close: false, + close_after_save: false, + prefs, + show_prefs: false, + system_fonts: None, + fonts_rx: None, + glyph_check: true, + last_revision: 0, + title: String::new(), + keymap, + shortcuts, + key_capture: None, + }; + app.apply_prefs(&cc.egui_ctx); + app.status_ok("Welcome to AniCraft. Press Enter to play the sample animation."); + app + } + + pub fn status_ok(&mut self, text: impl Into) { + self.status = Some(Status { text: text.into(), error: false, at: 0.0 }); + } + pub fn status_err(&mut self, text: impl Into) { + self.status = Some(Status { text: text.into(), error: true, at: 0.0 }); + } + + /// Runs an engine command, reporting failures in the status bar. + pub fn run(&mut self, id: &str, params: Value) -> Option { + match self.s.execute(id, ¶ms) { + Ok(v) => Some(v), + Err(e) => { + self.status_err(e.to_string()); + None + } + } + } + + // ----- preferences ---------------------------------------------------------------------- + + /// Applies scale and fonts from `self.prefs`. System fonts need the font scan; until it + /// finishes the bundled fonts stay in place, and they are swapped in when it completes. + pub fn apply_prefs(&mut self, ctx: &egui::Context) { + ctx.set_zoom_factor(self.prefs.ui_scale); + self.keymap = keymap::Keymap::new(&self.prefs.shortcuts); + self.shortcuts = self.keymap.table(); + let wants_system = [&self.prefs.ui_font, &self.prefs.data_font].iter().any(|f| matches!(f, prefs::FontChoice::System(_))); + if wants_system && self.system_fonts.is_none() { + self.scan_system_fonts(); + } + let load = |choice: &prefs::FontChoice, sys: Option<&prefs::SystemFonts>| -> Option { + match (choice, sys) { + (prefs::FontChoice::System(name), Some(s)) => s.regular(name).map(|(b, i)| (name.clone(), b, i)), + _ => None, + } + }; + let sys = self.system_fonts.clone(); + let ui_font = load(&self.prefs.ui_font, sys.as_deref()); + let data_font = load(&self.prefs.data_font, sys.as_deref()); + if sys.is_some() { + let missing: Vec = [(&self.prefs.ui_font, ui_font.is_some()), (&self.prefs.data_font, data_font.is_some())] + .into_iter() + .filter_map(|(c, ok)| match c { + prefs::FontChoice::System(name) if !ok => Some(name.clone()), + _ => None, + }) + .collect(); + for name in missing { + self.status_err(format!("Font “{name}” is not installed; using the bundled font")); + } + } + theme::install_fonts(ctx, ui_font.as_ref(), data_font.as_ref()); + self.glyph_check = true; + } + + pub fn open_prefs(&mut self) { + self.show_prefs = true; + self.scan_system_fonts(); + } + + /// Changes preferences: applies them live and saves them. + pub fn set_prefs(&mut self, ctx: &egui::Context, p: prefs::Prefs) { + let p = p.sanitized(); + if p == self.prefs { + return; + } + self.prefs = p; + self.apply_prefs(ctx); + if self.shot.is_none() + && let Err(e) = self.prefs.save() + { + self.status_err(format!("Could not save preferences: {e}")); + } + } + + /// Starts scanning installed fonts on a background thread (once). + pub fn scan_system_fonts(&mut self) { + if self.system_fonts.is_some() || self.fonts_rx.is_some() { + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("anicraft-fonts".into()).spawn(move || { + let _ = tx.send(prefs::SystemFonts::scan()); + }); + if spawned.is_ok() { + self.fonts_rx = Some(rx); + } + } + + fn poll_font_scan(&mut self, ctx: &egui::Context) { + let Some(rx) = &self.fonts_rx else { return }; + match rx.try_recv() { + Ok(fonts) => { + self.system_fonts = Some(std::sync::Arc::new(fonts)); + self.fonts_rx = None; + self.apply_prefs(ctx); + } + Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(50)), + Err(std::sync::mpsc::TryRecvError::Disconnected) => self.fonts_rx = None, + } + } + + /// `--open` at start-up: shows a panel, for visual checks and documentation screenshots. + pub fn open_panel(&mut self, which: Option<&str>) { + match which { + Some("palette") => self.palette = Some(dialogs::Palette { query: "key".into(), selected: 0 }), + Some("shortcuts") => self.show_shortcuts = true, + Some("files") => self.show_files = true, + Some("licenses") => self.show_licenses = true, + Some("zoom") => { + // 300% on the ball: many tiles, edges cross shapes (seam check). + self.view.fit = false; + self.view.zoom = 3.0; + self.view.pan = egui::vec2(1200.0, 300.0); + } + Some("prefs") => { + self.show_prefs = true; + self.scan_system_fonts(); + } + Some("confirm") => self.request("layer.delete", json!({})), + Some("transform") => { + self.tool = Tool::Transform; + self.run("layer.select", json!({"index": 0})); + self.run("edit.select_all", json!({})); + } + Some("points") => { + // A pencil stroke and a pen path being edited, with one smooth point selected. + let wave: Vec<[f32; 2]> = (0..=240).map(|i| [140.0 + i as f32 * 1.5, 330.0 + (i as f32 * 0.06).sin() * 28.0]).collect(); + self.run("draw.freehand", json!({"points": wave, "stroke_width": 3})); + if let Some(v) = self.run("draw.path", json!({"d": "M 520 90 L 700 120 L 660 260 L 540 230 Z"})) { + let id = anicraft_engine::doc::ElementId(v["element"].as_u64().unwrap_or(0)); + self.run("path.convert_point", json!({"id": id.0, "cmd": 1, "smooth": true})); + self.points = vec![(id, 1, anicraft_engine::geom::edit::ANCHOR)]; + } + self.tool = Tool::Subselect; + } + Some("frames") => { + // Frames 8–20 selected on the top three layers, with a keyframe drag in progress: + // 6 frames later and one layer down. + let layers = &self.s.doc.timeline.layers; + if let (Some(a), Some(b)) = (layers.first(), layers.get(2)) { + self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 7), head: (b.id, 19) }); + self.tl_drag = timeline::TlDrag::Move { grab: 10, by: 6, grab_row: 0, rows_by: 1 }; + } + self.run("timeline.goto", json!({"frame": 10})); + } + Some("bucket") => { + // A hand-drawn outline with no fill, filled by the bucket underneath its line. + let loop_pts: Vec<[f32; 2]> = (0..=72) + .map(|i| { + let a = i as f32 / 72.0 * std::f32::consts::TAU; + let r = 110.0 + 18.0 * (a * 5.0).sin(); + [640.0 + r * a.cos(), 330.0 + r * a.sin()] + }) + .collect(); + self.run("draw.freehand", json!({"points": loop_pts, "closed": true, "stroke": "#14141a", "stroke_width": 4})); + self.run("paint.bucket", json!({"x": 640, "y": 330, "color": "#ff9f43"})); + self.tool = Tool::PaintBucket; + self.bucket_gap = GapSize::Small; + self.run("edit.deselect", json!({})); + } + Some("tlwide") => { + // Zoomed in: wide frames, playhead on frame 1 and frame 4. + self.tl_cell_w = 48.0; + self.run("timeline.goto", json!({"frame": 3})); + } + Some("tlzoom") => { + // A long timeline zoomed out: the ruler thins its labels, the scrollbar shows. + self.run("timeline.insert_frame", json!({"frame": 47, "count": 600})); + self.tl_cell_w = 4.0; + self.tl_scroll = 120.0; + } + Some("span") => { + // Stretching the Star layer's span by its end, with the length readout. + if let Some(l) = self.s.doc.timeline.layers.get(1) + && let Some(k) = l.keyframes.first() + { + self.tl_drag = timeline::TlDrag::Span { layer: l.id, start: k.start, end: k.end(), to: k.end() + 6 }; + } + } + Some("pen") => { + // A pen path still being drawn: a corner, a smooth point with handles, a corner. + self.tool = Tool::Pen; + let k = |x: f32, y: f32| [anicraft_engine::geom::Vec2::new(x, y); 3]; + let mut curve = k(260.0, 140.0); + curve[1] = anicraft_engine::geom::Vec2::new(220.0, 180.0); + curve[2] = anicraft_engine::geom::Vec2::new(300.0, 100.0); + self.pen = Some(pathtools::PenPath { knots: vec![k(120.0, 160.0), curve, k(380.0, 150.0)], dragging: false }); + } + _ => {} + } + } + + /// 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 + } + + /// The single entry point for user-initiated commands: asks first when the engine says the + /// command needs confirmation (ADR 0004), otherwise runs it. + pub fn request(&mut self, id: &str, params: Value) { + if let Some(c) = self.s.confirmation(id, ¶ms) + && (c.irreversible || !self.skip_confirm.contains(id)) + { + self.playing = false; + self.confirm = Some(dialogs::PendingConfirm { id: id.to_string(), params, conf: c, dont_ask: false }); + return; + } + self.perform(id, params); + } + + /// Runs a command and reports the outcome; routine destructive edits say how to undo. + pub fn perform(&mut self, id: &str, params: Value) -> Option { + let selected = self.s.selection.len(); + let v = self.run(id, params)?; + match id { + "file.new" | "file.new_sample" | "file.open" => { + self.view.fit = true; + self.library_sel = (!self.s.doc.library.is_empty()).then_some(0); + match v.get("report").and_then(Value::as_str) { + // An imported file: say what came across and what didn't, and that saving + // makes a new .anicraft document. + Some(r) => self.status_ok(format!("{r} Save to keep it as an AniCraft document.")), + None => self.status_ok(if id == "file.open" { "Opened" } else { "New document" }), + } + } + "file.save" | "file.save_as" => { + self.status_ok(format!("Saved {}", v["saved"].as_str().unwrap_or(""))); + if self.close_after_save { + self.allow_close = true; + } + } + "file.export_png" | "file.export_png_sequence" | "file.export_gif" => self.status_ok(format!("Exported {}", v.get("written").or_else(|| v.get("dir")).and_then(Value::as_str).unwrap_or(""))), + "edit.undo" => self.status_ok(format!("Undid {}", v["undone"].as_str().unwrap_or(""))), + "edit.redo" => self.status_ok(format!("Redid {}", v["redone"].as_str().unwrap_or(""))), + "edit.delete" => self.status_ok(format!("Deleted {} {} — Ctrl+Z to undo", selected, if selected == 1 { "element" } else { "elements" })), + "layer.delete" => self.status_ok("Deleted layer — Ctrl+Z to undo"), + "timeline.clear_keyframe" => { + let n = v["cleared"].as_u64().unwrap_or(1); + self.status_ok(format!("Cleared {} — Ctrl+Z to undo", if n == 1 { "keyframe".to_string() } else { format!("{n} keyframes") })); + } + "timeline.copy_frames" | "timeline.cut_frames" | "timeline.paste_frames" => { + let n = v["copied"].as_u64().or_else(|| v["cut"].as_u64()).or_else(|| v["pasted"].as_u64()).unwrap_or(0); + let what = format!("{n} {}", if n == 1 { "frame" } else { "frames" }); + self.status_ok(match id { + "timeline.copy_frames" => format!("Copied {what}"), + "timeline.cut_frames" => format!("Cut {what} — Ctrl+Z to undo"), + _ => format!("Pasted {what} — Ctrl+Z to undo"), + }); + } + "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") })); + } + _ => {} + } + Some(v) + } + + /// Invokes a command from a menu, shortcut, palette or context menu, asking for a path or + /// name first when it needs one. + pub fn invoke(&mut self, id: &'static str) { + // Ctrl+X/C/V act on frames when the timeline was used last and has frames to act on + // (Animate's Ctrl+Alt+X/C/V work anywhere). + let id: &'static str = match id { + "edit.cut" if self.timeline_focus && self.frame_sel.is_some() => "timeline.cut_frames", + "edit.copy" if self.timeline_focus && self.frame_sel.is_some() => "timeline.copy_frames", + "edit.paste" if self.timeline_focus && !self.s.frame_clipboard.is_empty() => "timeline.paste_frames", + other => other, + }; + if id == "timeline.paste_frames" + && let Some(p) = timeline::paste_params(self) + { + self.request(id, p); + return; + } + if id == "edit.paste" { + // Paste in the centre of what you are looking at. + let c = self.view_center_stage(); + self.request(id, json!({"x": c.x, "y": c.y})); + return; + } + let prompt = match id { + "file.open" => Some(("Open document", "path", "animation.anicraft".to_string())), + "file.save" if self.s.path.is_none() => Some(("Save document as", "path", "animation.anicraft".to_string())), + "file.save_as" => Some(("Save document as", "path", self.s.path.as_ref().map_or_else(|| "animation.anicraft".to_string(), |p| p.display().to_string()))), + "layer.rename" => Some(("Rename layer", "name", self.s.active_layer().map_or_else(String::new, |l| l.name.clone()))), + "file.export_png" => Some(("Export frame as PNG", "path", format!("frame_{:04}.png", self.s.frame + 1))), + "file.export_png_sequence" => Some(("Export PNG sequence to folder", "dir", "frames".to_string())), + "file.export_gif" => Some(("Export animated GIF", "path", "animation.gif".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."); + 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; + match platform::file_dialog(id, title, &text) { + Some(path) => self.request(id, json!({ key: path.display().to_string() })), + None => self.close_after_save = false, + } + return; + } + self.prompt = Some(Prompt { title, cmd: id, key, text }); + return; + } + // Frame commands act on the frame selection (F5 over 3 frames on 2 layers inserts 3 + // frames on each). + if timeline::RANGE_COMMANDS.contains(&id) + && let Some(p) = timeline::range_params(self) + { + self.request(id, p); + return; + } + self.request(id, json!({})); + } + + /// The stage point at the centre of the visible canvas. + pub fn view_center_stage(&self) -> egui::Vec2 { + let size = egui::vec2(self.s.doc.stage.width as f32, self.s.doc.stage.height as f32); + size * 0.5 - self.view.pan / self.view.zoom.max(1e-3) + } + + pub fn zoom_about(&mut self, canvas: egui::Rect, screen: egui::Pos2, new_zoom: f32) { + let new_zoom = new_zoom.clamp(0.05, 64.0); + let size = egui::vec2(self.s.doc.stage.width as f32, self.s.doc.stage.height as f32); + let origin = canvas.center() + self.view.pan - size * self.view.zoom * 0.5; + let stage_pt = (screen - origin) / self.view.zoom; + let new_origin = screen - stage_pt * new_zoom; + self.view.pan = new_origin - canvas.center() + size * new_zoom * 0.5; + self.view.zoom = new_zoom; + } + + pub fn toggle_play(&mut self) { + self.playing = !self.playing; + self.play_acc = 0.0; + if self.playing && self.s.frame + 1 >= self.s.frame_count() { + self.s.set_frame(0); + } + } + + fn tick_playback(&mut self, ctx: &egui::Context) { + if !self.playing { + return; + } + let fps = f64::from(self.s.doc.stage.fps.max(1.0)); + self.play_acc += f64::from(ctx.input(|i| i.stable_dt)).min(0.25); + let n = self.s.frame_count(); + while self.play_acc >= 1.0 / fps { + self.play_acc -= 1.0 / fps; + if self.s.frame + 1 >= n { + if self.looping { + self.s.set_frame(0); + } else { + self.playing = false; + break; + } + } else { + self.s.set_frame(self.s.frame + 1); + } + } + ctx.request_repaint(); + } + + fn handle_shortcuts(&mut self, ctx: &egui::Context) { + // While the shortcut editor records a key, every key press belongs to it. + if self.modal_open() || self.key_capture.is_some() { + return; + } + // Palette, shortcut sheet, preferences and quit work even while a text field has focus. + // Preferences: Ctrl+U (the shortcut Animate users know) and Ctrl/⌘+, (platform norm). + let (palette, sheet, prefs_key, quit) = ctx.input_mut(|i| { + // The shortcut sheet first: Ctrl+Alt+Shift+K (Animate's Keyboard Shortcuts) must not + // be taken by Ctrl+K, which egui would match with the extra modifiers ignored. + let sheet = i.consume_key(Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT, Key::K) || i.consume_key(Modifiers::NONE, Key::F1); + ( + i.consume_key(Modifiers::COMMAND, Key::K) || i.consume_key(Modifiers::COMMAND | Modifiers::SHIFT, Key::P), + sheet, + i.consume_key(Modifiers::COMMAND, Key::U) || i.consume_key(Modifiers::COMMAND, Key::Comma), + i.consume_key(Modifiers::COMMAND, Key::Q), + ) + }); + if prefs_key { + self.open_prefs(); + } + if quit { + // Goes through the close guard, so unsaved work is never lost. + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + if palette { + self.palette = if self.palette.is_some() { None } else { Some(dialogs::Palette::default()) }; + } + if sheet { + self.show_shortcuts = !self.show_shortcuts; + } + if ctx.egui_wants_keyboard_input() || self.palette.is_some() { + return; + } + pathtools::consume_keys(self, ctx); + let mut fire: Vec<&'static str> = Vec::new(); + let mut tool = None; + let mut play = false; + let mut nudge = egui::Vec2::ZERO; + ctx.input_mut(|i| { + for (m, k, id) in &self.shortcuts { + if i.consume_key(*m, *k) { + fire.push(id); + } + } + if i.consume_key(Modifiers::NONE, Key::Enter) { + play = true; + } + let step = if i.modifiers.shift { 10.0 } else { 1.0 }; + for (k, d) in [(Key::ArrowLeft, egui::vec2(-step, 0.0)), (Key::ArrowRight, egui::vec2(step, 0.0)), (Key::ArrowUp, egui::vec2(0.0, -step)), (Key::ArrowDown, egui::vec2(0.0, step))] { + if i.key_pressed(k) && !i.modifiers.command { + nudge += d; + } + } + }); + for id in fire { + match id { + // View-state keys (Animate's), handled here rather than in the engine. + "view.fit" => self.view.fit = true, + "view.onion" => self.onion = !self.onion, + "view.align_to_stage" => { + self.align_to_stage = !self.align_to_stage; + self.status_ok(if self.align_to_stage { "Align: to stage" } else { "Align: to the selection" }); + } + "view.select_all_frames" => { + let layers = &self.s.doc.timeline.layers; + if let (Some(a), Some(b)) = (layers.first(), layers.last()) { + let last = self.s.frame_count().saturating_sub(1); + self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 0), head: (b.id, last) }); + self.timeline_focus = true; + self.run("timeline.goto", json!({"frame": 0})); + } + } + "view.test" => { + // Test: play from frame 1. + self.run("timeline.goto", json!({"frame": 0})); + if !self.playing { + self.toggle_play(); + } + } + id if id.starts_with("tool.") => tool = keymap::tool_for(id).or(tool), + _ => self.invoke(id), + } + } + if let Some(t) = tool { + self.tool = t; + } + if play { + self.toggle_play(); + } + if nudge != egui::Vec2::ZERO && !self.s.selection.is_empty() { + self.run("element.translate", json!({"dx": nudge.x, "dy": nudge.y})); + } + } + + fn handle_screenshot(&mut self, ctx: &egui::Context) { + let Some(shot) = &mut self.shot else { return }; + shot.frames += 1; + ctx.request_repaint(); + let image = ctx.input(|i| { + i.raw.events.iter().find_map(|e| match e { + egui::Event::Screenshot { image, .. } => Some(image.clone()), + _ => None, + }) + }); + if let Some(img) = image { + let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); + let result = anicraft_render::encode_png(img.size[0] as u32, img.size[1] as u32, &rgba).map_err(|e| e.to_string()).and_then(|png| { + if let Some(dir) = shot.path.parent() + && !dir.as_os_str().is_empty() + { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + std::fs::write(&shot.path, png).map_err(|e| e.to_string()) + }); + match result { + Ok(()) => println!("screenshot saved to {}", shot.path.display()), + Err(e) => eprintln!("screenshot failed: {e}"), + } + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + return; + } + if shot.frames >= SHOT_FRAMES && !shot.requested { + shot.requested = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::default())); + } + if shot.frames > SHOT_FRAMES + 600 { + eprintln!("screenshot: the renderer never delivered a frame"); + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + + fn update_title(&mut self, ctx: &egui::Context) { + let name = self.s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned()); + let title = format!("AniCraft — {name}{}", if self.s.is_dirty() { " •" } else { "" }); + if title != self.title { + ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone())); + self.title = title; + } + } + + fn prompt_window(&mut self, ctx: &egui::Context) { + let Some(p) = &mut self.prompt else { return }; + let mut submit = false; + let mut cancel = false; + egui::Window::new(p.title).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| { + ui.set_min_width(360.0); + let r = ui.add(egui::TextEdit::singleline(&mut p.text).desired_width(f32::INFINITY)); + r.request_focus(); + if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { + submit = true; + } + ui.horizontal(|ui| { + if ui.button("OK").clicked() { + submit = true; + } + if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { + cancel = true; + } + }); + }); + if submit { + if let Some(p) = self.prompt.take() { + // Through `request`, so opening over unsaved work or saving over a file asks first. + self.request(p.cmd, json!({ p.key: p.text })); + } + } else if cancel { + self.prompt = None; + self.close_after_save = false; + } + } + + 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.heading("AniCraft"); + ui.label(format!("Version {} · {RELEASE_STAGE}", env!("CARGO_PKG_VERSION"))); + ui.label("Open-source 2D vector animation studio, written in Rust."); + ui.label(format!("{} engine commands — all available headless via anicraft-cli.", commands().len())); + ui.colored_label(T.text_dim, "MIT OR Apache-2.0"); + ui.label(theme::text(theme::Type::Caption, format!("Typefaces: {}", theme::font_summary()))); + }); + self.show_about = open; + } + + /// Help › Project Files: where the docs, source and saved files live, with buttons to open them. + fn files_window(&mut self, ctx: &egui::Context) { + let mut open = self.show_files; + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let entries: [(&str, PathBuf); 12] = [ + ("Project folder", root.clone()), + ("Requirements & technology", root.join("docs").join("requirements.md")), + ("Architecture philosophy", root.join("docs").join("architecture.md")), + ("Roadmap", root.join("docs").join("roadmap.md")), + ("Performance & budgets", root.join("docs").join("performance.md")), + ("Decision records (ADRs)", root.join("docs").join("adr")), + ("Legal compliance", root.join("docs").join("legal").join("compliance.md")), + ("README", root.join("README.md")), + ("Agent / contributor guide", root.join("AGENTS.md")), + ("Engine crates (source)", root.join("crates")), + ("Desktop app (source)", root.join("src")), + ("Screenshots", root.join("shots")), + ]; + let mut opened: Option> = None; + egui::Window::new("Project Files").open(&mut open).collapsible(false).resizable(false).default_width(620.0).show(ctx, |ui| { + ui.label(theme::text(theme::Type::Label, "Where AniCraft's documents and files are on this computer")); + ui.add_space(4.0); + egui::Grid::new("files").num_columns(3).spacing([10.0, 6.0]).striped(true).show(ui, |ui| { + for (label, path) in &entries { + ui.label(theme::text(theme::Type::Body, *label).strong()); + ui.label(theme::text(theme::Type::Path, path.display().to_string()).color(if path.exists() { T.text } else { T.text_faint })); + if ui.add_enabled(path.exists(), egui::Button::new("Open")).clicked() { + opened = Some(open_in_system(path)); + } + ui.end_row(); + } + let doc = self.s.path.as_ref().map_or_else(|| "not saved yet (File › Save)".to_string(), |p| p.display().to_string()); + ui.label(theme::text(theme::Type::Body, "Current document").strong()); + ui.label(theme::text(theme::Type::Path, doc)); + ui.end_row(); + }); + ui.add_space(4.0); + ui.label(theme::text(theme::Type::Caption, "Saved documents and exports go where you type in the save box; a plain name lands in the folder AniCraft was started from.")); + }); + match opened { + Some(Err(e)) => self.status_err(e), + Some(Ok(())) => self.status_ok("Opened in your system's file viewer"), + None => {} + } + self.show_files = open; + } +} + +/// Opens a file or folder with the operating system's default handler. +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); + c + } else if cfg!(target_os = "macos") { + let mut c = std::process::Command::new("open"); + c.arg(path); + c + } else { + let mut c = std::process::Command::new("xdg-open"); + c.arg(path); + c + }; + cmd.spawn().map(|_| ()).map_err(|e| format!("could not open {}: {e}", path.display())) +} + +impl eframe::App for App { + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + let ctx = ui.ctx().clone(); + self.handle_screenshot(&ctx); + self.poll_font_scan(&ctx); + if self.glyph_check { + // Fonts installed last frame are live now: can they draw the macOS key symbols? + let ok = ctx.fonts_mut(|f| f.has_glyphs(&theme::font(theme::Type::Key), "⌘⇧⌥")); + platform::set_mac_glyphs(ok); + self.glyph_check = false; + } + self.handle_shortcuts(&ctx); + // Switching away from a path tool keeps its work: a Pen path in progress is finished. + if self.tool != Tool::Pen && self.pen.is_some() { + pathtools::commit_pen(self, false); + } + if self.tool != Tool::Subselect { + self.points.clear(); + } + pathtools::upkeep(self); + self.tick_playback(&ctx); + self.update_title(&ctx); + if let Some(st) = &mut self.status + && st.at == 0.0 { + st.at = ctx.input(|i| i.time); + } + + let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2)); + egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui)); + egui::Panel::top("edit_bar").exact_size(theme::TARGET + 8.0).frame(bar(T.panel)).show(ui, |ui| panels::edit_bar(self, ui)); + egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui)); + egui::Panel::left("tools").resizable(false).exact_size(theme::TOOL_BUTTON + 12.0).frame(egui::Frame::NONE.fill(T.panel).inner_margin(egui::Margin::symmetric(6, 8))).show(ui, |ui| panels::tools(self, ui)); + egui::Panel::right("properties").resizable(true).default_size(292.0).frame(egui::Frame::NONE.fill(T.panel).inner_margin(egui::Margin::same(0))).show(ui, |ui| panels::right(self, ui)); + egui::Panel::bottom("timeline").resizable(true).default_size(292.0).frame(egui::Frame::NONE.fill(T.panel).inner_margin(egui::Margin::same(0))).show(ui, |ui| timeline::show(self, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(T.pasteboard)).show(ui, |ui| stage::show(self, ui)); + + self.prompt_window(&ctx); + self.about_window(&ctx); + dialogs::show_all(self, &ctx); + + // Never lose work on close: intercept it while there are unsaved changes. + if self.allow_close { + if self.close_after_save || self.close_dialog { + self.close_after_save = false; + self.close_dialog = false; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } else if ctx.input(|i| i.viewport().close_requested()) && self.shot.is_none() && self.s.is_dirty() { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.playing = false; + self.close_dialog = true; + } + 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()) { + self.s.end_gesture(); + } + + // 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. + if self.s.revision != self.last_revision { + self.last_revision = self.s.revision; + ctx.request_repaint(); + } + } +} diff --git a/src/dialogs.rs b/src/dialogs.rs new file mode 100644 index 00000000..86535381 --- /dev/null +++ b/src/dialogs.rs @@ -0,0 +1,800 @@ +//! Modal and floating dialogs: destructive-action confirmation (ADR 0004), the unsaved-changes +//! guard on close, the command palette (Ctrl+K) and the keyboard-shortcut sheet (F1). + +use crate::app::{App, Tool}; +use crate::prefs::{FontChoice, RenderMode}; +use crate::theme::{T, Type, text, with_type}; +use anicraft_engine::confirm::Confirmation; +use anicraft_engine::{CommandSpec, commands}; +use egui::{Color32, Key}; +use serde_json::{Value, json}; + +/// A command waiting for the user's yes/no. +pub struct PendingConfirm { + pub id: String, + pub params: Value, + pub conf: Confirmation, + pub dont_ask: bool, +} + +#[derive(Default)] +pub struct Palette { + pub query: String, + pub selected: usize, +} + +pub fn show_all(app: &mut App, ctx: &egui::Context) { + preferences(app, ctx); + licenses(app, ctx); + confirm_modal(app, ctx); + close_modal(app, ctx); + palette(app, ctx); + shortcut_sheet(app, ctx); +} + +fn danger_button(label: &str) -> egui::Button<'static> { + egui::Button::new(text(Type::Body, label).color(Color32::WHITE).strong()).fill(T.danger).min_size(egui::vec2(120.0, crate::theme::TARGET + 4.0)) +} + +fn confirm_modal(app: &mut App, ctx: &egui::Context) { + let Some(p) = &mut app.confirm else { return }; + let mut decision: Option = None; + let irreversible = p.conf.irreversible; + egui::Modal::new(egui::Id::new("confirm")).show(ctx, |ui| { + ui.set_width(420.0); + ui.add_space(4.0); + ui.label(text(Type::Title, p.conf.title.clone())); + ui.add_space(6.0); + ui.label(text(Type::Body, p.conf.message.clone()).color(T.text_dim)); + ui.add_space(4.0); + if irreversible { + ui.label(text(Type::Caption, "This cannot be undone.").color(T.error)); + } else { + crate::theme::checkbox(ui, &mut p.dont_ask, text(Type::Caption, "Don't ask again this session").color(T.text_dim)); + } + ui.add_space(10.0); + ui.horizontal(|ui| { + if ui.add(egui::Button::new("Cancel").min_size(egui::vec2(96.0, crate::theme::TARGET + 4.0))).clicked() { + decision = Some(false); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(danger_button(&p.conf.action)).clicked() { + decision = Some(true); + } + }); + }); + ui.add_space(2.0); + let hint = if irreversible { "Esc cancels · click the red button to proceed" } else { "Enter confirms · Esc cancels" }; + ui.label(text(Type::Caption, hint)); + }); + // Irreversible actions are never one keystroke away: Enter does not confirm them. + let (esc, enter) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, Key::Escape), i.consume_key(egui::Modifiers::NONE, Key::Enter))); + if esc { + decision = Some(false); + } else if enter && !irreversible { + decision = Some(true); + } + match decision { + Some(true) => { + if let Some(p) = app.confirm.take() { + if p.dont_ask { + app.skip_confirm.insert(p.id.clone()); + } + let mut params = p.params; + if let Some(obj) = params.as_object_mut() { + obj.insert("confirm".into(), json!(true)); + } + app.perform(&p.id, params); + } + } + Some(false) => { + app.confirm = None; + app.close_after_save = false; + app.status_ok("Cancelled"); + } + None => {} + } +} + +fn close_modal(app: &mut App, ctx: &egui::Context) { + if !app.close_dialog || app.prompt.is_some() || app.confirm.is_some() { + return; + } + #[derive(PartialEq)] + enum Choice { + Save, + Discard, + Cancel, + } + let mut choice = None; + let name = app.s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned()); + egui::Modal::new(egui::Id::new("close_guard")).show(ctx, |ui| { + ui.set_width(440.0); + ui.label(text(Type::Title, format!("Save changes to “{name}” before closing?"))); + ui.add_space(6.0); + ui.label(text(Type::Body, "If you don't save, your changes since the last save will be lost.").color(T.text_dim)); + ui.add_space(12.0); + ui.horizontal(|ui| { + if ui.add(danger_button("Don't Save")).clicked() { + choice = Some(Choice::Discard); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(egui::Button::new(text(Type::Body, "Save").strong().color(Color32::WHITE)).fill(T.accent).min_size(egui::vec2(96.0, crate::theme::TARGET + 4.0))).clicked() { + choice = Some(Choice::Save); + } + if ui.add(egui::Button::new("Cancel").min_size(egui::vec2(96.0, crate::theme::TARGET + 4.0))).clicked() { + choice = Some(Choice::Cancel); + } + }); + }); + ui.label(text(Type::Caption, "Enter saves · Esc cancels")); + }); + let (esc, enter) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, Key::Escape), i.consume_key(egui::Modifiers::NONE, Key::Enter))); + if esc { + choice = Some(Choice::Cancel); + } else if enter { + choice = Some(Choice::Save); + } + match choice { + Some(Choice::Save) => { + app.close_dialog = false; + app.close_after_save = true; + if app.s.path.is_some() { + app.perform("file.save", json!({})); + } else { + app.invoke("file.save_as"); + } + } + Some(Choice::Discard) => { + app.allow_close = true; + } + Some(Choice::Cancel) => { + app.close_dialog = false; + } + None => {} + } +} + +// ----- command palette -------------------------------------------------------------------------- + +#[derive(Clone)] +enum Entry { + Command(CommandSpec), + Tool(Tool), + View(&'static str, &'static str, fn(&mut App)), +} + +impl Entry { + fn title(&self) -> String { + match self { + Entry::Command(c) => { + if c.menu.is_empty() { + c.label.to_string() + } else { + format!("{} › {}", c.menu.replace('/', " › "), c.label) + } + } + Entry::Tool(t) => format!("Tool › {}", t.label()), + Entry::View(name, _, _) => format!("View › {name}"), + } + } + fn shortcut(&self, km: &crate::keymap::Keymap) -> String { + match self { + 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(), + } + } +} + +/// 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.export_png" | "file.export_gif" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename") { + return true; + } + let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}'); + inner.split(',').map(str::trim).filter(|k| !k.is_empty()).all(|k| k.split(':').next().is_some_and(|name| name.trim().ends_with('?'))) +} + +fn entries() -> Vec { + let mut v: Vec = commands().into_iter().filter(runnable).map(Entry::Command).collect(); + v.extend(Tool::ALL.iter().map(|t| Entry::Tool(*t))); + v.push(Entry::View("Play / Stop", "Enter", App::toggle_play)); + v.push(Entry::View("Onion Skin", "", |a| a.onion = !a.onion)); + v.push(Entry::View("Fit Stage in Window", "Ctrl+0", |a| a.view.fit = true)); + v.push(Entry::View("Keyboard Shortcuts", "F1", |a| a.show_shortcuts = true)); + v.push(Entry::View("Project Files & Docs", "", |a| a.show_files = true)); + v.push(Entry::View("Licenses & Notices", "", |a| a.show_licenses = true)); + v.push(Entry::View("Preferences", "Ctrl+U", App::open_prefs)); + v +} + +/// Subsequence match score (higher is better); `None` when not all query chars appear in order. +fn fuzzy(query: &str, text: &str) -> Option { + let text = text.to_lowercase(); + let mut score = 0; + let mut last = 0usize; + let mut chars = text.char_indices(); + for q in query.to_lowercase().chars().filter(|c| !c.is_whitespace()) { + let (i, _) = chars.by_ref().find(|(_, c)| *c == q)?; + score += if i == last { 3 } else { 1 }; + if i == 0 || text[..i].ends_with([' ', '›', '.', '_']) { + score += 4; + } + last = i + q.len_utf8(); + } + Some(score - (text.len() as i32) / 16) +} + +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 matches: Vec<(i32, Entry, String)> = + all.into_iter().filter_map(|e| { + let key = e.shortcut(km); + fuzzy(&p.query, &format!("{} {key}", e.title())).map(|s| (s, e, key)) + }).collect(); + matches.sort_by_key(|m| std::cmp::Reverse(m.0)); + matches.truncate(14); + p.selected = p.selected.min(matches.len().saturating_sub(1)); + let (up, down, enter, esc) = ctx.input_mut(|i| { + ( + i.consume_key(egui::Modifiers::NONE, Key::ArrowUp), + i.consume_key(egui::Modifiers::NONE, Key::ArrowDown), + i.consume_key(egui::Modifiers::NONE, Key::Enter), + i.consume_key(egui::Modifiers::NONE, Key::Escape), + ) + }); + if up { + p.selected = p.selected.saturating_sub(1); + } + if down && p.selected + 1 < matches.len() { + p.selected += 1; + } + let mut run: Option = None; + let mut close = esc; + let selected = p.selected; + egui::Area::new(egui::Id::new("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, 70.0]).show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(T.panel_alt).inner_margin(egui::Margin::same(10)).show(ui, |ui| { + ui.set_width(560.0); + let r = ui.add(egui::TextEdit::singleline(&mut p.query).hint_text("Type a command, tool or setting…").desired_width(f32::INFINITY).font(egui::TextStyle::Heading)); + r.request_focus(); + if r.changed() { + p.selected = 0; + } + ui.add_space(6.0); + if matches.is_empty() { + ui.label(text(Type::Caption, "No matching commands")); + } + for (i, (_, e, key)) in matches.iter().enumerate() { + let sel = i == selected; + let resp = ui + .horizontal(|ui| { + let lab = ui.selectable_label(sel, e.title()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(text(Type::Key, crate::platform::shortcut_label(key))); + }); + lab + }) + .inner; + if resp.clicked() { + run = Some(e.clone()); + } + } + ui.add_space(4.0); + ui.label(text(Type::Caption, "Up/Down choose · Enter run · Esc close")); + }); + }); + if enter { + run = matches.get(selected).map(|(_, e, _)| e.clone()); + } + if run.is_some() { + close = true; + } + if close { + app.palette = None; + } + match run { + Some(Entry::Command(c)) => app.invoke(c.id), + Some(Entry::Tool(t)) => app.tool = t, + Some(Entry::View(_, _, f)) => f(app), + None => {} + } +} + +// ----- preferences ------------------------------------------------------------------------------ + +/// A font picker: the bundled default plus every installed family, filterable. +fn font_picker(ui: &mut egui::Ui, id: &str, current: &FontChoice, families: Option<&[String]>, bundled: &str) -> Option { + let mut picked = None; + let filter_id = egui::Id::new(("font_filter", id)); + let shown = match current { + FontChoice::Bundled => format!("Default ({bundled})"), + FontChoice::System(name) => name.clone(), + }; + egui::ComboBox::from_id_salt(id).width(260.0).selected_text(text(Type::Body, shown)).show_ui(ui, |ui| { + if ui.selectable_label(*current == FontChoice::Bundled, text(Type::Body, format!("Default (bundled: {bundled})"))).clicked() { + picked = Some(FontChoice::Bundled); + } + ui.separator(); + match families { + None => { + ui.label(text(Type::Caption, "Scanning installed fonts…")); + } + Some(list) => { + let mut filter: String = ui.ctx().data_mut(|d| d.get_temp(filter_id).unwrap_or_default()); + ui.add(egui::TextEdit::singleline(&mut filter).hint_text("Filter fonts…").desired_width(240.0)); + let f = filter.to_lowercase(); + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { + for fam in list.iter().filter(|n| f.is_empty() || n.to_lowercase().contains(&f)) { + let on = matches!(current, FontChoice::System(n) if n == fam); + if ui.selectable_label(on, text(Type::Body, fam.as_str())).clicked() { + picked = Some(FontChoice::System(fam.clone())); + } + } + }); + ui.ctx().data_mut(|d| d.insert_temp(filter_id, filter)); + } + } + }); + picked +} + +fn preferences(app: &mut App, ctx: &egui::Context) { + if !app.show_prefs { + return; + } + let mut open = true; + let mut p = app.prefs.clone(); + let sys = app.system_fonts.clone(); + let (bundled_ui, bundled_mono) = crate::theme::bundled_names(); + let mut reset_confirms = false; + let title = if crate::platform::OS == crate::platform::Os::Mac { "Settings" } else { "Preferences" }; + egui::Window::new(title) + .open(&mut open) + .collapsible(false) + .resizable(false) + .pivot(egui::Align2::CENTER_CENTER) + .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); + + 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")); + }); + }); + 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_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); + } + }); + }); + }); + + 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.")); + }); + }); + }); + + 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())))); + }); + if reset_confirms { + app.skip_confirm.clear(); + } + if p != app.prefs { + app.set_prefs(ctx, p); + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { + open = false; + } + app.show_prefs = open; +} + +// ----- licences --------------------------------------------------------------------------------- + +/// Licence texts compiled into the binary, so every copy of the app carries its notices. +const NOTICES: &[(&str, &str)] = &[ + ("NOTICE", include_str!("../NOTICE")), + ("AniCraft: MIT License", include_str!("../LICENSE-MIT")), + ("AniCraft: Apache License 2.0", include_str!("../LICENSE-APACHE")), + ("Font: Ubuntu Light (Ubuntu Font Licence 1.0)", include_str!("../licenses/fonts/UFL-1.0-Ubuntu-font.txt")), + ("Font: Hack (MIT, Bitstream Vera)", include_str!("../licenses/fonts/LICENSE-Hack.txt")), + ("Font: Noto Emoji (SIL OFL 1.1)", include_str!("../licenses/fonts/OFL-1.1-NotoEmoji.txt")), + ("Font: emoji-icon-font (MIT)", include_str!("../licenses/fonts/LICENSE-emoji-icon-font.txt")), + ("Icons: Lucide (ISC)", include_str!("../licenses/icons/LICENSE-lucide.txt")), + ("Rust crates: licence inventory", include_str!("../docs/legal/third-party-inventory.txt")), +]; + +fn licenses(app: &mut App, ctx: &egui::Context) { + if !app.show_licenses { + return; + } + let mut open = true; + egui::Window::new("Licenses & Notices") + .open(&mut open) + .collapsible(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .default_width(680.0) + .default_height(560.0) + .show(ctx, |ui| { + ui.label(text(Type::Body, "AniCraft is free software: MIT OR Apache-2.0, at your option.").strong()); + ui.label( + text(Type::Body, "It is an independent project, not affiliated with or endorsed by Adobe. Bundled fonts and Rust crates keep their own permissive licences, listed below.") + .color(T.text_dim), + ); + ui.add_space(6.0); + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + for (title, body) in NOTICES { + egui::CollapsingHeader::new(*title).default_open(*title == "NOTICE").show(ui, |ui| { + ui.add(egui::Label::new(text(Type::Path, *body)).wrap()); + }); + } + }); + }); + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { + open = false; + } + app.show_licenses = open; +} + +// ----- keyboard shortcuts (editor) ---------------------------------------------------------------- + +/// The shortcut editor is recording a key for `id`: replacing its key at `replace`, or adding. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct KeyCapture { + pub id: &'static str, + pub replace: Option, +} + +/// Editor state between frames: the last message, a key waiting to be moved here from another +/// action, and the reset-all confirmation. +#[derive(Clone, Default)] +struct SheetState { + filter: String, + notice: Option<(String, bool)>, + steal: Option<(KeyCapture, String, &'static str)>, + confirm_reset_all: bool, +} + +enum SheetAct { + Capture(KeyCapture), + Remove(&'static str, usize), + Reset(&'static str), + ResetAll, + Steal, + Dismiss, +} + +/// Fixed keys: handled before the shortcut map, shown read-only. +fn fixed_rows() -> Vec<(&'static str, &'static str, Vec<&'static str>)> { + let quit = if crate::platform::OS == crate::platform::Os::Mac { "Quit" } else { "Exit" }; + vec![ + ("Essentials", "Command palette", vec!["Ctrl+K"]), + ("Essentials", "Keyboard shortcuts (this editor)", vec!["F1", "Ctrl+Alt+Shift+K"]), + ("Essentials", "Play / Stop", vec!["Enter"]), + ("Essentials", "Preferences", vec!["Ctrl+U", "Ctrl+,"]), + ("Essentials", quit, vec!["Ctrl+Q"]), + ("View", "Zoom in / out", vec!["Ctrl+=", "Ctrl+-"]), + ("View", "Fit stage in window", vec!["Ctrl+0"]), + ("View", "Actual size (100%)", vec!["Ctrl+1"]), + ("View", "Zoom at the cursor", vec!["Ctrl+Wheel"]), + ("View", "Pan with any tool", vec!["Space+Drag", "Middle-drag"]), + ("Editing", "Nudge selection 1 px", vec!["Arrow keys"]), + ("Editing", "Nudge selection 10 px", vec!["Shift+Arrow keys"]), + ("Editing", "Add to / remove from selection", vec!["Shift+Click"]), + ("Editing", "Constrain shape / 45° line", vec!["Shift+Drag"]), + ("Editing", "Context actions", vec!["Right-click"]), + ] +} + +const GROUP_ORDER: [&str; 12] = ["Essentials", "Tools", "File", "Edit", "View", "Insert", "Modify", "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) { + ui.allocate_ui_with_layout(egui::vec2(240.0, crate::theme::TARGET), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(240.0); + ui.add(egui::Label::new(label).truncate()); + }); +} + +fn action_label(km: &crate::keymap::Keymap, id: &str) -> &'static str { + km.actions.iter().find(|a| a.id == id).map_or("this action", |a| a.label) +} + +/// The next key press while recording, with every other key event taken out of the frame. +fn take_key_press(ctx: &egui::Context) -> Option<(egui::Modifiers, Key)> { + ctx.input_mut(|i| { + let mut got = None; + i.events.retain(|e| match e { + egui::Event::Key { key, pressed, modifiers, .. } => { + if *pressed && got.is_none() { + got = Some((*modifiers, *key)); + } + false + } + egui::Event::Text(_) => false, + _ => true, + }); + got + }) +} + +fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { + if !app.show_shortcuts { + app.key_capture = None; + return; + } + let state_id = egui::Id::new("shortcut_editor"); + let mut st: SheetState = ctx.data_mut(|d| d.get_temp(state_id).unwrap_or_default()); + let key = crate::platform::shortcut_label; + + // Recording: the next key press becomes the shortcut (Esc cancels). + if let Some(cap) = app.key_capture + && let Some((m, k)) = take_key_press(ctx) + { + app.key_capture = None; + if k == Key::Escape && !m.any() { + st.notice = None; + } else { + let chord = crate::keymap::chord(m, k); + match crate::keymap::assign(&app.prefs.shortcuts, cap.id, cap.replace, &chord, false) { + Ok(o) => { + st.notice = Some((format!("{}: {}", action_label(&app.keymap, cap.id), key(&chord)), false)); + let mut p = app.prefs.clone(); + p.shortcuts = o; + app.set_prefs(ctx, p); + } + Err(crate::keymap::Refusal::Taken { label, .. }) => { + st.notice = Some((format!("{} is already used by {label}.", key(&chord)), true)); + st.steal = Some((cap, chord, label)); + } + Err(crate::keymap::Refusal::Reserved(why)) => st.notice = Some((format!("{} is kept for {why}; choose another key.", key(&chord)), true)), + Err(crate::keymap::Refusal::TooMany) => st.notice = Some((format!("An action can have up to {} keys.", crate::keymap::MAX_KEYS), true)), + } + } + } + + let mut open = true; + let mut acts: Vec = Vec::new(); + let capture = app.key_capture; + let changed = app.prefs.shortcuts.len(); + egui::Window::new("Keyboard Shortcuts") + .open(&mut open) + .collapsible(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .default_width(660.0) + .default_height(600.0) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text("Filter by name or key…").desired_width(ui.available_width() - 120.0)); + let reset_all = ui.add_enabled(changed > 0, egui::Button::new("Reset all…")).on_hover_text("Put every shortcut back to the defaults"); + if reset_all.clicked() { + st.confirm_reset_all = true; + } + }); + // One message line: what is happening, what just happened, or what needs a decision. + if let Some(cap) = capture { + ui.label(text(Type::Label, format!("Press the new keys for {}. Esc cancels.", action_label(&app.keymap, cap.id))).color(T.accent)); + } else if st.confirm_reset_all { + ui.horizontal(|ui| { + ui.label(text(Type::Label, format!("Reset {changed} changed {} to the defaults?", if changed == 1 { "shortcut" } else { "shortcuts" }))); + if ui.add(danger_button("Reset all")).clicked() { + acts.push(SheetAct::ResetAll); + } + if ui.button("Cancel").clicked() { + acts.push(SheetAct::Dismiss); + } + }); + } else if let Some((msg, err)) = &st.notice { + ui.horizontal(|ui| { + ui.label(text(Type::Label, msg.clone()).color(if *err { T.error } else { T.ok })); + if let Some((cap, _, _)) = &st.steal { + if ui.button(format!("Use it for {}", action_label(&app.keymap, cap.id))).clicked() { + acts.push(SheetAct::Steal); + } + if ui.button("Cancel").clicked() { + acts.push(SheetAct::Dismiss); + } + } + }); + } else { + ui.label(text(Type::Caption, "Click a key to change it or + to add one; right-click a key to remove it. Changes save as you go.")); + } + ui.add_space(4.0); + + let f = st.filter.to_lowercase(); + let hit = |s: &str| f.is_empty() || s.to_lowercase().contains(&f); + let fixed = fixed_rows(); + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + for group in GROUP_ORDER { + let actions: Vec<&crate::keymap::Action> = app + .keymap + .actions + .iter() + .filter(|a| a.group == group || (group == "Other" && !GROUP_ORDER.contains(&a.group))) + .filter(|a| hit(a.label) || hit(group) || app.keymap.keys(a.id).iter().any(|k| hit(k) || hit(&key(k)))) + .collect(); + let fixed: Vec<_> = fixed.iter().filter(|(g, l, ks)| *g == group && (hit(l) || hit(g) || ks.iter().any(|k| hit(k)))).collect(); + if actions.is_empty() && fixed.is_empty() { + continue; + } + let count = (actions.len() + fixed.len()).to_string(); + crate::theme::section(ui, &format!("sheet_{group}"), crate::theme::Section::Rule, group, Some(&count), |ui| { + egui::Grid::new(("sc", group)).num_columns(3).striped(true).min_col_width(60.0).show(ui, |ui| { + for (_, label, keys) in &fixed { + name_cell(ui, label); + ui.horizontal(|ui| { + ui.label(text(Type::Key, keys.iter().map(|k| key(k)).collect::>().join(" · ")).color(T.text_dim)); + ui.add_space(6.0); + ui.label(text(Type::Caption, "fixed")); + }); + ui.label(""); + ui.end_row(); + } + for a in actions { + name_cell(ui, a.label); + ui.horizontal(|ui| { + let keys = app.keymap.keys(a.id); + for (i, k) in keys.iter().enumerate() { + let recording = capture == Some(KeyCapture { id: a.id, replace: Some(i) }); + let chip = if recording { + egui::Button::new(text(Type::Key, "Press keys…").color(Color32::WHITE)).fill(T.accent) + } else { + egui::Button::new(text(Type::Key, key(k)).color(T.text)) + }; + let r = ui.add(chip).on_hover_text("Click to change · right-click to remove"); + if r.clicked() { + acts.push(SheetAct::Capture(KeyCapture { id: a.id, replace: Some(i) })); + } + r.context_menu(|ui| { + if ui.button("Change…").clicked() { + acts.push(SheetAct::Capture(KeyCapture { id: a.id, replace: Some(i) })); + ui.close(); + } + if ui.button("Remove").clicked() { + acts.push(SheetAct::Remove(a.id, i)); + ui.close(); + } + }); + } + if capture == Some(KeyCapture { id: a.id, replace: None }) { + ui.add(egui::Button::new(text(Type::Key, "Press keys…").color(Color32::WHITE)).fill(T.accent)); + } else if keys.len() < crate::keymap::MAX_KEYS { + let tip = if keys.is_empty() { "Add a shortcut" } else { "Add another shortcut" }; + if ui.add(egui::Button::new("+").min_size(egui::vec2(crate::theme::TARGET, crate::theme::TARGET))).on_hover_text(tip).clicked() { + acts.push(SheetAct::Capture(KeyCapture { id: a.id, replace: None })); + } + } + }); + if app.keymap.is_default(a.id) { + ui.label(""); + } else if ui.button("Reset").on_hover_text(format!("Back to the default ({})", if a.defaults.is_empty() { "none".to_string() } else { a.defaults.iter().map(|k| key(k)).collect::>().join(" · ") })).clicked() { + acts.push(SheetAct::Reset(a.id)); + } + ui.end_row(); + } + }); + }); + } + }); + }); + + for act in acts { + let mut p = app.prefs.clone(); + match act { + SheetAct::Capture(c) => { + app.key_capture = Some(c); + st.notice = None; + st.steal = None; + st.confirm_reset_all = false; + continue; + } + SheetAct::Remove(id, i) => { + p.shortcuts = crate::keymap::remove(&p.shortcuts, id, i); + st.notice = Some((format!("{}: key removed", action_label(&app.keymap, id)), false)); + } + SheetAct::Reset(id) => { + p.shortcuts = crate::keymap::reset(&p.shortcuts, id); + st.notice = Some((format!("{}: back to the default", action_label(&app.keymap, id)), false)); + } + SheetAct::ResetAll => { + p.shortcuts.clear(); + st.confirm_reset_all = false; + st.notice = Some(("Every shortcut is back to the defaults.".into(), false)); + } + SheetAct::Steal => { + let Some((cap, chord, from)) = st.steal.take() else { continue }; + match crate::keymap::assign(&p.shortcuts, cap.id, cap.replace, &chord, true) { + Ok(o) => { + p.shortcuts = o; + st.notice = Some((format!("{}: {} (removed from {from})", action_label(&app.keymap, cap.id), key(&chord)), false)); + } + Err(_) => st.notice = Some((format!("{} could not be moved.", key(&chord)), true)), + } + } + SheetAct::Dismiss => { + st.steal = None; + st.notice = None; + st.confirm_reset_all = false; + continue; + } + } + app.set_prefs(ctx, p); + } + if app.key_capture.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { + open = false; + } + if !open { + app.key_capture = None; + st.steal = None; + st.confirm_reset_all = false; + } + ctx.data_mut(|d| d.insert_temp(state_id, st)); + app.show_shortcuts = open; +} diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs new file mode 100644 index 00000000..eab59f91 --- /dev/null +++ b/src/guidelines_tests.rs @@ -0,0 +1,101 @@ +//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values. + +const SOURCES: [(&str, &str); 11] = [ + ("icons.rs", include_str!("icons.rs")), + ("pathtools.rs", include_str!("pathtools.rs")), + ("platform.rs", include_str!("platform.rs")), + ("prefs.rs", include_str!("prefs.rs")), + ("app.rs", include_str!("app.rs")), + ("dialogs.rs", include_str!("dialogs.rs")), + ("menus.rs", include_str!("menus.rs")), + ("panels.rs", include_str!("panels.rs")), + ("stage.rs", include_str!("stage.rs")), + ("timeline.rs", include_str!("timeline.rs")), + ("main.rs", ""), +]; + +#[test] +fn typography_goes_through_theme_roles() { + // Raw font families/sizes outside theme.rs bypass the prose/data rules. + let banned = ["FontId::", ".monospace()", ".size(", "RichText::new("]; + let mut found = Vec::new(); + for (file, src) in SOURCES { + for (n, line) in src.lines().enumerate() { + for b in banned { + if line.contains(b) { + found.push(format!("{file}:{}: `{b}` (use theme::text / theme::font)", n + 1)); + } + } + } + } + assert!(found.is_empty(), "UI guideline violations:\n{}", found.join("\n")); +} + +#[test] +fn colours_and_shapes_come_from_tokens() { + // Raw colours and radii outside theme.rs drift from the palette and the square look. + let banned = ["Color32::from_rgb(", "Color32::from_rgba_unmultiplied(", "CornerRadius::same("]; + let mut found = Vec::new(); + for (file, src) in SOURCES { + for (n, line) in src.lines().enumerate() { + for b in banned { + if line.contains(b) { + found.push(format!("{file}:{}: `{b}` (add a token to theme::T)", n + 1)); + } + } + } + } + assert!(found.is_empty(), "UI guideline violations:\n{}", found.join("\n")); +} + +/// WCAG 2.x relative luminance and contrast ratio. +fn contrast(a: egui::Color32, b: egui::Color32) -> f32 { + let lum = |c: egui::Color32| { + let ch = |v: u8| { + let s = f32::from(v) / 255.0; + if s <= 0.040_45 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b()) + }; + let (x, y) = (lum(a), lum(b)); + (x.max(y) + 0.05) / (x.min(y) + 0.05) +} + +#[test] +fn palette_meets_contrast_and_target_minimums() { + use crate::theme::{T, TARGET, TOOL_BUTTON}; + use egui::Color32; + for (bg, name) in [(T.panel, "panel"), (T.panel_alt, "panel_alt"), (T.chrome, "chrome")] { + assert!(contrast(T.text, bg) >= 7.0, "text on {name}"); + assert!(contrast(T.text_dim, bg) >= 4.5, "text_dim on {name}"); + assert!(contrast(T.text_faint, bg) >= 4.5, "text_faint on {name}: {:.2}", contrast(T.text_faint, bg)); + } + // Button text on raised and hovered surfaces. + assert!(contrast(T.text, T.header) >= 7.0 && contrast(T.text, T.hover) >= 4.5); + // Icons at rest, and the white icon on the active tool's gray block. + assert!(contrast(T.icon, T.panel) >= 4.5 && contrast(Color32::WHITE, T.active) >= 7.0, "tool icons"); + // Text on filled buttons (Save, destructive actions). + 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, "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); + // 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)); + // Click targets (WCAG 2.5.8 asks for at least 24 × 24). + const { assert!(TARGET >= 24.0 && TOOL_BUTTON >= TARGET) }; +} + +#[test] +fn data_roles_are_monospace_and_prose_roles_are_not() { + use crate::theme::{Type, font}; + use egui::FontFamily; + for t in [Type::Data, Type::DataSmall, Type::DataLarge, Type::Key, Type::Path] { + assert_eq!(font(t).family, FontFamily::Monospace, "{t:?}"); + } + for t in [Type::Title, Type::Heading, Type::Body, Type::Label, Type::Caption] { + assert_eq!(font(t).family, FontFamily::Proportional, "{t:?}"); + } +} diff --git a/src/icons.rs b/src/icons.rs new file mode 100644 index 00000000..c030237a --- /dev/null +++ b/src/icons.rs @@ -0,0 +1,400 @@ +//! Interface icons: Lucide (ISC licence, `assets/icons/`, see ATTRIBUTION.md). +//! +//! Lucide icons are 24 × 24 outlines made of a few SVG shapes. Rather than pull in an SVG +//! rasterizer, the shapes are parsed once with the engine's own SVG path reader +//! (`geom::svg`) and stroked as vectors at the exact on-screen size, so they stay crisp at any +//! interface scale and cost nothing in build size. Only icons the app uses are embedded; add a +//! file to `assets/icons/` and a variant here to use another. + +use anicraft_engine::geom::svg::parse_path_data; +use anicraft_engine::geom::{Affine, Path, Vec2}; +use egui::{Color32, Pos2, Rect, Stroke, pos2}; +use std::collections::HashMap; +use std::sync::OnceLock; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Icon { + Select, + Subselect, + Transform, + Pen, + Pencil, + Rect, + Oval, + PolyStar, + Line, + Bucket, + Ink, + Hand, + Zoom, + First, + Last, + Prev, + Next, + Play, + Pause, + Loop, + Onion, + Eye, + EyeOff, + Lock, + Unlock, + ChevronRight, + ChevronDown, + AlignLeft, + AlignHCenter, + AlignRight, + AlignTop, + AlignVCenter, + AlignBottom, + DistributeH, + DistributeV, + Mask, + Masked, +} + +impl Icon { + #[cfg(test)] + pub const ALL: [Icon; 37] = [ + Icon::Mask, + Icon::Masked, + Icon::AlignLeft, + Icon::AlignHCenter, + Icon::AlignRight, + Icon::AlignTop, + Icon::AlignVCenter, + Icon::AlignBottom, + Icon::DistributeH, + Icon::DistributeV, + Icon::Select, + Icon::Subselect, + Icon::Transform, + Icon::Pen, + Icon::Pencil, + Icon::Rect, + Icon::Oval, + Icon::PolyStar, + Icon::Line, + Icon::Bucket, + Icon::Ink, + Icon::Hand, + Icon::Zoom, + Icon::First, + Icon::Last, + Icon::Prev, + Icon::Next, + Icon::Play, + Icon::Pause, + Icon::Loop, + Icon::Onion, + Icon::Eye, + Icon::EyeOff, + Icon::Lock, + Icon::Unlock, + Icon::ChevronRight, + Icon::ChevronDown, + ]; + + /// Drawn filled as well as outlined: the Selection arrow is solid, the Subselection arrow + /// hollow, the way animators tell the two apart at a glance. + fn solid(self) -> bool { + matches!(self, Icon::Select) + } + + /// Lucide icon file and whether it is drawn mirrored. + fn source(self) -> (&'static str, bool) { + match self { + Icon::Select => ("mouse-pointer-2", false), + // A hollow arrowhead, mirrored to point like a cursor: the subselection arrow. + Icon::Subselect => ("navigation", true), + Icon::Transform => ("scaling", false), + Icon::Pen => ("pen-tool", false), + Icon::Pencil => ("pencil", false), + Icon::Rect => ("rectangle-horizontal", false), + Icon::Oval => ("circle", false), + Icon::PolyStar => ("pentagon", false), + Icon::Line => ("slash", false), + Icon::Bucket => ("paint-bucket", false), + Icon::Ink => ("droplet", false), + Icon::Hand => ("hand", false), + Icon::Zoom => ("zoom-in", false), + Icon::First => ("chevrons-left", false), + Icon::Last => ("chevrons-right", false), + Icon::Prev => ("chevron-right", true), + Icon::Next => ("chevron-right", false), + Icon::Play => ("play", false), + Icon::Pause => ("pause", false), + Icon::Loop => ("rotate-cw", false), + Icon::Onion => ("layers", false), + Icon::Eye => ("eye", false), + Icon::EyeOff => ("eye-off", false), + Icon::Lock => ("lock", false), + Icon::Unlock => ("lock-open", false), + Icon::ChevronRight => ("chevron-right", false), + Icon::ChevronDown => ("chevron-down", false), + // Lucide's object-align icons aren't in the local set; these are AniCraft originals + // drawn on the same 24 grid with the same 2-unit round strokes. + Icon::AlignLeft => ("anicraft-align-left", false), + Icon::AlignHCenter => ("anicraft-align-hcenter", false), + Icon::AlignRight => ("anicraft-align-right", false), + Icon::AlignTop => ("anicraft-align-top", false), + Icon::AlignVCenter => ("anicraft-align-vcenter", false), + Icon::AlignBottom => ("anicraft-align-bottom", false), + Icon::DistributeH => ("anicraft-distribute-h", false), + Icon::DistributeV => ("anicraft-distribute-v", false), + // Layer types: a stencil (mask) and the area inside it (masked). + Icon::Mask => ("anicraft-mask", false), + Icon::Masked => ("anicraft-masked", false), + } + } +} + +static FILES: &[(&str, &str)] = &[ + ("mouse-pointer-2", include_str!("../assets/icons/mouse-pointer-2.svg")), + ("navigation", include_str!("../assets/icons/navigation.svg")), + ("scaling", include_str!("../assets/icons/scaling.svg")), + ("pen-tool", include_str!("../assets/icons/pen-tool.svg")), + ("pencil", include_str!("../assets/icons/pencil.svg")), + ("rectangle-horizontal", include_str!("../assets/icons/rectangle-horizontal.svg")), + ("circle", include_str!("../assets/icons/circle.svg")), + ("pentagon", include_str!("../assets/icons/pentagon.svg")), + ("slash", include_str!("../assets/icons/slash.svg")), + ("paint-bucket", include_str!("../assets/icons/paint-bucket.svg")), + ("droplet", include_str!("../assets/icons/droplet.svg")), + ("hand", include_str!("../assets/icons/hand.svg")), + ("zoom-in", include_str!("../assets/icons/zoom-in.svg")), + ("chevrons-left", include_str!("../assets/icons/chevrons-left.svg")), + ("chevrons-right", include_str!("../assets/icons/chevrons-right.svg")), + ("chevron-right", include_str!("../assets/icons/chevron-right.svg")), + ("chevron-down", include_str!("../assets/icons/chevron-down.svg")), + ("play", include_str!("../assets/icons/play.svg")), + ("pause", include_str!("../assets/icons/pause.svg")), + ("rotate-cw", include_str!("../assets/icons/rotate-cw.svg")), + ("layers", include_str!("../assets/icons/layers.svg")), + ("eye", include_str!("../assets/icons/eye.svg")), + ("eye-off", include_str!("../assets/icons/eye-off.svg")), + ("lock", include_str!("../assets/icons/lock.svg")), + ("lock-open", include_str!("../assets/icons/lock-open.svg")), + ("anicraft-align-left", include_str!("../assets/icons/anicraft-align-left.svg")), + ("anicraft-align-hcenter", include_str!("../assets/icons/anicraft-align-hcenter.svg")), + ("anicraft-align-right", include_str!("../assets/icons/anicraft-align-right.svg")), + ("anicraft-align-top", include_str!("../assets/icons/anicraft-align-top.svg")), + ("anicraft-align-vcenter", include_str!("../assets/icons/anicraft-align-vcenter.svg")), + ("anicraft-align-bottom", include_str!("../assets/icons/anicraft-align-bottom.svg")), + ("anicraft-distribute-h", include_str!("../assets/icons/anicraft-distribute-h.svg")), + ("anicraft-distribute-v", include_str!("../assets/icons/anicraft-distribute-v.svg")), + ("anicraft-mask", include_str!("../assets/icons/anicraft-mask.svg")), + ("anicraft-masked", include_str!("../assets/icons/anicraft-masked.svg")), +]; + +/// The value of attribute `name` in an element's tag text. +fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> { + let key = format!(" {name}=\""); + let at = tag.find(&key)? + key.len(); + let rest = tag.get(at..)?; + rest.get(..rest.find('"')?) +} + +fn num(tag: &str, name: &str) -> f32 { + attr(tag, name).and_then(|v| v.trim().parse().ok()).filter(|v: &f32| v.is_finite()).unwrap_or(0.0) +} + +fn points(tag: &str, close: bool) -> Option { + let v: Vec = attr(tag, "points")?.split(|c: char| c.is_whitespace() || c == ',').filter_map(|t| t.parse().ok()).collect(); + let mut p = Path::new(); + for (i, xy) in v.chunks_exact(2).enumerate() { + let q = Vec2::new(xy[0], xy[1]); + if i == 0 { + p.move_to(q); + } else { + p.line_to(q); + } + } + if close { + p.close(); + } + (!p.is_empty()).then_some(p) +} + +/// The outline shapes of one SVG file (the subset icon sets use). +pub fn parse_svg(src: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = src; + while let Some(i) = rest.find('<') { + rest = rest.get(i + 1..).unwrap_or(""); + let end = rest.find('>').unwrap_or(rest.len()); + let tag = rest.get(..end).unwrap_or(""); + rest = rest.get(end..).unwrap_or(""); + let shape = match tag.split_whitespace().next().unwrap_or("") { + "path" => attr(tag, "d").and_then(|d| parse_path_data(d).ok()), + "circle" => Some(Path::ellipse(num(tag, "cx"), num(tag, "cy"), num(tag, "r"), num(tag, "r"))), + "ellipse" => Some(Path::ellipse(num(tag, "cx"), num(tag, "cy"), num(tag, "rx"), num(tag, "ry"))), + "rect" => Some(Path::rounded_rect(num(tag, "x"), num(tag, "y"), num(tag, "width"), num(tag, "height"), num(tag, "rx").max(num(tag, "ry")))), + "line" => Some(Path::line(Vec2::new(num(tag, "x1"), num(tag, "y1")), Vec2::new(num(tag, "x2"), num(tag, "y2")))), + "polyline" => points(tag, false), + "polygon" => points(tag, true), + _ => None, + }; + out.extend(shape.filter(|p| !p.is_empty())); + } + out +} + +fn library() -> &'static HashMap<&'static str, Vec> { + static LIB: OnceLock>> = OnceLock::new(); + LIB.get_or_init(|| FILES.iter().map(|(name, src)| (*name, parse_svg(src))).collect()) +} + +/// Strokes `icon` centred in `rect` (sized to its shorter side) in `color`. +/// +/// Crispness: the icon's 24-unit grid is placed on whole device pixels and the stroke width is +/// rounded to whole device pixels, so lines land on the pixel grid the way the set is drawn +/// (at 24 px it is exact; other sizes stay consistent instead of smearing across pixels). +pub fn paint(p: &egui::Painter, rect: Rect, icon: Icon, color: Color32) { + let (name, flip) = icon.source(); + let Some(paths) = library().get(name) else { return }; + let ppp = p.pixels_per_point().max(0.25); + let s = rect.width().min(rect.height()) / 24.0; + let snap = |v: f32| (v * ppp).round() / ppp; + let (ox, oy) = (snap(rect.center().x - 12.0 * s), snap(rect.center().y - 12.0 * s)); + let m = if flip { + Affine::translate(ox + 24.0 * s, oy).mul(&Affine::scale(-s, s)) + } else { + Affine::translate(ox, oy).mul(&Affine::scale(s, s)) + }; + // Lucide draws 2-unit strokes on its 24 grid; a touch lighter reads better at UI sizes. + let w = ((1.75 * s * ppp).round().max(1.0)) / ppp; + let stroke = Stroke::new(w, color); + let solid = icon.solid(); + for path in paths { + for pl in path.flatten(&m, 0.08) { + let pts: Vec = pl.points.iter().map(|q| pos2(q.x, q.y)).collect(); + if pl.closed { + if solid { + fill_polygon(p, &pts, color); + } + p.add(egui::Shape::closed_line(pts, stroke)); + } else { + // Round caps, as the icons are designed. + for end in [pts.first(), pts.last()].into_iter().flatten() { + p.circle_filled(*end, w * 0.5, color); + } + p.add(egui::Shape::line(pts, stroke)); + } + } + } +} + +/// Fills a simple (possibly concave) polygon by ear clipping. Icon outlines have a few dozen +/// points, so the quadratic search is trivial; anything degenerate just isn't filled. +fn fill_polygon(p: &egui::Painter, pts: &[Pos2], color: Color32) { + let (v, tris) = triangulate(pts); + if tris.is_empty() { + return; + } + let mut mesh = egui::Mesh::default(); + for q in &v { + mesh.colored_vertex(*q, color); + } + for [a, b, c] in tris { + mesh.add_triangle(a, b, c); + } + p.add(egui::Shape::mesh(mesh)); +} + +/// Ear-clipping triangulation: the cleaned-up vertices and triangles indexing them. +fn triangulate(pts: &[Pos2]) -> (Vec, Vec<[u32; 3]>) { + let mut v: Vec = pts.to_vec(); + v.dedup_by(|a, b| a.distance(*b) < 1e-3); + if v.len() > 2 && v.first().zip(v.last()).is_some_and(|(a, b)| a.distance(*b) < 1e-3) { + v.pop(); + } + let mut tris = Vec::new(); + if v.len() < 3 || v.len() > 4096 { + return (v, tris); + } + let cross = |a: Pos2, b: Pos2, c: Pos2| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + let area: f32 = (0..v.len()).map(|i| cross(pos2(0.0, 0.0), v[i], v[(i + 1) % v.len()])).sum(); + let ccw = area > 0.0; + let mut idx: Vec = (0..v.len()).collect(); + let mut guard = 0; + while idx.len() > 3 && guard < 10_000 { + guard += 1; + let n = idx.len(); + let mut clipped = false; + for i in 0..n { + let (ia, ib, ic) = (idx[(i + n - 1) % n], idx[i], idx[(i + 1) % n]); + let (a, b, c) = (v[ia], v[ib], v[ic]); + let turn = cross(a, b, c); + if (turn > 0.0) != ccw || turn.abs() < 1e-6 { + continue; + } + let inside = idx.iter().any(|&j| { + if j == ia || j == ib || j == ic { + return false; + } + let q = v[j]; + let (d1, d2, d3) = (cross(a, b, q), cross(b, c, q), cross(c, a, q)); + if ccw { d1 > 0.0 && d2 > 0.0 && d3 > 0.0 } else { d1 < 0.0 && d2 < 0.0 && d3 < 0.0 } + }); + if !inside { + tris.push([ia as u32, ib as u32, ic as u32]); + idx.remove(i); + clipped = true; + break; + } + } + if !clipped { + break; + } + } + if let [a, b, c] = idx[..] { + tris.push([a as u32, b as u32, c as u32]); + } + (v, tris) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_icon_is_embedded_and_parses() { + for icon in Icon::ALL { + let (name, _) = icon.source(); + let paths = library().get(name).unwrap_or_else(|| panic!("{icon:?}: {name}.svg is not embedded")); + assert!(!paths.is_empty(), "{name}.svg has no shapes"); + for p in paths { + let b = p.bounds(); + assert!(b.min.x >= -0.5 && b.min.y >= -0.5 && b.max.x <= 24.5 && b.max.y <= 24.5, "{name}: {b:?} outside the 24 grid"); + } + } + } + + #[test] + fn concave_outlines_triangulate_completely() { + // An arrowhead with a notch (concave), like the Selection arrow. + let arrow = [pos2(0.0, 0.0), pos2(10.0, 4.0), pos2(5.0, 5.0), pos2(4.0, 10.0)]; + let (v, tris) = triangulate(&arrow); + assert_eq!(tris.len(), v.len() - 2); + let area = |t: &[u32; 3]| { + let (a, b, c) = (v[t[0] as usize], v[t[1] as usize], v[t[2] as usize]); + ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)).abs() * 0.5 + }; + // Shoelace area of the arrow is 30; the triangles cover exactly that. + assert!((tris.iter().map(area).sum::() - 30.0).abs() < 1e-3); + assert!(triangulate(&[pos2(0.0, 0.0), pos2(1.0, 1.0)]).1.is_empty()); + // The Selection icon really is filled: its outline triangulates. + let (name, _) = Icon::Select.source(); + let outline = library().get(name).unwrap()[0].flatten(&Affine::IDENTITY, 0.08); + let pts: Vec = outline[0].points.iter().map(|q| pos2(q.x, q.y)).collect(); + assert!(!triangulate(&pts).1.is_empty()); + } + + #[test] + fn reads_each_shape_kind() { + let svg = r#""#; + assert_eq!(parse_svg(svg).len(), 5); + assert!(parse_svg("").is_empty(), "bad shapes are skipped, never panics"); + } +} diff --git a/src/keymap.rs b/src/keymap.rs new file mode 100644 index 00000000..4e75b34c --- /dev/null +++ b/src/keymap.rs @@ -0,0 +1,423 @@ +//! The keyboard shortcut map: defaults plus the user's changes. +//! +//! Every bindable action has default keys: registry commands (their shortcut and any engine +//! alias), the tools and the view keys. The user's changes are stored in preferences as +//! overrides (`action id → its full key list`), so actions the user never touched keep +//! following the defaults as they evolve. A few keys are reserved and cannot be rebound: the +//! ones that open this editor, the palette and preferences, quitting, playing and cancelling. +//! A chord is written in registry notation, modifiers in a fixed order: `Ctrl+Alt+Shift+K`. + +use crate::app::{Tool, VIEW_SHORTCUTS}; +use anicraft_engine::{SHORTCUT_ALIASES, commands}; +use egui::{Key, Modifiers}; +use std::collections::BTreeMap; + +/// Keys handled before the shortcut map, which the editor will not assign. +pub const RESERVED: &[(&str, &str)] = &[ + ("Ctrl+K", "the command palette"), + ("Ctrl+Shift+P", "the command palette"), + ("F1", "the shortcut editor"), + ("Ctrl+Alt+Shift+K", "the shortcut editor"), + ("Ctrl+U", "Preferences"), + ("Ctrl+,", "Preferences"), + ("Ctrl+Q", "quitting"), + ("Enter", "play / stop"), + ("Escape", "cancelling"), + ("Space", "panning with any tool"), + ("Tab", "moving between fields"), +]; + +/// Most keys one action may have. +pub const MAX_KEYS: usize = 4; + +/// A bindable action. +#[derive(Clone, Debug)] +pub struct Action { + pub id: &'static str, + pub label: &'static str, + /// Where it lives (a top menu, "Tools" or "View"). + pub group: &'static str, + pub defaults: Vec<&'static str>, +} + +/// The id a tool is bound under. +pub fn tool_id(t: Tool) -> &'static str { + match t { + Tool::Select => "tool.selection", + Tool::Subselect => "tool.subselection", + Tool::Transform => "tool.free_transform", + Tool::Pen => "tool.pen", + Tool::Pencil => "tool.pencil", + Tool::Rect => "tool.rectangle", + Tool::Oval => "tool.oval", + Tool::Star => "tool.polystar", + Tool::Line => "tool.line", + Tool::PaintBucket => "tool.paint_bucket", + Tool::InkBottle => "tool.ink_bottle", + Tool::Hand => "tool.hand", + Tool::Zoom => "tool.zoom", + } +} + +pub fn tool_for(id: &str) -> Option { + Tool::ALL.into_iter().find(|t| tool_id(*t) == id) +} + +fn view_label(id: &str) -> &'static str { + match id { + "view.fit" => "Fit Stage in Window", + "view.onion" => "Onion Skin On / Off", + "view.select_all_frames" => "Select All Frames", + "view.align_to_stage" => "Align to Stage On / Off", + "view.test" => "Test (Play from Frame 1)", + _ => "View action", + } +} + +/// Every action that can carry a shortcut: the menu commands, any command with a default key, +/// the tools and the view keys. +pub fn actions() -> Vec { + let mut v: Vec = commands() + .into_iter() + .filter(|c| !c.menu.is_empty() || c.shortcut.is_some()) + .map(|c| Action { + id: c.id, + label: c.label, + group: if c.menu.is_empty() { "Other" } else { c.menu.split('/').next().unwrap_or("Other") }, + defaults: c.shortcut.into_iter().chain(SHORTCUT_ALIASES.iter().filter(|(_, id)| *id == c.id).map(|(k, _)| *k)).collect(), + }) + .collect(); + v.extend(Tool::ALL.into_iter().map(|t| Action { id: tool_id(t), label: t.label(), group: "Tools", defaults: t.shortcut().into_iter().collect() })); + let mut views: Vec<&str> = Vec::new(); + for (_, id) in VIEW_SHORTCUTS { + if !views.contains(id) { + views.push(id); + } + } + v.extend(views.into_iter().map(|id| Action { + id, + label: view_label(id), + group: "View", + defaults: VIEW_SHORTCUTS.iter().filter(|(_, i)| *i == id).map(|(k, _)| *k).collect(), + })); + v +} + +/// The registry spelling of a key. +fn key_name(k: Key) -> &'static str { + match k { + Key::Comma => ",", + Key::Period => ".", + Key::Minus => "-", + Key::Equals => "=", + other => other.name(), + } +} + +/// Parses a chord in registry notation (`Ctrl+Shift+Z`, `Shift+,`, `F5`). +pub fn parse(s: &str) -> Option<(Modifiers, Key)> { + let mut m = Modifiers::NONE; + let mut key = None; + for part in s.split('+') { + match part { + "Ctrl" => m |= Modifiers::COMMAND, + "Shift" => m |= Modifiers::SHIFT, + "Alt" => m |= Modifiers::ALT, + "" => return None, + other => { + if key.is_some() { + return None; + } + key = Some(Key::from_name(other)?); + } + } + } + key.map(|k| (m, k)) +} + +/// The canonical spelling of a key press. +pub fn chord(m: Modifiers, k: Key) -> String { + let mut s = String::new(); + for (on, name) in [(m.command || m.ctrl, "Ctrl+"), (m.alt, "Alt+"), (m.shift, "Shift+")] { + if on { + s.push_str(name); + } + } + s.push_str(key_name(k)); + s +} + +/// The canonical spelling of a chord, or `None` when it is not a chord. +pub fn normalize(s: &str) -> Option { + parse(s).map(|(m, k)| chord(m, k)) +} + +/// What a reserved chord is kept for. +pub fn reserved(chord: &str) -> Option<&'static str> { + let c = normalize(chord)?; + RESERVED.iter().find(|(k, _)| normalize(k).as_deref() == Some(c.as_str())).map(|(_, why)| *why) +} + +/// Defaults with the user's overrides applied. +#[derive(Clone, Debug)] +pub struct Keymap { + pub actions: Vec, + keys: Vec>, +} + +impl Keymap { + pub fn new(overrides: &BTreeMap>) -> Keymap { + let actions = actions(); + let keys = actions + .iter() + .map(|a| match overrides.get(a.id) { + Some(user) => user.iter().filter_map(|k| normalize(k)).collect(), + None => a.defaults.iter().filter_map(|k| normalize(k)).collect(), + }) + .collect(); + Keymap { actions, keys } + } + + fn index(&self, id: &str) -> Option { + self.actions.iter().position(|a| a.id == id) + } + + pub fn keys(&self, id: &str) -> &[String] { + self.index(id).and_then(|i| self.keys.get(i)).map_or(&[], Vec::as_slice) + } + + /// The first key, for menus and tooltips. + pub fn primary(&self, id: &str) -> Option<&str> { + self.keys(id).first().map(String::as_str) + } + + pub fn is_default(&self, id: &str) -> bool { + self.index(id).is_none_or(|i| { + let defaults: Vec = self.actions.get(i).map(|a| a.defaults.iter().filter_map(|k| normalize(k)).collect()).unwrap_or_default(); + self.keys.get(i) == Some(&defaults) + }) + } + + /// The action a chord is bound to. + pub fn owner(&self, chord: &str) -> Option<&Action> { + let c = normalize(chord)?; + self.keys.iter().position(|ks| ks.contains(&c)).and_then(|i| self.actions.get(i)) + } + + /// `(modifiers, key, action)` for every binding, most specific chord first: egui matches a + /// chord with extra Shift/Alt held, so Ctrl+Shift+Z must be tried before Ctrl+Z. + pub fn table(&self) -> Vec<(Modifiers, Key, &'static str)> { + let mut t: Vec<(Modifiers, Key, &'static str)> = + self.actions.iter().zip(&self.keys).flat_map(|(a, ks)| ks.iter().filter_map(|k| parse(k)).map(|(m, k)| (m, k, a.id))).collect(); + t.sort_by_key(|(m, _, _)| std::cmp::Reverse(u8::from(m.command) + u8::from(m.shift) + u8::from(m.alt))); + t + } +} + +/// Why a key cannot be assigned to an action as asked. +#[derive(Clone, Debug, PartialEq)] +pub enum Refusal { + Reserved(&'static str), + /// Bound to another action; assign again with `steal` to move it. + Taken { id: &'static str, label: &'static str }, + TooMany, +} + +/// Overrides after giving `id` the key `chord` (replacing its key at `replace`, or adding one). +/// With `steal`, a chord bound elsewhere moves here; otherwise that is refused. +pub fn assign(overrides: &BTreeMap>, id: &str, replace: Option, chord: &str, steal: bool) -> Result>, Refusal> { + let map = Keymap::new(overrides); + let c = normalize(chord).ok_or(Refusal::Reserved("nothing (not a key)"))?; + if let Some(why) = reserved(&c) { + return Err(Refusal::Reserved(why)); + } + let mut out = overrides.clone(); + if let Some(other) = map.owner(&c) + && other.id != id + { + if !steal { + return Err(Refusal::Taken { id: other.id, label: other.label }); + } + let rest: Vec = map.keys(other.id).iter().filter(|k| **k != c).cloned().collect(); + set(&mut out, &map, other.id, rest); + } + let mut mine: Vec = map.keys(id).to_vec(); + match replace.filter(|&i| i < mine.len()) { + Some(i) => { + if let Some(slot) = mine.get_mut(i) { + *slot = c.clone(); + } + } + None if mine.len() >= MAX_KEYS => return Err(Refusal::TooMany), + None => mine.push(c.clone()), + } + // A chord the action already had elsewhere in its list collapses into one. + let mut seen = Vec::new(); + mine.retain(|k| !seen.contains(k) && { + seen.push(k.clone()); + true + }); + set(&mut out, &map, id, mine); + Ok(out) +} + +/// Overrides after removing `id`'s key at `index`. +pub fn remove(overrides: &BTreeMap>, id: &str, index: usize) -> BTreeMap> { + let map = Keymap::new(overrides); + let mut mine = map.keys(id).to_vec(); + if index < mine.len() { + mine.remove(index); + } + let mut out = overrides.clone(); + set(&mut out, &map, id, mine); + out +} + +/// Overrides with `id` back on its defaults. Defaults that another action has taken over stay +/// with that action, so a reset never creates a clash. +pub fn reset(overrides: &BTreeMap>, id: &str) -> BTreeMap> { + let mut out = overrides.clone(); + out.remove(id); + let map = Keymap::new(&out); + if let Some(a) = map.actions.iter().find(|a| a.id == id) { + let free: Vec = a.defaults.iter().filter_map(|k| normalize(k)).filter(|k| map.actions.iter().all(|o| o.id == id || !map.keys(o.id).contains(k))).collect(); + set(&mut out, &map, id, free); + } + out +} + +/// Records `keys` for `id`, as an override only when they differ from the defaults. +fn set(out: &mut BTreeMap>, map: &Keymap, id: &str, keys: Vec) { + let defaults: Vec = map.actions.iter().find(|a| a.id == id).map(|a| a.defaults.iter().filter_map(|k| normalize(k)).collect()).unwrap_or_default(); + if keys == defaults { + out.remove(id); + } else { + out.insert(id.to_string(), keys); + } +} + +/// Overrides as loaded from a file: unknown actions and malformed or reserved keys dropped, at +/// most [`MAX_KEYS`] per action, and no chord bound twice (the first binding wins). +pub fn sanitize(overrides: BTreeMap>) -> BTreeMap> { + let known = actions(); + let mut out: BTreeMap> = BTreeMap::new(); + for (id, keys) in overrides.into_iter().take(1_000) { + if !known.iter().any(|a| a.id == id) { + continue; + } + let mut clean: Vec = Vec::new(); + for k in keys.iter().take(16).filter(|k| k.len() <= 64) { + if let Some(c) = normalize(k) + && reserved(&c).is_none() + && !clean.contains(&c) + && clean.len() < MAX_KEYS + { + clean.push(c); + } + } + out.insert(id, clean); + } + // Resolve clashes between overrides and the defaults of untouched actions. + let map = Keymap::new(&out); + let mut seen: Vec = Vec::new(); + let mut fixes: Vec<(&'static str, Vec)> = Vec::new(); + for a in &map.actions { + let ks = map.keys(a.id); + let keep: Vec = ks.iter().filter(|k| !seen.contains(k)).cloned().collect(); + seen.extend(keep.iter().cloned()); + if keep.len() != ks.len() { + fixes.push((a.id, keep)); + } + } + for (id, keep) in fixes { + out.insert(id.to_string(), keep); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn none() -> BTreeMap> { + BTreeMap::new() + } + + #[test] + fn defaults_cover_commands_tools_and_view_keys_without_clashes() { + let m = Keymap::new(&none()); + assert_eq!(m.keys("edit.undo"), ["Ctrl+Z"]); + assert_eq!(m.keys("edit.delete"), ["Delete", "Backspace"], "aliases are second keys"); + assert_eq!(m.primary("tool.pen"), Some("P")); + assert_eq!(m.primary("view.onion"), Some("Alt+Shift+O")); + assert_eq!(m.owner("ctrl+z").map(|a| a.id), None, "chords are case-sensitive registry names"); + assert_eq!(m.owner("Ctrl+Shift+Z").map(|a| a.id), Some("modify.remove_transform")); + let mut all: Vec = m.actions.iter().flat_map(|a| m.keys(a.id).to_vec()).collect(); + let n = all.len(); + all.sort(); + all.dedup(); + assert_eq!(all.len(), n, "a default chord is bound twice"); + assert!(all.iter().all(|k| reserved(k).is_none()), "a default uses a reserved key"); + assert!(m.actions.iter().all(|a| m.is_default(a.id))); + } + + #[test] + fn chords_round_trip_in_one_spelling() { + for s in ["Ctrl+Shift+Z", "Shift+,", "Ctrl+Up", "F5", "Ctrl+Alt+Shift+K", "Ctrl+-", "Alt+Shift+O", "Backspace"] { + assert_eq!(normalize(s).as_deref(), Some(s), "{s}"); + } + assert_eq!(normalize("Shift+Ctrl+Z").as_deref(), Some("Ctrl+Shift+Z")); + assert_eq!(chord(Modifiers::COMMAND | Modifiers::ALT, Key::Num8), "Ctrl+Alt+8"); + for bad in ["", "Ctrl+", "Ctrl+A+B", "Hyper+Q", "Ctrl++"] { + assert_eq!(normalize(bad), None, "{bad}"); + } + } + + #[test] + fn assigning_moves_keys_only_when_asked_and_stores_only_changes() { + // Rebind Undo to Ctrl+D (Duplicate's key): refused, then moved on request. + let r = assign(&none(), "edit.undo", Some(0), "Ctrl+D", false); + assert_eq!(r, Err(Refusal::Taken { id: "edit.duplicate", label: "Duplicate" })); + let o = assign(&none(), "edit.undo", Some(0), "Ctrl+D", true).unwrap(); + let m = Keymap::new(&o); + assert_eq!(m.keys("edit.undo"), ["Ctrl+D"]); + assert!(m.keys("edit.duplicate").is_empty()); + assert_eq!(o.len(), 2, "both changes are stored, nothing else"); + // Reserved keys stay reserved. + assert_eq!(assign(&none(), "edit.undo", None, "Ctrl+K", true), Err(Refusal::Reserved("the command palette"))); + // Adding a second key, then putting it back the way it was, stores nothing. + let o = assign(&none(), "tool.pen", None, "Shift+P", false).unwrap(); + assert_eq!(Keymap::new(&o).keys("tool.pen"), ["P", "Shift+P"]); + assert!(remove(&o, "tool.pen", 1).is_empty()); + // Removing every key is a change too (the action is unbound). + let o = remove(&none(), "tool.pen", 0); + assert!(Keymap::new(&o).keys("tool.pen").is_empty()); + assert!(!Keymap::new(&o).is_default("tool.pen")); + } + + #[test] + fn reset_never_creates_a_clash() { + let o = assign(&none(), "edit.undo", Some(0), "Ctrl+D", true).unwrap(); + // Duplicate's default (Ctrl+D) now belongs to Undo, so resetting Duplicate skips it... + let o = reset(&o, "edit.duplicate"); + assert!(Keymap::new(&o).keys("edit.duplicate").is_empty()); + // ...until Undo is reset too and Duplicate is reset again. + let o = reset(&reset(&o, "edit.undo"), "edit.duplicate"); + assert!(o.is_empty()); + } + + #[test] + fn hostile_preference_files_are_cleaned() { + let mut o = BTreeMap::new(); + o.insert("no.such.command".to_string(), vec!["F9".to_string()]); + o.insert("tool.pen".to_string(), vec!["Ctrl+K".into(), "bogus".into(), "F9".into(), "F9".into(), "x".repeat(500)]); + // Undo takes Ctrl+D without Duplicate giving it up: the clash is resolved. + o.insert("edit.undo".to_string(), vec!["Ctrl+D".into()]); + let o = sanitize(o); + let m = Keymap::new(&o); + assert!(!o.contains_key("no.such.command")); + assert_eq!(m.keys("tool.pen"), ["F9"]); + let owners: Vec<&str> = m.actions.iter().filter(|a| m.keys(a.id).iter().any(|k| k == "Ctrl+D")).map(|a| a.id).collect(); + assert_eq!(owners.len(), 1, "{owners:?}"); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 00000000..5dab6de4 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,106 @@ +//! AniCraft desktop app. +//! +//! ```text +//! anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open ] +//! ``` +//! `--screenshot` starts normally, draws ~120 frames, saves the window as PNG and exits. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod app; +mod dialogs; +mod icons; +mod keymap; +mod menus; +mod panels; +mod pathtools; +mod platform; +mod prefs; +mod stage; +mod theme; +mod timeline; + +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()) }; + 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()) { + println!("{r}"); + } + s + } + Err(e) => { + eprintln!("could not open {}: {e}; starting with the sample", p.display()); + Session::new(anicraft_engine::doc::sample::demo()) + } + } +} + +fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, open: Option) -> eframe::Result { + let options = eframe::NativeOptions { + viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])), + renderer, + ..Default::default() + }; + let session = 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()); + Ok(Box::new(a)) + }), + ) +} + +fn main() -> eframe::Result { + let mut shot: Option = None; + let mut file: Option = None; + let mut open: Option = None; + let mut renderer_arg: Option = None; + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + match a.as_str() { + "--screenshot" => match args.next() { + Some(p) => shot = Some(PathBuf::from(p)), + None => { + eprintln!("--screenshot needs a file name"); + std::process::exit(2); + } + }, + "--open" => open = args.next(), + "--renderer" => renderer_arg = args.next(), + "--help" | "-h" => { + println!( + "anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open palette|shortcuts|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|prefs|licenses|zoom]\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" + ); + return Ok(()); + } + other => file = Some(PathBuf::from(other)), + } + } + + // wgpu first (Vulkan/Metal/DX12). If it cannot start (old GPU, VM, missing drivers, common + // on some Linux setups) retry once with OpenGL, unless the user forced a backend. + let forced = platform::forced_renderer(renderer_arg.as_deref()); + let first = forced.unwrap_or(eframe::Renderer::Wgpu); + match run(first, file.as_deref(), shot.clone(), open.clone()) { + Err(e) if forced.is_none() && first == eframe::Renderer::Wgpu => { + eprintln!("GPU backend (wgpu) failed to start: {e}. Retrying with OpenGL."); + run(eframe::Renderer::Glow, file.as_deref(), shot, open) + } + other => other, + } +} + +#[cfg(test)] +mod guidelines_tests; diff --git a/src/menus.rs b/src/menus.rs new file mode 100644 index 00000000..8c6c62d2 --- /dev/null +++ b/src/menus.rs @@ -0,0 +1,207 @@ +//! Menu bar generated from the engine's command registry, plus a few view-only items. + +use crate::app::App; +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"]; + +pub fn bar(app: &mut App, ui: &mut egui::Ui) { + let cmds = commands(); + egui::MenuBar::new().ui(ui, |ui| { + // macOS: leave room for the traffic lights over the unified title bar. + ui.add_space(platform::menu_inset()); + if platform::OS == Os::Mac { + // The application menu, as every Mac app has (About, Settings, Quit). + ui.menu_button(text(Type::Body, "AniCraft").strong(), |ui| { + ui.set_min_width(220.0); + if ui_item(ui, "About AniCraft", "", None) { + app.show_about = true; + } + ui.separator(); + if ui_item(ui, "Settings…", "Ctrl+,", None) { + app.open_prefs(); + } + ui.separator(); + if ui_item(ui, "Quit AniCraft", "Ctrl+Q", None) { + ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); + } + }); + } + // Windows and Linux: no name before the menus; the window title already shows it. + for top in TOP_MENUS { + ui.menu_button(top, |ui| { + ui.set_min_width(230.0); + menu_contents(app, ui, top, &cmds); + }); + } + }); +} + +fn enabled(app: &App, id: &str) -> bool { + match id { + "edit.undo" => app.s.can_undo(), + "edit.redo" => app.s.can_redo(), + "edit.delete" | "edit.duplicate" | "modify.convert_to_symbol" | "modify.break_apart" | "arrange.bring_to_front" | "arrange.send_to_back" => !app.s.selection.is_empty(), + "layer.delete" => app.s.doc.timeline.layers.len() > 1, + "timeline.clear_keyframe" => match app.frame_sel { + Some(sel) => sel.has_keys(&app.s.doc.timeline.layers), + None => app.s.active_layer().is_some_and(|l| l.keyframe_starting_at(app.s.frame).is_some()), + }, + "timeline.paste_frames" => !app.s.frame_clipboard.is_empty(), + "timeline.remove_frame" | "timeline.create_tween" => app.s.active_layer().is_some_and(|l| l.keyframe_at(app.s.frame).is_some()), + _ => true, + } +} + +fn item(app: &mut App, ui: &mut egui::Ui, spec: &CommandSpec) { + let label = match spec.id { + "edit.undo" => app.s.undo_label().map_or_else(|| "Undo".to_string(), |l| format!("Undo {l}")), + _ => spec.label.to_string(), + }; + let button = egui::Button::new(label).shortcut_text(text(Type::Key, platform::shortcut_label(app.keymap.primary(spec.id).unwrap_or("")))); + if ui.add_enabled(enabled(app, spec.id), button).clicked() { + app.invoke(spec.id); + ui.close(); + } +} + +/// A registry command as a menu item (label and shortcut from the registry); used by context +/// menus so every surface shows the same names and keys. +pub fn cmd_item(app: &mut App, ui: &mut egui::Ui, id: &str) { + if let Some(spec) = anicraft_engine::find_command(id) { + item(app, ui, &spec); + } +} + +/// A check item for state that is not a registry command's own (context menus). +pub fn check_item(ui: &mut egui::Ui, label: &str, checked: bool, enabled: bool) -> bool { + let label = if checked { format!("✔ {label}") } else { format!(" {label}") }; + let clicked = ui.add_enabled(enabled, egui::Button::new(label)).clicked(); + if clicked { + ui.close(); + } + clicked +} + +fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option) -> bool { + let label_text = match checked { + Some(true) => format!("✔ {label}"), + Some(false) => format!(" {label}"), + None => label.to_string(), + }; + let clicked = ui.add(egui::Button::new(label_text).shortcut_text(text(Type::Key, platform::shortcut_label(shortcut)))).clicked(); + if clicked { + ui.close(); + } + clicked +} + +fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) { + // 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); + } + let mut subs: Vec<&str> = Vec::new(); + for c in cmds { + if let Some(sub) = c.menu.strip_prefix(top).and_then(|r| r.strip_prefix('/')) + && !subs.contains(&sub) + { + subs.push(sub); + } + } + for sub in subs { + let path = format!("{top}/{sub}"); + ui.menu_button(sub, |ui| { + ui.set_min_width(220.0); + for spec in cmds.iter().filter(|c| c.menu == path) { + item(app, ui, spec); + } + }); + } + + match top { + // Windows / Linux conventions; on macOS these live in the AniCraft (application) menu. + "File" if platform::OS != Os::Mac => { + ui.separator(); + if ui_item(ui, "Exit", "Ctrl+Q", None) { + ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); + } + } + "Edit" if platform::OS != Os::Mac => { + ui.separator(); + if ui_item(ui, "Preferences…", "Ctrl+U", None) { + app.open_prefs(); + } + } + "View" => { + let canvas = app.stage_cache.canvas; + let center = canvas.center(); + if ui_item(ui, "Zoom In", "Ctrl+=", None) { + let z = app.view.zoom * 1.5; + app.zoom_about(canvas, center, z); + } + if ui_item(ui, "Zoom Out", "Ctrl+-", None) { + let z = app.view.zoom / 1.5; + app.zoom_about(canvas, center, z); + } + if ui_item(ui, "Fit in Window", "Ctrl+0", None) { + app.view.fit = true; + } + if ui_item(ui, "100%", "Ctrl+1", None) { + app.zoom_about(canvas, center, 1.0); + } + ui.separator(); + if ui_item(ui, "Onion Skin", "", Some(app.onion)) { + app.onion = !app.onion; + } + ui.menu_button("Stage Rendering", |ui| { + for (mode, name, tip) in crate::prefs::RenderMode::ALL { + if ui_item(ui, name, "", Some(app.prefs.render_mode == mode)) { + let mut p = app.prefs.clone(); + p.render_mode = mode; + let ctx = ui.ctx().clone(); + app.set_prefs(&ctx, p); + } + ui.label(text(Type::Caption, tip)); + } + }); + } + "Control" => { + ui.separator(); + if ui_item(ui, if app.playing { "Stop" } else { "Play" }, "Enter", None) { + app.toggle_play(); + } + if ui_item(ui, "Loop Playback", "", Some(app.looping)) { + app.looping = !app.looping; + } + } + "Window" => { + if ui_item(ui, "Onion Skin", "", Some(app.onion)) { + app.onion = !app.onion; + } + ui.label(text(Type::Caption, "Panels are docked: Tools, Stage, Timeline, Properties, Library")); + } + "Help" => { + if ui_item(ui, "Command Palette…", "Ctrl+K", None) { + app.palette = Some(crate::dialogs::Palette::default()); + } + if ui_item(ui, "Keyboard Shortcuts", "F1", None) { + app.show_shortcuts = true; + } + ui.separator(); + if ui_item(ui, "Project Files & Docs…", "", None) { + app.show_files = true; + } + if ui_item(ui, "Licenses & Notices", "", None) { + app.show_licenses = true; + } + if ui_item(ui, "About AniCraft", "", None) { + app.show_about = true; + } + ui.label(text(Type::Caption, format!("{} commands are scriptable via anicraft-cli", cmds.len()))); + } + _ => {} + } +} diff --git a/src/panels.rs b/src/panels.rs new file mode 100644 index 00000000..b400bf8c --- /dev/null +++ b/src/panels.rs @@ -0,0 +1,526 @@ +//! Tools bar, edit bar, status bar, Properties and Library panels. + +use crate::app::{App, Tool}; +use crate::icons::{self, Icon}; +use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, font, section, text, to_color32, with_type}; +use anicraft_engine::doc::{ElementKind, Paint, Rgba, SymbolKind, evaluate_layer_elements}; +use anicraft_engine::element_label; +use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use serde_json::{Value, json}; + +// ----- tools -------------------------------------------------------------------------------- + +/// The Lucide icon for a tool. +fn tool_icon(tool: Tool) -> Icon { + match tool { + Tool::Select => Icon::Select, + Tool::Subselect => Icon::Subselect, + Tool::Transform => Icon::Transform, + Tool::Pen => Icon::Pen, + Tool::Pencil => Icon::Pencil, + Tool::Rect => Icon::Rect, + Tool::Oval => Icon::Oval, + Tool::Star => Icon::PolyStar, + Tool::Line => Icon::Line, + Tool::PaintBucket => Icon::Bucket, + Tool::InkBottle => Icon::Ink, + Tool::Hand => Icon::Hand, + Tool::Zoom => Icon::Zoom, + } +} + +pub fn tools(app: &mut App, ui: &mut egui::Ui) { + ui.vertical_centered(|ui| { + for tool in Tool::ALL { + let (rect, resp) = ui.allocate_exact_size(vec2(TOOL_BUTTON, TOOL_BUTTON), Sense::click()); + let active = app.tool == tool; + // The active tool sits on a lighter gray block with a white icon; the rest are a + // step dimmer, so the one in hand stands out without colour. + let bg = if active { + T.active + } else if resp.hovered() { + T.header + } else { + Color32::TRANSPARENT + }; + ui.painter().rect_filled(rect, T.rc(), bg); + let tint = if active || resp.hovered() { Color32::WHITE } else { T.icon }; + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(TOOL_ICON, TOOL_ICON)), tool_icon(tool), tint); + let key = app.keymap.primary(crate::keymap::tool_id(tool)).map(|k| format!(" ({})", crate::platform::shortcut_label(k))).unwrap_or_default(); + if resp.on_hover_text(format!("{}{key}\n{}", tool.label(), tool.hint())).clicked() { + app.tool = tool; + } + if matches!(tool, Tool::Transform | Tool::Pencil | Tool::Line | Tool::InkBottle) { + // Tool groups: select, draw by hand, shapes, view. + ui.add_space(3.0); + let y = ui.cursor().top(); + ui.painter().line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(1.0, T.border)); + ui.add_space(4.0); + } + } + ui.add_space(10.0); + // fill / stroke swatches + let st = app.s.style; + let (r, _) = ui.allocate_exact_size(vec2(TOOL_BUTTON, TOOL_BUTTON), Sense::hover()); + let back = Rect::from_min_size(r.left_top() + vec2(14.0, 14.0), vec2(24.0, 24.0)); + let front = Rect::from_min_size(r.left_top() + vec2(2.0, 2.0), vec2(24.0, 24.0)); + ui.painter().rect_filled(back, T.rc(), if st.use_fill { to_color32(st.fill) } else { T.field }); + ui.painter().rect_stroke(back, T.rc(), Stroke::new(1.0, T.border), StrokeKind::Inside); + ui.painter().rect_filled(front, T.rc(), T.panel); + ui.painter().rect_stroke(front.shrink(1.0), T.rc(), Stroke::new(5.0, if st.use_stroke { to_color32(st.stroke) } else { T.field }), StrokeKind::Inside); + ui.painter().rect_stroke(front, T.rc(), Stroke::new(1.0, T.border), StrokeKind::Inside); + }); +} + +// ----- edit bar & status ------------------------------------------------------------------ + +pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { + ui.horizontal_centered(|ui| { + ui.label(text(Type::Body, "Scene 1").strong()); + ui.label(text(Type::Caption, "›")); + let layer = app.s.active_layer().map_or("—".to_string(), |l| l.name.clone()); + ui.label(text(Type::Body, layer).color(T.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let z = app.view.zoom; + let canvas = app.stage_cache.canvas; + egui::ComboBox::from_id_salt("zoom").width(84.0).selected_text(text(Type::Data, format!("{:>4.0}%", z * 100.0))).show_ui(ui, |ui| { + if ui.selectable_label(false, "Fit in window").clicked() { + app.view.fit = true; + } + for pct in [25.0f32, 50.0, 100.0, 200.0, 400.0, 800.0] { + if ui.selectable_label((z * 100.0 - pct).abs() < 0.5, text(Type::Data, format!("{pct:>4.0}%"))).clicked() { + app.zoom_about(canvas, canvas.center(), pct / 100.0); + } + } + }); + if ui.selectable_label(app.onion, "Onion skin").clicked() { + app.onion = !app.onion; + } + let st = app.s.doc.stage; + ui.label(text(Type::Data, format!("{} × {} px", st.width, st.height)).color(T.text_faint)); + }); + }); +} + +pub fn status_bar(app: &mut App, ui: &mut egui::Ui) { + ui.horizontal_centered(|ui| { + let now = ui.input(|i| i.time); + let msg = app.status.as_ref().filter(|s| s.error || now - s.at < 8.0 || s.at == 0.0); + match msg { + Some(s) => { + ui.label(text(Type::Label, s.text.clone()).color(if s.error { T.error } else { T.ok })); + } + None => { + ui.label(text(Type::Label, app.tool.hint())); + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let small = |t: String| text(Type::Data, t).color(T.text_faint); + ui.label(small(format!("undo {} · {:.1} MB", app.s.history().undo_len(), app.s.history().bytes() as f32 / (1024.0 * 1024.0)))); + ui.add_space(12.0); + if let Some((n, mb, hit)) = app.stage_cache.stats() { + ui.label(small(format!("cache {n} fr · {mb:.0} MB · {hit:.0}% hit"))); + ui.add_space(12.0); + } + let (ready, needed) = app.stage_cache.ready; + ui.label(small(format!("render {:.1} ms · tiles {ready}/{needed}", app.stage_cache.ms))); + if let Some(p) = app.cursor_stage { + ui.label(small(format!("x {:.0} y {:.0}", p.x, p.y))); + } + }); + }); +} + +// ----- right dock --------------------------------------------------------------------------- + +fn rgb(c: Rgba) -> [u8; 3] { + let c = c.sanitized(); + [(c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8] +} + +fn hex(c: [u8; 3]) -> String { + format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) +} + +/// Runs a command from a continuously-edited widget, coalescing into one undo step. +fn live(app: &mut App, label: &str, id: &str, p: Value) { + app.s.begin_gesture(label); + app.run(id, p); +} + +/// A property row for values: proportional label (left-aligned column), monospace fields. +fn row(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui)) { + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, label, |ui| with_type(ui, Type::Data, add)); +} + +/// A property row whose field holds prose (names, labels, preset choices). +fn row_prose(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui)) { + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, label, add); +} + +pub fn right(app: &mut App, ui: &mut egui::Ui) { + let h = ui.available_height(); + // Dock sections are layout bands; each folds away to give the others room. + egui::ScrollArea::vertical().id_salt("props").max_height(h * 0.56).auto_shrink([false, true]).show(ui, |ui| { + section(ui, "dock_properties", Section::Band, "Properties", None, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| properties(app, ui)); + }); + }); + section(ui, "dock_align", Section::Band, "Align", None, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| align_panel(app, ui)); + }); + section(ui, "dock_library", Section::Band, "Library", None, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); + }); + section(ui, "dock_history", Section::Band, "History", None, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| history(app, ui)); + }); +} + +/// The Align panel: align edges or centres, distribute, relative to the selection or the stage. +fn align_panel(app: &mut App, ui: &mut egui::Ui) { + let has_sel = !app.s.selection.is_empty(); + let button = |app: &mut App, ui: &mut egui::Ui, icon: Icon, id: &str| { + let (rect, resp) = ui.allocate_exact_size(vec2(TARGET + 4.0, TARGET), if has_sel { Sense::click() } else { Sense::hover() }); + if has_sel && resp.hovered() { + ui.painter().rect_filled(rect, T.rc(), T.hover); + } + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(18.0, 18.0)), icon, if !has_sel { T.text_faint } else if resp.hovered() { Color32::WHITE } else { T.icon }); + let spec = anicraft_engine::find_command(id); + let tip = spec.map_or_else(String::new, |c| match app.keymap.primary(c.id) { + Some(k) => format!("{} ({})", c.label, crate::platform::shortcut_label(k)), + None => c.label.to_string(), + }); + let tip = if has_sel { tip } else { format!("{tip}\nSelect something to align") }; + if resp.on_hover_text(tip).clicked() { + // Leave it unset when off, so a single shape still aligns to the stage. + app.run(id, if app.align_to_stage { json!({"to_stage": true}) } else { json!({}) }); + } + }; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for (icon, id) in [(Icon::AlignLeft, "align.left"), (Icon::AlignHCenter, "align.hcenter"), (Icon::AlignRight, "align.right")] { + button(app, ui, icon, id); + } + ui.add_space(10.0); + for (icon, id) in [(Icon::AlignTop, "align.top"), (Icon::AlignVCenter, "align.vcenter"), (Icon::AlignBottom, "align.bottom")] { + button(app, ui, icon, id); + } + }); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + button(app, ui, Icon::DistributeH, "align.distribute_h"); + button(app, ui, Icon::DistributeV, "align.distribute_v"); + ui.add_space(12.0); + crate::theme::checkbox(ui, &mut app.align_to_stage, text(Type::Body, "To stage")).on_hover_text("Align to the stage instead of the selection's bounds (a single shape always aligns to the stage)"); + }); +} + +/// Undo history: past steps (click to go back), the current state, and redoable steps (dimmed). +fn history(app: &mut App, ui: &mut egui::Ui) { + let hist = app.s.history(); + let past: Vec = hist.undo_labels().map(str::to_string).collect(); + let future: Vec = hist.redo_labels().map(str::to_string).collect(); + let evicted = hist.evicted; + let mut target = None; + egui::ScrollArea::vertical().id_salt("history").max_height(ui.available_height().max(60.0)).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + let base = if evicted > 0 { "… older steps freed (memory budget)" } else { "Opened document" }; + if ui.selectable_label(past.is_empty(), text(Type::Body, base).color(if evicted > 0 { T.text_faint } else { T.text_dim })).clicked() { + target = Some(0); + } + for (i, label) in past.iter().enumerate() { + let current = i + 1 == past.len(); + if ui.selectable_label(current, label.as_str()).clicked() { + target = Some(i + 1); + } + } + for (i, label) in future.iter().enumerate() { + if ui.selectable_label(false, text(Type::Body, label.as_str()).color(T.text_faint).italics()).clicked() { + target = Some(past.len() + i + 1); + } + } + }); + if let Some(t) = target + && let Err(e) = app.s.travel_to(t) + { + app.status_err(e.to_string()); + } +} + +fn properties(app: &mut App, ui: &mut egui::Ui) { + let elements = app.s.visible_elements(); + let sel: Vec<_> = elements.iter().filter(|e| app.s.selection.contains(&e.id)).cloned().collect(); + + // ---- tool options first while a drawing tool is in hand: they're what you reach for ---- + if matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::PaintBucket | Tool::InkBottle) { + let title = format!("{} tool", app.tool.label()); + section(ui, "prop_tool", Section::Rule, &title, None, |ui| tool_props(app, ui)); + } + if let Some(e) = sel.first() { + let title = if sel.len() > 1 { format!("{} elements", sel.len()) } else { element_label(&app.s.doc, e) }; + section(ui, "prop_selection", Section::Rule, &title, None, |ui| selection_props(app, ui, e, sel.len())); + } else { + section(ui, "prop_document", Section::Rule, "Document", None, |ui| document_props(app, ui)); + } + // ---- frame ---- + let frame = app.s.frame; + if let Some(layer) = app.s.active_layer().cloned() { + // Mixed title: prose label, data value. + let detail = format!("{} · {}", frame + 1, layer.name); + section(ui, "prop_frame", Section::Rule, "Frame", Some(&detail), |ui| frame_props(app, ui, &layer, frame)); + } +} + +fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, _count: usize) { + { + let d = e.transform.decompose(); + let (mut x, mut y, mut sx, mut sy, mut rot) = (d.tx, d.ty, d.sx * 100.0, d.sy * 100.0, d.rotation.to_degrees()); + row(ui, "Position", |ui| { + let a = ui.add(egui::DragValue::new(&mut x).prefix("X ").speed(1.0).max_decimals(1)); + let b = ui.add(egui::DragValue::new(&mut y).prefix("Y ").speed(1.0).max_decimals(1)); + if a.changed() || b.changed() { + live(app, "Move", "element.set_transform", json!({"x": x, "y": y})); + } + }); + row(ui, "Scale", |ui| { + let a = ui.add(egui::DragValue::new(&mut sx).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)); + let b = ui.add(egui::DragValue::new(&mut sy).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)); + if a.changed() || b.changed() { + live(app, "Scale", "element.set_transform", json!({"sx": sx / 100.0, "sy": sy / 100.0})); + } + }); + row(ui, "Rotation", |ui| { + if ui.add(egui::DragValue::new(&mut rot).suffix("°").speed(0.5).range(-360.0..=360.0).max_decimals(1)).changed() { + live(app, "Rotate", "element.set_transform", json!({"rotation": rot})); + } + }); + let mut alpha = e.color.alpha * 100.0; + row(ui, "Alpha", |ui| { + if ui.add(egui::Slider::new(&mut alpha, 0.0..=100.0).suffix(" %").max_decimals(0)).changed() { + live(app, "Alpha", "element.set_alpha", json!({"alpha": alpha / 100.0})); + } + }); + if let ElementKind::Shape(sh) = &e.kind { + ui.add_space(4.0); + let fill = sh.fill.as_ref().map(Paint::primary_color); + row(ui, "Fill", |ui| { + let is_grad = matches!(sh.fill, Some(Paint::Linear { .. } | Paint::Radial { .. })); + let mut c = rgb(fill.unwrap_or(Rgba::WHITE)); + if ui.color_edit_button_srgb(&mut c).changed() { + live(app, "Fill colour", "element.set_fill", json!({"color": hex(c)})); + } + let mut on = fill.is_some(); + if crate::theme::checkbox(ui, &mut on, "").on_hover_text("Fill on/off").changed() { + app.run("element.set_fill", if on { json!({"color": hex(c)}) } else { json!({"color": null}) }); + } + if is_grad { + ui.label(text(Type::Caption, "gradient")); + } + }); + let mut sc = rgb(sh.stroke.map_or(app.s.style.stroke, |s| s.color)); + let mut sw = sh.stroke.map_or(0.0, |s| s.width); + row(ui, "Stroke", |ui| { + if ui.color_edit_button_srgb(&mut sc).changed() { + live(app, "Stroke colour", "element.set_stroke", json!({"color": hex(sc)})); + } + if ui.add(egui::DragValue::new(&mut sw).suffix(" px").speed(0.1).range(0.0..=200.0).max_decimals(1)).changed() { + live(app, "Stroke width", "element.set_stroke", json!({"width": sw})); + } + }); + } + ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + for (label, id) in [("Convert to Symbol", "modify.convert_to_symbol"), ("Break Apart", "modify.break_apart"), ("Duplicate", "edit.duplicate"), ("Delete", "edit.delete")] { + if ui.button(label).clicked() { + app.invoke(id); + } + } + }); + } +} + +fn document_props(app: &mut App, ui: &mut egui::Ui) { + { + let st = app.s.doc.stage; + let (mut w, mut h, mut fps) = (st.width, st.height, st.fps); + row(ui, "Size", |ui| { + let a = ui.add(egui::DragValue::new(&mut w).suffix(" px").range(1..=8192)); + let b = ui.add(egui::DragValue::new(&mut h).suffix(" px").range(1..=8192)); + if a.changed() || b.changed() { + live(app, "Stage size", "doc.set_stage", json!({"width": w, "height": h})); + } + }); + row(ui, "Frame rate", |ui| { + if ui.add(egui::DragValue::new(&mut fps).suffix(" fps").speed(0.1).range(1.0..=120.0).max_decimals(2)).changed() { + live(app, "Frame rate", "doc.set_stage", json!({"fps": fps})); + } + }); + let mut bg = rgb(st.background); + row(ui, "Stage", |ui| { + if ui.color_edit_button_srgb(&mut bg).changed() { + live(app, "Stage colour", "doc.set_stage", json!({"background": hex(bg)})); + } + ui.label(text(Type::Data, format!("{} frames", app.s.frame_count())).color(T.text_faint)); + }); + } +} + +fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::Layer, frame: u32) { + { + match layer.keyframe_at(frame) { + Some(k) => { + let n = evaluate_layer_elements(layer, frame).map_or(0, |(_, e)| e.len()); + let (frames, els) = (if k.duration == 1 { "frame" } else { "frames" }, if n == 1 { "element" } else { "elements" }); + ui.label(text(Type::Label, format!("Keyframe at {} · {} {frames} · {n} {els}", k.start + 1, k.duration))); + if layer.kind == anicraft_engine::doc::LayerKind::Mask { + ui.label(text(Type::Caption, "Mask layer: its fills reveal the masked layers below. Lock it to hide its outline.")); + } + let mut label = k.label.clone(); + row_prose(ui, "Label", |ui| { + if ui.add(egui::TextEdit::singleline(&mut label).desired_width(150.0)).changed() { + live(app, "Frame label", "timeline.set_label", json!({"label": label})); + } + }); + match k.tween { + Some(t) => { + row_prose(ui, "Tween", |ui| { + egui::ComboBox::from_id_salt("prop_ease").width(150.0).selected_text(t.easing.label()).show_ui(ui, |ui| { + for (name, e) in anicraft_engine::doc::Easing::PRESETS { + if ui.selectable_label(t.easing == e, name).clicked() { + app.run("timeline.set_easing", json!({"easing": crate::timeline::easing_param(e)})); + } + } + }); + }); + ease_curve(ui, t.easing); + } + None => { + if ui.button("Create Classic Tween").clicked() { + app.run("timeline.create_tween", json!({})); + } + } + } + } + None => { + ui.label(text(Type::Caption, "Empty frame — press F7 for a blank keyframe")); + } + } + } +} + +fn tool_props(app: &mut App, ui: &mut egui::Ui) { + let mut st = app.s.style; + // Each tool shows only what it uses: the bucket always fills, the ink bottle always strokes. + let (bucket, ink) = (app.tool == Tool::PaintBucket, app.tool == Tool::InkBottle); + if !ink { + row(ui, "Fill", |ui| { + let mut c = rgb(st.fill); + if ui.color_edit_button_srgb(&mut c).changed() { + st.fill = Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0); + } + if !bucket { + crate::theme::checkbox(ui, &mut st.use_fill, ""); + } + }); + } + if !bucket { + row(ui, "Stroke", |ui| { + let mut c = rgb(st.stroke); + if ui.color_edit_button_srgb(&mut c).changed() { + st.stroke = Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0); + } + if !ink { + crate::theme::checkbox(ui, &mut st.use_stroke, ""); + } + ui.add(egui::DragValue::new(&mut st.stroke_width).suffix(" px").speed(0.1).range(0.0..=100.0).max_decimals(1)); + }); + } + app.s.style = st; + match app.tool { + Tool::Rect => row(ui, "Corners", |ui| { + ui.add(egui::DragValue::new(&mut app.rect_radius).suffix(" px").range(0.0..=500.0)); + }), + Tool::Star => row(ui, "Points", |ui| { + ui.add(egui::DragValue::new(&mut app.star_points).range(3..=32)); + }), + Tool::PaintBucket => row_prose(ui, "Gap size", |ui| { + egui::ComboBox::from_id_salt("bucket_gap").width(170.0).selected_text(app.bucket_gap.label()).show_ui(ui, |ui| { + for g in crate::app::GapSize::ALL { + ui.selectable_value(&mut app.bucket_gap, g, g.label()); + } + }); + }), + Tool::Pencil => row(ui, "Mode", |ui| { + use crate::pathtools::PencilMode; + for m in [PencilMode::Smooth, PencilMode::Straighten, PencilMode::Ink] { + ui.selectable_value(&mut app.pencil_mode, m, m.label()).on_hover_text(m.hint()); + } + }), + _ => {} + } +} + +/// Plots the easing curve (output against time). +fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) { + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width().min(240.0), 70.0), Sense::hover()); + let p = ui.painter(); + p.rect_filled(r, T.rc(), T.field); + let inner = r.shrink(8.0); + let pts: Vec = (0..=48) + .map(|i| { + let t = i as f32 / 48.0; + pos2(inner.left() + t * inner.width(), inner.bottom() - e.apply(t) * inner.height()) + }) + .collect(); + p.line_segment([inner.left_bottom(), inner.right_top()], Stroke::new(1.0, T.border)); + p.add(egui::Shape::line(pts, Stroke::new(2.0, T.tween))); +} + +fn library(app: &mut App, ui: &mut egui::Ui) { + let lib = app.s.doc.library.clone(); + if lib.is_empty() { + ui.label(text(Type::Caption, "No symbols yet. Select artwork and press F8.")); + return; + } + ui.label(text(Type::Caption, format!("{} items", lib.len()))); + egui::ScrollArea::vertical().id_salt("lib").max_height(140.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, sym) in lib.iter().enumerate() { + let selected = app.library_sel == Some(i); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click()); + if selected || resp.hovered() { + ui.painter().rect_filled(r, T.rc(), if selected { T.accent_dim } else { T.hover }); + } + if selected { + ui.painter().rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); + } + let icon = Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(14.0, 14.0)); + let kind_color = match sym.kind { + SymbolKind::Graphic => T.kind_graphic, + SymbolKind::MovieClip => T.kind_movie_clip, + SymbolKind::Button => T.kind_button, + }; + ui.painter().rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside); + ui.painter().circle_filled(icon.center(), 2.5, kind_color); + ui.painter().text(r.left_center() + vec2(30.0, 0.0), Align2::LEFT_CENTER, &sym.name, font(Type::Body), color(Type::Body)); + ui.painter().text( + r.right_center() - vec2(8.0, 0.0), + Align2::RIGHT_CENTER, + format!("{:?} · {}f", sym.kind, sym.timeline.frame_count()), + font(Type::Caption), + color(Type::Caption), + ); + if resp.clicked() { + app.library_sel = Some(i); + } + if resp.double_clicked() { + app.run("library.place", json!({"symbol": sym.id.0})); + } + } + }); + ui.add_space(4.0); + let can_place = app.library_sel.and_then(|i| lib.get(i)).map(|s| s.id.0); + if ui.add_enabled(can_place.is_some(), egui::Button::new("Place on stage")).on_hover_text("Adds an instance at the stage centre (or double-click an item)").clicked() + && let Some(id) = can_place { + app.run("library.place", json!({"symbol": id})); + } +} diff --git a/src/pathtools.rs b/src/pathtools.rs new file mode 100644 index 00000000..5dc06f82 --- /dev/null +++ b/src/pathtools.rs @@ -0,0 +1,523 @@ +//! Pen (P), Pencil (Shift+Y) and Subselection (A). +//! +//! The Pen's interaction model comes from PhotoCraft's Pen (`vector_ui.rs`): knots kept as +//! `[anchor, in, out]` while drawing, a press adds a knot, dragging pulls mirrored handles, +//! pressing the first knot closes the path, and the finished path is one command, so one undo +//! step. Added here: Alt breaks the handles, a click on the last knot (or a double-click) +//! finishes an open path, Backspace takes back the last knot, a tiny drag stays a corner, and +//! switching tools keeps the path instead of dropping it. +//! +//! Only view state lives here. Every document change is an engine command (`draw.path`, +//! `draw.freehand`, `path.*`), so agents and the CLI draw and edit exactly the same way. + +use crate::app::{App, Drag, Tool}; +use crate::theme::T; +use anicraft_engine::doc::{ElementId, ElementKind}; +use anicraft_engine::geom::edit::{ANCHOR, C1, C2}; +use anicraft_engine::geom::{Affine, Path, PathCmd, Vec2}; +use egui::{Color32, Key, Modifiers, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; +use serde_json::json; +use std::sync::Arc; + +/// Screen ↔ stage mapping of the current frame. +#[derive(Clone, Copy)] +pub struct Xf { + pub origin: Pos2, + pub zoom: f32, +} + +impl Xf { + pub fn to_screen(self, p: Vec2) -> Pos2 { + pos2(self.origin.x + p.x * self.zoom, self.origin.y + p.y * self.zoom) + } + pub fn to_stage(self, p: Pos2) -> Vec2 { + Vec2::new((p.x - self.origin.x) / self.zoom, (p.y - self.origin.y) / self.zoom) + } + /// Stage units per screen point. + fn unit(self) -> f32 { + 1.0 / self.zoom.max(1e-3) + } +} + +/// Pick radius for points and knots, in screen points. +const PICK: f32 = 6.0; + +// ----- Pen --------------------------------------------------------------------------------- + +/// Pen path under construction: knots as `[anchor, in, out]` in stage space. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PenPath { + pub knots: Vec<[Vec2; 3]>, + pub dragging: bool, +} + +impl PenPath { + /// SVG path data for `draw.path`. Straight where both handles sit on their anchors. + pub fn to_svg(&self, closed: bool) -> String { + let mut d = String::new(); + let Some(first) = self.knots.first() else { return d }; + d.push_str(&format!("M{} {}", first[0].x, first[0].y)); + let seg = |d: &mut String, a: &[Vec2; 3], b: &[Vec2; 3]| { + if a[2] == a[0] && b[1] == b[0] { + d.push_str(&format!(" L{} {}", b[0].x, b[0].y)); + } else { + d.push_str(&format!(" C{} {} {} {} {} {}", a[2].x, a[2].y, b[1].x, b[1].y, b[0].x, b[0].y)); + } + }; + for w in self.knots.windows(2) { + seg(&mut d, &w[0], &w[1]); + } + if closed { + if let Some(last) = self.knots.last() + && (last[2] != last[0] || first[1] != first[0]) + { + seg(&mut d, last, first); + } + d.push_str(" Z"); + } + d + } +} + +/// Pointer handling for the Pen. Runs on raw press/release (not egui's drag threshold), so a +/// quick click places a point exactly where it was pressed. +pub fn pen_input(app: &mut App, ui: &egui::Ui, resp: &egui::Response, xf: Xf) { + let (pressed, down, alt) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_down(), i.modifiers.alt)); + let Some(pos) = resp.interact_pointer_pos().or_else(|| resp.hover_pos()) else { return }; + let p = xf.to_stage(pos); + if pressed && resp.hovered() { + let tol = PICK * xf.unit(); + let pen = app.pen.get_or_insert_with(PenPath::default); + let n = pen.knots.len(); + if n >= 2 && pen.knots.first().is_some_and(|k| k[0].distance(p) <= tol) { + commit_pen(app, true); + return; + } + if n >= 2 && pen.knots.last().is_some_and(|k| k[0].distance(p) <= tol) { + commit_pen(app, false); + return; + } + pen.knots.push([p; 3]); + pen.dragging = true; + return; + } + let Some(pen) = app.pen.as_mut() else { return }; + if !down { + pen.dragging = false; + return; + } + if pen.dragging + && let Some(k) = pen.knots.last_mut() + { + let a = k[0]; + if a.distance(p) * xf.zoom < 2.0 { + // A press that barely moved is a corner. + *k = [a; 3]; + } else { + k[2] = p; + if !alt { + k[1] = a * 2.0 - p; + } + } + } +} + +/// Finishes the Pen path as a shape (one undo step). Fewer than two knots are dropped. +pub fn commit_pen(app: &mut App, closed: bool) { + let Some(pen) = app.pen.take() else { return }; + if pen.knots.len() < 2 { + return; + } + app.run("draw.path", json!({"d": pen.to_svg(closed)})); +} + +// ----- Pencil ------------------------------------------------------------------------------ + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum PencilMode { + #[default] + Smooth, + Straighten, + Ink, +} + +impl PencilMode { + pub fn label(self) -> &'static str { + match self { + PencilMode::Smooth => "Smooth", + PencilMode::Straighten => "Straighten", + PencilMode::Ink => "Ink", + } + } + pub fn hint(self) -> &'static str { + match self { + PencilMode::Smooth => "Fits smooth curves to the stroke, keeping sharp corners.", + PencilMode::Straighten => "Turns the stroke into straight segments.", + PencilMode::Ink => "Follows the hand closely with little smoothing.", + } + } + fn id(self) -> &'static str { + match self { + PencilMode::Smooth => "smooth", + PencilMode::Straighten => "straighten", + PencilMode::Ink => "ink", + } + } +} + +/// Adds a pointer sample to the stroke (closer samples than half a screen point add nothing). +pub fn pencil_sample(app: &mut App, p: Vec2, xf: Xf) { + if app.pencil.last().is_none_or(|l| l.distance(p) * xf.zoom >= 0.5) && app.pencil.len() < 100_000 { + app.pencil.push(p); + } +} + +/// Sends the stroke to the engine; smoothing is relative to the screen, so a stroke looks the +/// same at any zoom. +pub fn commit_pencil(app: &mut App, xf: Xf) { + let pts = std::mem::take(&mut app.pencil); + if pts.len() < 2 { + return; + } + let points: Vec<[f32; 2]> = pts.iter().map(|p| [p.x, p.y]).collect(); + app.run("draw.freehand", json!({"points": points, "mode": app.pencil_mode.id(), "tolerance": 1.5 * xf.unit()})); +} + +// ----- Subselection -------------------------------------------------------------------------- + +/// A selected point: element, command, slot. +pub type PointRef = (ElementId, usize, u8); + +/// Selected shapes on the active layer with their path and transform. +fn selected_shapes(app: &App) -> Vec<(ElementId, Arc, Affine)> { + app.s + .visible_elements() + .into_iter() + .filter(|e| app.s.selection.contains(&e.id)) + .filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some((e.id, sh.path.clone(), e.transform)), + ElementKind::Symbol { .. } => None, + }) + .take(64) + .collect() +} + +/// Handles shown for the selected anchors: `(cmd, slot, anchor cmd)`. +fn shown_handles(path: &Path, anchors: impl Iterator) -> Vec<(usize, u8, usize)> { + let mut v = Vec::new(); + for a in anchors { + let (i, o) = path.anchor_segments(a); + if let Some(i) = i.filter(|&i| matches!(path.cmds.get(i), Some(PathCmd::CubicTo(..)))) { + v.push((i, C2, a)); + } + if let Some(o) = o.filter(|&o| matches!(path.cmds.get(o), Some(PathCmd::CubicTo(..)) | Some(PathCmd::QuadTo(..)))) { + v.push((o, C1, a)); + } + } + v +} + +/// Drops point references that no longer exist (after undo, deselection or a frame change). +pub fn upkeep(app: &mut App) { + if app.points.is_empty() { + return; + } + let shapes = selected_shapes(app); + app.points.retain(|(id, cmd, slot)| shapes.iter().any(|(e, p, _)| e == id && p.point(*cmd, *slot).is_some())); +} + +/// The point under screen position `at`: shown handles first (they sit on top), then anchors. +fn point_at(app: &App, at: Pos2, xf: Xf) -> Option { + let near = |q: Vec2, m: &Affine| xf.to_screen(m.apply(q)).distance(at) <= PICK; + for (id, path, m) in selected_shapes(app) { + let sel = app.points.iter().filter(|p| p.0 == id && p.2 == ANCHOR).map(|p| p.1); + for (cmd, slot, _) in shown_handles(&path, sel) { + if path.point(cmd, slot).is_some_and(|q| near(q, &m)) { + return Some((id, cmd, slot)); + } + } + if let Some((cmd, _)) = path.editable_anchors().into_iter().find(|(_, q)| near(*q, &m)) { + return Some((id, cmd, ANCHOR)); + } + } + None +} + +/// Press with the Subselection tool: grab a point, else a shape (moves it whole, as Animate +/// does when you drag an outline), else start a marquee over points. +pub fn subselect_drag_start(app: &mut App, press: Pos2, shift: bool, xf: Xf) -> Drag { + let sp = xf.to_stage(press); + if let Some(pt) = point_at(app, press, xf) { + if !app.points.contains(&pt) { + if !shift { + app.points.clear(); + } + app.points.push(pt); + } + app.s.begin_gesture("Move Points"); + return Drag::Points { last: pos2(sp.x, sp.y) }; + } + if let Some((_, el)) = app.s.hit_test(sp, 3.0 * xf.unit()) { + if !app.s.selection.contains(&el) { + app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); + app.points.clear(); + } + app.s.begin_gesture("Move"); + return Drag::Move { last: pos2(sp.x, sp.y) }; + } + if !shift { + app.points.clear(); + } + if selected_shapes(app).is_empty() { Drag::Marquee { start: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) } } else { Drag::PointMarquee { start: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) } } +} + +/// Moves the selected points by a stage-space delta (inside the open gesture). +pub fn move_points(app: &mut App, d: Vec2) { + let mut ids: Vec = app.points.iter().map(|p| p.0).collect(); + ids.dedup(); + for id in ids { + let pts: Vec<[u64; 2]> = app.points.iter().filter(|p| p.0 == id).map(|p| [p.1 as u64, u64::from(p.2)]).collect(); + app.run("path.move_points", json!({"id": id.0, "points": pts, "dx": d.x, "dy": d.y})); + } +} + +/// Selects the anchors inside a stage-space marquee. +pub fn marquee_points(app: &mut App, a: Pos2, b: Pos2, shift: bool) { + let r = Rect::from_two_pos(a, b); + if !shift { + app.points.clear(); + } + for (id, path, m) in selected_shapes(app) { + for (cmd, q) in path.editable_anchors() { + let s = m.apply(q); + if r.contains(pos2(s.x, s.y)) && !app.points.contains(&(id, cmd, ANCHOR)) { + app.points.push((id, cmd, ANCHOR)); + } + } + } +} + +/// Click with the Subselection tool: a point toggles into the point selection, a shape is +/// selected (showing its points), empty space clears both. +pub fn subselect_click(app: &mut App, at: Pos2, shift: bool, xf: Xf) { + if let Some(pt) = point_at(app, at, xf) { + if shift { + if let Some(i) = app.points.iter().position(|p| *p == pt) { + app.points.remove(i); + } else { + app.points.push(pt); + } + } else { + app.points = vec![pt]; + } + return; + } + let sp = xf.to_stage(at); + app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); + app.points.clear(); +} + +/// Double-click on a selected shape's outline adds a point there and selects it. +pub fn subselect_double_click(app: &mut App, at: Pos2, xf: Xf) { + let sp = xf.to_stage(at); + for (id, _, _) in selected_shapes(app) { + let r = app.s.execute("path.add_point", &json!({"id": id.0, "x": sp.x, "y": sp.y, "slop": PICK * xf.unit()})); + if let Ok(v) = r { + app.points = v["cmd"].as_u64().map(|c| vec![(id, c as usize, ANCHOR)]).unwrap_or_default(); + app.status_ok("Added a point. Ctrl+Z to undo."); + return; + } + } +} + +/// Anchors in the point selection, grouped per element. +fn selected_anchors(app: &App) -> Vec<(ElementId, Vec)> { + let mut out: Vec<(ElementId, Vec)> = Vec::new(); + for &(id, cmd, slot) in &app.points { + if slot != ANCHOR { + continue; + } + match out.iter_mut().find(|(e, _)| *e == id) { + Some((_, v)) => v.push(cmd as u64), + None => out.push((id, vec![cmd as u64])), + } + } + out +} + +pub fn delete_points(app: &mut App) { + for (id, cmds) in selected_anchors(app) { + app.run("path.delete_points", json!({"id": id.0, "cmds": cmds})); + } + app.points.clear(); +} + +pub fn convert_points(app: &mut App, smooth: bool) { + for (id, cmds) in selected_anchors(app) { + for cmd in cmds { + app.run("path.convert_point", json!({"id": id.0, "cmd": cmd, "smooth": smooth})); + } + } +} + +/// Right-click menu for selected points; false when no anchor is selected. +pub fn point_menu(app: &mut App, ui: &mut egui::Ui) -> bool { + if app.tool != Tool::Subselect || selected_anchors(app).is_empty() { + return false; + } + if ui.button("Make Smooth").clicked() { + convert_points(app, true); + ui.close(); + } + if ui.button("Make Corner").clicked() { + convert_points(app, false); + ui.close(); + } + ui.separator(); + if ui.button("Delete Point").clicked() { + delete_points(app); + ui.close(); + } + true +} + +// ----- keys ---------------------------------------------------------------------------------- + +/// Keys the path tools own while they are busy, taken before the global shortcuts (so Enter +/// finishes a path instead of starting playback, and Delete removes points, not the shape). +pub fn consume_keys(app: &mut App, ctx: &egui::Context) { + let take = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); + if app.pen.is_some() { + if take(Key::Enter) || take(Key::Escape) { + commit_pen(app, false); + } + if (take(Key::Backspace) || take(Key::Delete)) + && let Some(pen) = app.pen.as_mut() + { + pen.knots.pop(); + if pen.knots.is_empty() { + app.pen = None; + } + } + } + if app.tool == Tool::Subselect && !app.points.is_empty() { + if take(Key::Delete) || take(Key::Backspace) { + delete_points(app); + } + if take(Key::Escape) { + app.points.clear(); + } + } +} + +// ----- drawing ------------------------------------------------------------------------------- + +fn bezier(p0: Vec2, c0: Vec2, c1: Vec2, p1: Vec2, t: f32) -> Vec2 { + let u = 1.0 - t; + p0 * (u * u * u) + c0 * (3.0 * u * u * t) + c1 * (3.0 * u * t * t) + p1 * (t * t * t) +} + +fn anchor_box(painter: &egui::Painter, c: Pos2, filled: bool) { + let r = Rect::from_center_size(c, vec2(6.0, 6.0)); + painter.rect_filled(r, 0.0, if filled { T.selection } else { Color32::WHITE }); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle); +} + +/// Path tool overlays: point editing on selected shapes, the Pen path being drawn and the +/// Pencil stroke in progress. +pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option) { + let line = Stroke::new(1.0, T.selection); + if app.tool == Tool::Subselect { + for (id, path, m) in selected_shapes(app) { + let to_px = Affine::translate(xf.origin.x, xf.origin.y).mul(&Affine::scale(xf.zoom, xf.zoom)).mul(&m); + for pl in path.flatten(&to_px, 0.35) { + let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); + painter.add(if pl.closed { egui::Shape::closed_line(pts, line) } else { egui::Shape::line(pts, line) }); + } + let sel = app.points.iter().filter(|p| p.0 == id && p.2 == ANCHOR).map(|p| p.1); + for (cmd, slot, anchor) in shown_handles(&path, sel) { + if let (Some(h), Some(a)) = (path.point(cmd, slot), path.point(anchor, ANCHOR)) { + let (hs, as_) = (xf.to_screen(m.apply(h)), xf.to_screen(m.apply(a))); + painter.line_segment([as_, hs], line); + let picked = app.points.contains(&(id, cmd, slot)); + painter.circle(hs, 3.0, if picked { T.selection } else { Color32::WHITE }, line); + } + } + for (cmd, q) in path.editable_anchors().into_iter().take(20_000) { + anchor_box(painter, xf.to_screen(m.apply(q)), app.points.contains(&(id, cmd, ANCHOR))); + } + } + } + if let Some(pen) = &app.pen { + let stroke = Stroke::new(1.5, T.selection); + let mut pts = Vec::new(); + for w in pen.knots.windows(2) { + for k in 0..=16 { + pts.push(xf.to_screen(bezier(w[0][0], w[0][2], w[1][1], w[1][0], k as f32 / 16.0))); + } + } + painter.add(egui::Shape::line(pts, stroke)); + let first = pen.knots.first().map(|k| xf.to_screen(k[0])); + if let (Some(last), Some(h)) = (pen.knots.last(), hover) + && !pen.dragging + { + painter.add(egui::Shape::dashed_line(&[xf.to_screen(last[0]), h], line, 4.0, 3.0)); + // Closing cue: a ring on the first point when a click would close the path. + if pen.knots.len() >= 2 + && let Some(f) = first + && f.distance(h) <= PICK + { + painter.circle_stroke(f, 6.0, Stroke::new(1.5, T.selection)); + } + } + for (i, k) in pen.knots.iter().enumerate() { + let c = xf.to_screen(k[0]); + let last = i + 1 == pen.knots.len(); + if last && k[2] != k[0] { + for hnd in [k[1], k[2]] { + let hp = xf.to_screen(hnd); + painter.line_segment([c, hp], line); + painter.circle_filled(hp, 3.0, T.selection); + } + } + anchor_box(painter, c, last); + } + } + if app.drag == Drag::Pencil && app.pencil.len() > 1 { + let w = (app.s.style.stroke_width * xf.zoom).max(1.0); + let pts: Vec = app.pencil.iter().map(|p| xf.to_screen(*p)).collect(); + painter.add(egui::Shape::line(pts, Stroke::new(w, crate::theme::to_color32(app.s.style.stroke)))); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn knot(x: f32, y: f32) -> [Vec2; 3] { + [Vec2::new(x, y); 3] + } + + #[test] + fn pen_svg_is_straight_for_corners_and_curved_for_handles() { + let mut pen = PenPath { knots: vec![knot(0.0, 0.0), knot(100.0, 0.0), knot(100.0, 50.0)], dragging: false }; + assert_eq!(pen.to_svg(false), "M0 0 L100 0 L100 50"); + assert_eq!(pen.to_svg(true), "M0 0 L100 0 L100 50 Z"); + pen.knots[1] = [Vec2::new(100.0, 0.0), Vec2::new(80.0, -10.0), Vec2::new(120.0, 10.0)]; + let d = pen.to_svg(false); + assert!(d.contains(" C0 0 80 -10 100 0") && d.contains(" C120 10 100 50 100 50"), "{d}"); + // The engine takes it. + let mut s = anicraft_engine::Session::default(); + assert!(s.execute("draw.path", &json!({"d": pen.to_svg(true)})).is_ok()); + } + + #[test] + fn handles_shown_for_a_selected_smooth_anchor() { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(10.0, 10.0)).line_to(Vec2::new(20.0, 0.0)); + assert!(shown_handles(&p, [1usize].into_iter()).is_empty(), "lines have no handles"); + assert!(p.make_smooth(1)); + let h = shown_handles(&p, [1usize].into_iter()); + assert_eq!(h, vec![(1, C2, 1), (2, C1, 1)]); + } +} diff --git a/src/platform.rs b/src/platform.rs new file mode 100644 index 00000000..f3bfab45 --- /dev/null +++ b/src/platform.rs @@ -0,0 +1,168 @@ +//! Platform layer (ADR 0006). Every OS-specific decision in the shell lives here, so the rest +//! of the UI is written once: shortcut labels (⌘ on macOS), window chrome, the settings folder, +//! native file dialogs and the renderer choice. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Os { + Mac, + Windows, + Linux, + Other, +} + +pub const OS: Os = if cfg!(target_os = "macos") { + Os::Mac +} else if cfg!(target_os = "windows") { + Os::Windows +} else if cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly")) { + Os::Linux +} else { + Os::Other +}; + +impl Os { + pub fn name(self) -> &'static str { + match self { + Os::Mac => "macOS", + Os::Windows => "Windows", + Os::Linux => "Linux / BSD", + Os::Other => "other", + } + } +} + +/// Whether the active fonts can draw ⌘ ⇧ ⌥ ⌃ (set once fonts are installed). +static MAC_GLYPHS: AtomicBool = AtomicBool::new(false); + +pub fn set_mac_glyphs(available: bool) { + MAC_GLYPHS.store(available, Ordering::Relaxed); +} + +/// A registry shortcut ("Ctrl+Shift+S") as this platform writes it: unchanged on Windows and +/// Linux; "⇧⌘S" on macOS (or "Shift+Cmd+S" when the font lacks the symbols). +pub fn shortcut_label(s: &str) -> String { + shortcut_label_for(OS, s, MAC_GLYPHS.load(Ordering::Relaxed)) +} + +pub fn shortcut_label_for(os: Os, s: &str, glyphs: bool) -> String { + if os != Os::Mac || s.is_empty() { + return s.to_string(); + } + // A trailing "+" key ("Ctrl++") must survive the split. + let (mods, key) = match s.rsplit_once('+') { + Some((m, "")) => (m.trim_end_matches('+'), "+"), + Some((m, k)) => (m, k), + None => ("", s), + }; + let has = |m: &str| mods.split('+').any(|x| x == m); + let key = match (key, glyphs) { + ("Delete", true) => "⌫", + ("Enter", true) => "↩", + ("Up", true) => "↑", + ("Down", true) => "↓", + ("Left", true) => "←", + ("Right", true) => "→", + (k, _) => k, + }; + // Apple order: Control, Option, Shift, Command. Our "Ctrl" is the command modifier. + let mut out = String::new(); + for (name, glyph, text) in [("Alt", "⌥", "Option+"), ("Shift", "⇧", "Shift+"), ("Ctrl", "⌘", "Cmd+")] { + if has(name) { + out.push_str(if glyphs { glyph } else { text }); + } + } + out.push_str(key); + out +} + +/// Where preferences live: %APPDATA%\AniCraft, ~/Library/Application Support/AniCraft, or +/// $XDG_CONFIG_HOME/anicraft (default ~/.config/anicraft). +pub fn config_dir() -> Option { + let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from); + match OS { + Os::Windows => env("APPDATA").map(|p| p.join("AniCraft")), + Os::Mac => env("HOME").map(|p| p.join("Library").join("Application Support").join("AniCraft")), + Os::Linux | Os::Other => env("XDG_CONFIG_HOME").or_else(|| env("HOME").map(|h| h.join(".config"))).map(|p| p.join("anicraft")), + } +} + +/// Main-window chrome. macOS gets the unified look (content under a transparent title bar, +/// traffic lights over our menu row); Windows and Linux keep their native frames. +pub fn viewport(b: egui::ViewportBuilder) -> egui::ViewportBuilder { + let b = b.with_app_id("anicraft"); // Wayland/X11 window class, for docks and window rules + match OS { + Os::Mac => b.with_fullsize_content_view(true).with_title_shown(false), + _ => b, + } +} + +/// Space left of the menu row for the macOS traffic-light buttons. +pub fn menu_inset() -> f32 { + if OS == Os::Mac { 72.0 } else { 0.0 } +} + +/// Renderer requested by `--renderer` / `ANICRAFT_RENDERER` (`wgpu` or `gl`), if any. +pub fn forced_renderer(arg: Option<&str>) -> Option { + let v = arg.map(str::to_owned).or_else(|| std::env::var("ANICRAFT_RENDERER").ok())?; + match v.to_ascii_lowercase().as_str() { + "gl" | "glow" | "opengl" => Some(eframe::Renderer::Glow), + "wgpu" | "vulkan" | "metal" | "dx12" => Some(eframe::Renderer::Wgpu), + _ => None, + } +} + +// ----- native file dialogs ---------------------------------------------------------------------- + +/// File type filters per command. +pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { + match cmd { + "file.export_png" => ("PNG image", &["png"]), + "file.export_gif" => ("Animated GIF", &["gif"]), + // Opening also imports .fla archives and .xfl packages. + "file.open" => ("Documents", &["anicraft", "fla", "xfl"]), + _ => ("AniCraft document", &["anicraft"]), + } +} + +/// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal). +/// `None` when cancelled. +pub fn file_dialog(cmd: &str, title: &str, default_name: &str) -> Option { + let (label, exts) = filters(cmd); + let d = rfd::FileDialog::new().set_title(title); + match cmd { + "file.open" => d.add_filter(label, exts).pick_file(), + "file.export_png_sequence" => d.pick_folder(), + _ => d.add_filter(label, exts).set_file_name(default_name).save_file(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mac_labels_use_apple_order_and_glyphs() { + assert_eq!(shortcut_label_for(Os::Mac, "Ctrl+Shift+S", true), "⇧⌘S"); + assert_eq!(shortcut_label_for(Os::Mac, "Ctrl+Alt+1", true), "⌥⌘1"); + assert_eq!(shortcut_label_for(Os::Mac, "Ctrl+Shift+S", false), "Shift+Cmd+S"); + assert_eq!(shortcut_label_for(Os::Mac, "Delete", true), "⌫"); + assert_eq!(shortcut_label_for(Os::Mac, "F6", true), "F6"); + assert_eq!(shortcut_label_for(Os::Mac, "Ctrl++", true), "⌘+"); + } + + #[test] + fn other_platforms_keep_registry_labels() { + for os in [Os::Windows, Os::Linux] { + assert_eq!(shortcut_label_for(os, "Ctrl+Shift+Z", true), "Ctrl+Shift+Z"); + } + } + + #[test] + fn renderer_override() { + assert_eq!(forced_renderer(Some("gl")), Some(eframe::Renderer::Glow)); + assert_eq!(forced_renderer(Some("WGPU")), Some(eframe::Renderer::Wgpu)); + } +} diff --git a/src/prefs.rs b/src/prefs.rs new file mode 100644 index 00000000..3efd831d --- /dev/null +++ b/src/prefs.rs @@ -0,0 +1,182 @@ +//! User preferences: appearance (fonts, UI scale), stage rendering, file dialogs. Stored as +//! JSON in the platform's settings folder (`platform::config_dir`). A missing or broken file +//! falls back to defaults; it never stops the app from starting. + +use serde::{Deserialize, Serialize}; + +/// Which typeface a text role uses. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum FontChoice { + /// The fonts AniCraft bundles (Inter / JetBrains Mono, or egui's defaults). + #[default] + Bundled, + /// A font family installed on this computer. + System(String), +} + +/// When the stage renders edits (ADR 0006). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum RenderMode { + /// Edits render immediately while frames are cheap, in the background when the scene is + /// heavy (with an outline preview of what you drag). + #[default] + Auto, + /// Always render edits immediately (lowest latency, may stutter on heavy scenes). + Immediate, + /// Always render in the background (UI never waits; picture can trail by a frame). + Background, +} + +impl RenderMode { + pub const ALL: [(RenderMode, &'static str, &'static str); 3] = [ + (RenderMode::Auto, "Auto", "Edits show immediately; heavy scenes render in the background with an outline preview."), + (RenderMode::Immediate, "Immediate", "Every edit renders before the next frame. Lowest latency; can stutter on very heavy scenes."), + (RenderMode::Background, "Background", "Always render off the UI thread. The window never waits; the picture can trail by a frame."), + ]; +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Prefs { + pub ui_font: FontChoice, + pub data_font: FontChoice, + /// Interface scale (1.0 = 100%). + pub ui_scale: f32, + pub render_mode: RenderMode, + /// Native open/save dialogs; off = a built-in path field (for Linux setups without an XDG + /// desktop portal). + pub native_dialogs: bool, + /// Extra space before frame 1 on the timeline, in points, on top of the room the playhead + /// needs (the playhead can't go there). Fixed on screen, whatever the zoom. + pub timeline_start_gap: f32, + /// Keyboard shortcuts the user changed: action id → its full list of keys (empty = + /// unbound). Actions not listed keep their defaults (`keymap`). + pub shortcuts: std::collections::BTreeMap>, +} + +impl Default for Prefs { + fn default() -> Self { + Prefs { + ui_font: FontChoice::Bundled, + data_font: FontChoice::Bundled, + ui_scale: 1.0, + render_mode: RenderMode::Auto, + native_dialogs: true, + timeline_start_gap: 0.0, + shortcuts: Default::default(), + } + } +} + +pub const SCALE_RANGE: std::ops::RangeInclusive = 0.75..=2.0; +pub const GAP_RANGE: std::ops::RangeInclusive = 0.0..=48.0; + +impl Prefs { + fn path() -> Option { + crate::platform::config_dir().map(|d| d.join("prefs.json")) + } + + pub fn sanitized(mut self) -> Prefs { + self.ui_scale = if self.ui_scale.is_finite() { self.ui_scale.clamp(*SCALE_RANGE.start(), *SCALE_RANGE.end()) } else { 1.0 }; + self.timeline_start_gap = if self.timeline_start_gap.is_finite() { self.timeline_start_gap.clamp(*GAP_RANGE.start(), *GAP_RANGE.end()) } else { 0.0 }; + for f in [&mut self.ui_font, &mut self.data_font] { + if let FontChoice::System(name) = f + && (name.trim().is_empty() || name.len() > 256) + { + *f = FontChoice::Bundled; + } + } + self.shortcuts = crate::keymap::sanitize(std::mem::take(&mut self.shortcuts)); + self + } + + pub fn from_json(text: &str) -> Prefs { + serde_json::from_str::(text).unwrap_or_default().sanitized() + } + + pub fn load() -> Prefs { + Self::path().and_then(|p| std::fs::read_to_string(p).ok()).map_or_else(Prefs::default, |t| Prefs::from_json(&t)) + } + + /// Writes atomically (temp file + rename). + pub fn save(&self) -> Result<(), String> { + let path = Self::path().ok_or("no settings folder on this system")?; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, json).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &path).map_err(|e| e.to_string()) + } +} + +// ----- system fonts ----------------------------------------------------------------------------- + +/// Font families installed on this computer (scanned once, off the UI thread). +pub struct SystemFonts { + db: fontdb::Database, + pub families: Vec, + pub monospace: Vec, +} + +impl SystemFonts { + /// Scans the OS font folders (Windows Fonts, macOS Library/Fonts, fontconfig dirs on Linux). + pub fn scan() -> SystemFonts { + let mut db = fontdb::Database::new(); + db.load_system_fonts(); + let mut families = std::collections::BTreeSet::new(); + let mut monospace = std::collections::BTreeSet::new(); + for face in db.faces() { + if let Some((name, _)) = face.families.first() { + if name.starts_with('.') { + continue; // hidden system UI faces on macOS + } + families.insert(name.clone()); + if face.monospaced { + monospace.insert(name.clone()); + } + } + } + SystemFonts { db, families: families.into_iter().collect(), monospace: monospace.into_iter().collect() } + } + + /// Bytes and face index of the regular style of `family`. + pub fn regular(&self, family: &str) -> Option<(Vec, u32)> { + let q = fontdb::Query { families: &[fontdb::Family::Name(family)], weight: fontdb::Weight::NORMAL, stretch: fontdb::Stretch::Normal, style: fontdb::Style::Normal }; + let id = self.db.query(&q)?; + self.db.with_face_data(id, |data, index| (data.to_vec(), index)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn system_font_scan_is_safe_and_loads_a_face() { + // Machine-dependent (CI containers may have no fonts); must never panic. + let fonts = SystemFonts::scan(); + eprintln!("{} families, {} monospace", fonts.families.len(), fonts.monospace.len()); + assert!(fonts.monospace.iter().all(|m| fonts.families.contains(m))); + if let Some(first) = fonts.families.first() { + assert!(fonts.regular(first).is_some_and(|(bytes, _)| !bytes.is_empty()), "{first}"); + } + assert!(fonts.regular("No Such Font Family 12345").is_none()); + } + + #[test] + fn broken_or_hostile_files_fall_back_to_defaults() { + assert_eq!(Prefs::from_json("not json"), Prefs::default()); + let p = Prefs::from_json(r#"{"ui_scale": 99, "ui_font": {"System": ""}, "unknown": 1}"#); + assert_eq!(p.ui_scale, 2.0); + assert_eq!(p.ui_font, FontChoice::Bundled); + let p = Prefs::from_json(r#"{"render_mode": "Background", "data_font": {"System": "Consolas"}}"#); + assert_eq!(p.render_mode, RenderMode::Background); + assert_eq!(p.data_font, FontChoice::System("Consolas".into())); + assert!(p.native_dialogs, "missing fields keep their defaults"); + let p = Prefs::from_json(r#"{"shortcuts": {"tool.pen": ["F9", "Ctrl+K"], "nope": ["F2"]}}"#); + assert_eq!(p.shortcuts.len(), 1); + assert_eq!(p.shortcuts.get("tool.pen"), Some(&vec!["F9".to_string()])); + } +} diff --git a/src/stage.rs b/src/stage.rs new file mode 100644 index 00000000..c064a1e9 --- /dev/null +++ b/src/stage.rs @@ -0,0 +1,895 @@ +//! The stage: tiled pictures from the render service, tool interaction and screen-space +//! overlays (ADR 0007). +//! +//! The stage is cut into `TILE`-pixel tiles on a device-pixel grid at the current zoom. Each +//! frame asks for the visible tiles as one batch (plus a one-tile margin as look-ahead), keeps +//! finished tiles as textures, and draws any older tiles that cover a gap (previous zoom or +//! state, scaled) underneath, so panning and zooming never reveal an empty stage. + +use crate::app::{App, Drag, Tool, XfKind}; +use crate::prefs::RenderMode; +use crate::theme::{T, to_color32}; +use anicraft_engine::geom::{Affine, Vec2}; +use anicraft_engine::render::View; +use anicraft_engine::render_service::{DEFAULT_CACHE_BYTES, FrameImage, FrameJob, RenderService, make_job}; +use egui::{Color32, CursorIcon, Key, Modifiers, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use serde_json::json; + +/// Frames rendered ahead of the playhead during playback. +const LOOKAHEAD: u32 = 12; +/// In Auto mode, edits render on the UI thread when the visible tiles last took at most this +/// long in total (keeps 60 fps interaction; heavier scenes fall back to the background worker). +const IMMEDIATE_BUDGET_MS: f32 = 12.0; +/// Tile edge in device pixels: big enough to keep per-tile overhead low, small enough that a +/// pan only needs a strip of new tiles. +pub const TILE: u32 = 512; +/// Tile textures kept on the GPU (≈ 1 MB each); least recently used ones are dropped. +const MAX_TILE_TEXTURES: usize = 192; + +/// A finished tile on the GPU. +struct TileTex { + key: u64, + /// Stage-space rectangle `[x0, y0, x1, y1]` this tile covers. + rect: [f32; 4], + tex: egui::TextureHandle, + used: u64, +} + +pub struct Cache { + tiles: Vec, + tick: u64, + /// Render time of the visible tiles the last time they were (re)rendered. + pub ms: f32, + /// `(ready, needed)` visible tiles this frame. + pub ready: (usize, usize), + pub canvas: Rect, + pub service: Option, + /// Document state of the picture on screen (an edit makes it differ). + pub shown_state: Option, +} + +impl Default for Cache { + fn default() -> Self { + Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), service: None, shown_state: None } + } +} + +impl Cache { + /// `(images, MB, hit %)` of the render cache, for the status bar. + pub fn stats(&self) -> Option<(usize, f32, f32)> { + self.service.as_ref().map(|s| { + let (n, bytes, hits, misses) = s.cache_stats(); + let total = (hits + misses).max(1); + (n, bytes as f32 / (1024.0 * 1024.0), hits as f32 * 100.0 / total as f32) + }) + } + + fn has(&mut self, key: u64) -> bool { + self.tick += 1; + let tick = self.tick; + match self.tiles.iter_mut().find(|t| t.key == key) { + Some(t) => { + t.used = tick; + true + } + None => false, + } + } + + fn upload(&mut self, ctx: &egui::Context, img: &FrameImage, rect: [f32; 4], keep: &[u64]) -> Option { + if let Some(e) = &img.error { + return Some(e.clone()); + } + if self.tiles.iter().any(|t| t.key == img.key) { + return None; + } + let image = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.rgba_premul); + self.tick += 1; + let tex = ctx.load_texture(format!("tile-{:x}", img.key), image, egui::TextureOptions::LINEAR); + self.tiles.push(TileTex { key: img.key, rect, tex, used: self.tick }); + // Evict least recently used tiles that are not on screen. + while self.tiles.len() > MAX_TILE_TEXTURES { + let victim = self.tiles.iter().enumerate().filter(|(_, t)| !keep.contains(&t.key)).min_by_key(|(_, t)| t.used).map(|(i, _)| i); + match victim { + Some(i) => { + self.tiles.swap_remove(i); + } + None => break, + } + } + None + } +} + +/// One tile of the stage at device scale `z`. +struct TileSpec { + rect: [f32; 4], + view: View, +} + +/// Tiles covering stage-device-pixel rect `[x0, x1) × [y0, y1)`, nearest to `centre` first. +fn tiles_for(z: f32, stage_px: (u32, u32), px: [f32; 4], margin: u32, bg: anicraft_engine::doc::Rgba) -> Vec { + let (sw, sh) = stage_px; + if sw == 0 || sh == 0 { + return Vec::new(); + } + let t = TILE as f32; + let last = (sw.div_ceil(TILE) - 1, sh.div_ceil(TILE) - 1); + let tx0 = ((px[0] / t).floor().max(0.0) as u32).saturating_sub(margin); + let ty0 = ((px[1] / t).floor().max(0.0) as u32).saturating_sub(margin); + let tx1 = (((px[2] - 1.0).max(0.0) / t).floor() as u32 + margin).min(last.0); + let ty1 = (((px[3] - 1.0).max(0.0) / t).floor() as u32 + margin).min(last.1); + let (cx, cy) = ((px[0] + px[2]) / 2.0, (px[1] + px[3]) / 2.0); + let mut out = Vec::new(); + for ty in ty0..=ty1 { + for tx in tx0..=tx1 { + let (ox, oy) = (tx * TILE, ty * TILE); + let (w, h) = (TILE.min(sw - ox), TILE.min(sh - oy)); + let view = View { transform: Affine::translate(-(ox as f32), -(oy as f32)).mul(&Affine::scale(z, z)), width: w, height: h, background: Some(bg) }; + let rect = [ox as f32 / z, oy as f32 / z, (ox + w) as f32 / z, (oy + h) as f32 / z]; + out.push(TileSpec { rect, view }); + } + } + let d = |s: &TileSpec| { + let (mx, my) = ((s.rect[0] + s.rect[2]) / 2.0 * z - cx, (s.rect[1] + s.rect[3]) / 2.0 * z - cy); + mx * mx + my * my + }; + out.sort_by(|a, b| d(a).total_cmp(&d(b))); + out +} + +fn to_v(p: Pos2) -> Vec2 { + Vec2::new(p.x, p.y) +} + +pub fn show(app: &mut App, ui: &mut egui::Ui) { + let canvas = ui.max_rect(); + app.stage_cache.canvas = canvas; + let resp = ui.allocate_rect(canvas, Sense::click_and_drag()); + let ppp = ui.ctx().pixels_per_point(); + let size = vec2(app.s.doc.stage.width as f32, app.s.doc.stage.height as f32); + if app.view.fit && canvas.width() > 10.0 { + app.view.zoom = ((canvas.width() - 64.0) / size.x).min((canvas.height() - 64.0) / size.y).clamp(0.05, 64.0); + app.view.pan = egui::Vec2::ZERO; + app.view.fit = false; + } + + // ---- camera input ------------------------------------------------------------------- + if resp.hovered() { + let (zoom_delta, scroll) = ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta)); + if let Some(p) = resp.hover_pos() { + if (zoom_delta - 1.0).abs() > 1e-4 { + let z = app.view.zoom * zoom_delta; + app.zoom_about(canvas, p, z); + } else if scroll != egui::Vec2::ZERO { + app.view.pan += scroll; + } + } + } + if !ui.ctx().egui_wants_keyboard_input() { + let (zin, zout, fit, one) = ui.input_mut(|i| { + ( + i.consume_key(Modifiers::COMMAND, Key::Equals) || i.consume_key(Modifiers::COMMAND, Key::Plus), + i.consume_key(Modifiers::COMMAND, Key::Minus), + i.consume_key(Modifiers::COMMAND, Key::Num0), + i.consume_key(Modifiers::COMMAND, Key::Num1), + ) + }); + let c = canvas.center(); + if zin { + let z = app.view.zoom * 1.5; + app.zoom_about(canvas, c, z); + } + if zout { + let z = app.view.zoom / 1.5; + app.zoom_about(canvas, c, z); + } + if fit { + app.view.fit = true; + } + if one { + app.zoom_about(canvas, c, 1.0); + } + } + + let zoom = app.view.zoom; + // Snap the stage origin to whole device pixels: tile edges then land exactly on screen + // pixels, so texture filtering can't show seams between tiles. + let raw = canvas.center() + app.view.pan - size * zoom * 0.5; + let origin = pos2((raw.x * ppp).round() / ppp, (raw.y * ppp).round() / ppp); + let to_screen = |p: Vec2| pos2(origin.x + p.x * zoom, origin.y + p.y * zoom); + let to_stage = |p: Pos2| pos2((p.x - origin.x) / zoom, (p.y - origin.y) / zoom); + let stage_rect = Rect::from_min_size(origin, size * zoom); + let painter = ui.painter_at(canvas); + + + // ---- tools ---------------------------------------------------------------------------- + let (shift, alt, space) = ui.input(|i| (i.modifiers.shift, i.modifiers.alt, i.key_down(Key::Space))); + let pointer = resp.hover_pos().or_else(|| resp.interact_pointer_pos()); + app.cursor_stage = pointer.filter(|p| canvas.contains(*p)).map(to_stage); + let panning = app.tool == Tool::Hand || space || resp.dragged_by(egui::PointerButton::Middle); + // Selection box in screen space (free transform handles live on it). + let sel_bounds = bounds_arr(app.s.selection_bounds()); + let sel_rect = sel_bounds.map(|b| Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3])))); + + if resp.hovered() { + let icon = match app.tool { + _ if panning => CursorIcon::Grab, + Tool::Transform => { + let zone = match app.drag { + Drag::Transform { kind, .. } => Some(kind), + _ => sel_rect.zip(pointer).and_then(|(r, p)| xf_zone(r, p)), + }; + match zone { + Some(XfKind::Scale { hx, hy }) if hx * hy > 0 => CursorIcon::ResizeNwSe, + Some(XfKind::Scale { hx, hy }) if hx * hy < 0 => CursorIcon::ResizeNeSw, + Some(XfKind::Scale { hx: 0, .. }) => CursorIcon::ResizeVertical, + Some(XfKind::Scale { .. }) => CursorIcon::ResizeHorizontal, + Some(XfKind::Rotate) => CursorIcon::Alias, + Some(XfKind::Move) => CursorIcon::Move, + None => CursorIcon::Default, + } + } + Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::PaintBucket | Tool::InkBottle => CursorIcon::Crosshair, + Tool::Zoom => { + if alt { + CursorIcon::ZoomOut + } else { + CursorIcon::ZoomIn + } + } + _ => CursorIcon::Default, + }; + ui.ctx().set_cursor_icon(icon); + } + + let xf = crate::pathtools::Xf { origin, zoom }; + if resp.clicked() || resp.drag_started() || resp.secondary_clicked() { + // Ctrl+X/C/V go back to artwork. + app.timeline_focus = false; + } + if app.tool == Tool::Pen && !panning { + crate::pathtools::pen_input(app, ui, &resp, xf); + } + + if resp.drag_started() { + let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(canvas.center()); + let sp = to_stage(press); + app.drag = if panning { + Drag::Pan + } else { + match app.tool { + Tool::Select => match app.s.hit_test(to_v(sp), 3.0 / zoom) { + Some((_, el)) => { + if !app.s.selection.contains(&el) { + app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); + } + app.s.begin_gesture("Move"); + Drag::Move { last: sp } + } + None => Drag::Marquee { start: sp, cur: sp }, + }, + Tool::Transform => { + let zone = sel_rect.and_then(|r| xf_zone(r, press)); + match (zone, sel_bounds) { + (Some(kind), Some(bounds)) => { + app.s.begin_gesture("Free Transform"); + Drag::Transform { kind, start: sp, bounds, applied: Affine::IDENTITY } + } + // Not on the box: grab whatever is under the pointer and move it. + _ => match app.s.hit_test(to_v(sp), 3.0 / zoom) { + Some(_) => { + app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); + match bounds_arr(app.s.selection_bounds()) { + Some(bounds) => { + app.s.begin_gesture("Free Transform"); + Drag::Transform { kind: XfKind::Move, start: sp, bounds, applied: Affine::IDENTITY } + } + None => Drag::None, + } + } + None => Drag::Marquee { start: sp, cur: sp }, + }, + } + } + Tool::Subselect => crate::pathtools::subselect_drag_start(app, press, shift, xf), + Tool::Pencil => { + app.pencil = vec![to_v(sp)]; + Drag::Pencil + } + Tool::Pen | Tool::PaintBucket | Tool::InkBottle => Drag::None, + Tool::Rect | Tool::Oval | Tool::Star | Tool::Line => Drag::Shape { start: sp, cur: sp }, + Tool::Hand => Drag::Pan, + Tool::Zoom => Drag::None, + } + }; + } + + if resp.dragged() { + let cur = resp.interact_pointer_pos().map(to_stage); + match (&mut app.drag, cur) { + (Drag::Pan, _) => app.view.pan += resp.drag_delta(), + (Drag::Move { last }, Some(c)) => { + let d = c - *last; + if d.length_sq() > 0.0 { + *last = c; + app.run("element.translate", json!({"dx": d.x, "dy": d.y})); + } + } + (Drag::Transform { kind, start, bounds, applied }, Some(c)) => { + let total = xf_total(*kind, *bounds, *start, c, shift, alt); + // Send only the change since the last frame; the gesture makes it one undo step. + if let Some(inv) = applied.inverse() { + let delta = total.mul(&inv); + if delta.m.iter().zip(Affine::IDENTITY.m).any(|(a, b)| (a - b).abs() > 1e-6) { + let [a, b, cc, d, e, f] = delta.m; + let ok = app.s.execute("modify.transform", &json!({"a": a, "b": b, "c": cc, "d": d, "e": e, "f": f})).is_ok(); + if ok { + *applied = total; + } + } + } + } + (Drag::Points { last }, Some(c)) => { + let d = c - *last; + if d.length_sq() > 0.0 { + *last = c; + crate::pathtools::move_points(app, Vec2::new(d.x, d.y)); + } + } + (Drag::PointMarquee { cur: m, .. }, Some(c)) => *m = c, + (Drag::Pencil, Some(c)) => crate::pathtools::pencil_sample(app, to_v(c), xf), + (Drag::Marquee { cur: m, .. }, Some(c)) => *m = c, + (Drag::Shape { start, cur: m }, Some(c)) => *m = constrain(app.tool, *start, c, shift), + _ => {} + } + } + + if resp.drag_stopped() { + match app.drag { + Drag::Move { .. } | Drag::Transform { .. } | Drag::Points { .. } => app.s.end_gesture(), + Drag::PointMarquee { start, cur } => crate::pathtools::marquee_points(app, start, cur, shift), + Drag::Pencil => crate::pathtools::commit_pencil(app, xf), + Drag::Marquee { start, cur } => { + let r = Rect::from_two_pos(start, cur); + let ids: Vec = app + .s + .visible_elements() + .iter() + .filter(|e| { + let b = app.s.element_bounds(e.id); + !b.is_empty() && r.intersects(Rect::from_min_max(pos2(b.min.x, b.min.y), pos2(b.max.x, b.max.y))) + }) + .map(|e| e.id.0) + .collect(); + let locked = app.s.active_layer().is_some_and(|l| l.locked); + if !locked { + app.run("element.select", json!({"ids": ids, "add": shift})); + } + } + Drag::Shape { start, cur } => create_shape(app, start, cur), + Drag::Pan | Drag::None => {} + } + app.drag = Drag::None; + } + + if resp.clicked() + && let Some(p) = resp.interact_pointer_pos() { + let sp = to_stage(p); + match app.tool { + Tool::Subselect if !panning => crate::pathtools::subselect_click(app, p, shift, xf), + Tool::PaintBucket if !panning => { + // The gap size is set in screen points, so it feels the same at any zoom. + let gap = app.bucket_gap.screen_px() / zoom.max(1e-3); + if let Some(v) = app.run("paint.bucket", json!({"x": sp.x, "y": sp.y, "gap": gap})) { + app.status_ok(if v.get("recolored").is_some() { "Recoloured the fill. Ctrl+Z to undo." } else { "Filled the area. Ctrl+Z to undo." }); + } + } + Tool::InkBottle if !panning => { + app.run("paint.ink", json!({"x": sp.x, "y": sp.y, "slop": 4.0 / zoom.max(1e-3)})); + } + Tool::Select | Tool::Transform if !panning => { + app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); + } + Tool::Zoom => { + let z = if alt { app.view.zoom / 2.0 } else { app.view.zoom * 2.0 }; + app.zoom_about(canvas, p, z); + } + _ => {} + } + } + + // Right-click: select what is under the cursor (keeping an existing multi-selection), then + // offer the actions that apply to it. + if resp.secondary_clicked() + && let Some(p) = resp.interact_pointer_pos() + { + let sp = to_stage(p); + let under = app.s.hit_test(to_v(sp), 3.0 / zoom).map(|(_, e)| e); + if under.is_none_or(|e| !app.s.selection.contains(&e)) { + app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": false})); + } + } + if app.tool == Tool::Subselect + && resp.double_clicked() + && let Some(p) = resp.interact_pointer_pos() + { + crate::pathtools::subselect_double_click(app, p, xf); + } + + resp.context_menu(|ui| { + ui.set_min_width(220.0); + if crate::pathtools::point_menu(app, ui) { + return; + } + if app.s.selection.is_empty() { + for id in ["edit.paste", "edit.paste_in_place", "edit.select_all", "timeline.insert_keyframe", "timeline.insert_blank_keyframe"] { + crate::menus::cmd_item(app, ui, id); + } + ui.separator(); + for id in ["edit.undo", "edit.redo"] { + crate::menus::cmd_item(app, ui, id); + } + } else { + for id in ["edit.cut", "edit.copy", "edit.paste", "edit.duplicate", "edit.delete"] { + crate::menus::cmd_item(app, ui, id); + } + ui.separator(); + ui.menu_button("Transform", |ui| { + for id in ["modify.rotate_cw", "modify.rotate_ccw", "modify.flip_h", "modify.flip_v"] { + crate::menus::cmd_item(app, ui, id); + } + }); + ui.menu_button("Align", |ui| { + for id in ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom", "align.distribute_h", "align.distribute_v"] { + crate::menus::cmd_item(app, ui, id); + } + }); + ui.separator(); + for id in ["modify.convert_to_symbol", "modify.break_apart"] { + crate::menus::cmd_item(app, ui, id); + } + ui.menu_button("Arrange", |ui| { + for id in ["arrange.bring_to_front", "arrange.send_to_back"] { + crate::menus::cmd_item(app, ui, id); + } + }); + ui.separator(); + for id in ["timeline.insert_keyframe", "timeline.create_tween", "edit.deselect"] { + crate::menus::cmd_item(app, ui, id); + } + } + }); + + // ---- render the frame ----------------------------------------------------------------- + painter.rect_filled(stage_rect.translate(vec2(3.0, 4.0)), 0.0, T.stage_shadow); + // Stage colour first, so a picture still rendering never shows as a hole. + painter.rect_filled(stage_rect, 0.0, crate::theme::to_color32(app.s.doc.stage.background)); + let vis = stage_rect.intersect(canvas); + if vis.width() >= 1.0 && vis.height() >= 1.0 { + if app.stage_cache.service.is_none() { + let ctx = ui.ctx().clone(); + app.stage_cache.service = Some(RenderService::new(DEFAULT_CACHE_BYTES, Some(Box::new(move || ctx.request_repaint())))); + } + // Tiles on a device-pixel grid at this zoom (ADR 0007). + let z = zoom * ppp; + let bg = app.s.doc.stage.background; + let stage_px = ((size.x * z).ceil().max(1.0) as u32, (size.y * z).ceil().max(1.0) as u32); + let px = [(vis.min.x - origin.x) * ppp, (vis.min.y - origin.y) * ppp, (vis.max.x - origin.x) * ppp, (vis.max.y - origin.y) * ppp]; + let visible = tiles_for(z, stage_px, px, 0, bg); + let onion = app.onion && !app.playing; + let state = app.s.state; + let frame = app.s.frame; + let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job(state, &app.s.doc, frame, t.view, onion); (t, j) }).collect(); + let keys: Vec = jobs.iter().map(|(_, j)| j.key).collect(); + let missing: Vec = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect(); + + if !missing.is_empty() + && let Some(svc) = &app.stage_cache.service + { + // Latency vs throughput (ADR 0006): an edit (the document changed under the picture + // on screen) renders the missing visible tiles right here, in one parallel batch, + // when they were cheap last time. Pans, zooms, playback and heavy scenes go to the + // background worker as one batch; older tiles cover the gap meanwhile. + // The very first picture has nothing older to stand in for it, so it counts too. + let edited = app.stage_cache.shown_state != Some(state); + let immediate = !app.playing + && edited + && match app.prefs.render_mode { + RenderMode::Immediate => true, + RenderMode::Background => false, + RenderMode::Auto => app.stage_cache.ms <= IMMEDIATE_BUDGET_MS, + }; + let batch: Vec = missing.iter().map(|&i| jobs[i].1.clone()).collect(); + let started = std::time::Instant::now(); + let results: Vec>> = if immediate { svc.render_now_batch(batch).into_iter().map(Some).collect() } else { svc.request_batch(batch) }; + let wall = started.elapsed().as_secs_f32() * 1000.0; + let mut ms = 0.0f32; + let mut error = None; + for (&i, img) in missing.iter().zip(results) { + if let Some(img) = img { + ms += img.ms; + if let Some(e) = app.stage_cache.upload(ui.ctx(), &img, jobs[i].0.rect, &keys) { + error = Some(e); + } + } + } + if ms > 0.0 { + // Wall-clock cost of showing the whole view (tiles render in parallel, so the + // sum of per-tile times would overstate it). Measured directly when rendered + // here; estimated from per-tile times and core count when they came from the + // worker. + let cores = std::thread::available_parallelism().map_or(1, |n| n.get()) as f32; + let tiles = missing.len().max(1) as f32; + let batch_ms = if immediate { wall } else { ms / cores.min(tiles) }; + app.stage_cache.ms = batch_ms * keys.len() as f32 / tiles; + } + if let Some(e) = error { + app.status_err(e); + } + } + let ready = keys.iter().filter(|k| app.stage_cache.tiles.iter().any(|t| t.key == **k)).count(); + app.stage_cache.ready = (ready, keys.len()); + if ready == keys.len() { + app.stage_cache.shown_state = Some(state); + } + + // Look-ahead: the ring of tiles around the view (a pan reveals them instantly) and, + // during playback, the next frames' visible tiles. + if let Some(svc) = &app.stage_cache.service { + let mut ahead: Vec = Vec::new(); + if app.playing { + let n = app.s.frame_count().max(1); + for d in 1..=LOOKAHEAD.min(n - 1) { + let f = (frame + d) % n; + ahead.extend(jobs.iter().map(|(t, _)| make_job(state, &app.s.doc, f, t.view, false))); + } + } else { + ahead.extend(tiles_for(z, stage_px, px, 1, bg).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job(state, &app.s.doc, frame, t.view, onion))); + } + svc.prefetch(ahead); + } + + // Draw: tiles from earlier zooms/states that cover the view go first (scaled, as a + // placeholder), then the current tiles on top. + let view_rect = [(vis.min.x - origin.x) / zoom, (vis.min.y - origin.y) / zoom, (vis.max.x - origin.x) / zoom, (vis.max.y - origin.y) / zoom]; + let overlaps = |r: &[f32; 4]| r[0] < view_rect[2] && r[2] > view_rect[0] && r[1] < view_rect[3] && r[3] > view_rect[1]; + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + let mut stale: Vec<&TileTex> = app.stage_cache.tiles.iter().filter(|t| !keys.contains(&t.key) && overlaps(&t.rect)).collect(); + if ready < keys.len() { + stale.sort_by_key(|t| t.used); + for t in stale.iter().rev().take(96).rev() { + let r = Rect::from_min_max(to_screen(Vec2::new(t.rect[0], t.rect[1])), to_screen(Vec2::new(t.rect[2], t.rect[3]))); + painter.image(t.tex.id(), r, uv, Color32::WHITE); + } + } + for t in app.stage_cache.tiles.iter().filter(|t| keys.contains(&t.key)) { + let r = Rect::from_min_max(to_screen(Vec2::new(t.rect[0], t.rect[1])), to_screen(Vec2::new(t.rect[2], t.rect[3]))); + painter.image(t.tex.id(), r, uv, Color32::WHITE); + } + + // While a background render catches up with a drag, outline where the selection is now, + // so the artwork never seems to lag the pointer. + if ready < keys.len() && matches!(app.drag, Drag::Move { .. } | Drag::Transform { .. }) { + let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); + let dl = app.s.display_list(); + let stroke = Stroke::new(1.5, T.selection); + for item in dl.items.iter().filter(|i| app.s.selection.contains(&i.element)).take(2_000) { + for pl in item.path.flatten(&to_px.mul(&item.transform), 0.5) { + let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); + painter.add(if pl.closed { egui::Shape::closed_line(pts, stroke) } else { egui::Shape::line(pts, stroke) }); + } + } + } + } + painter.rect_stroke(stage_rect, 0.0, Stroke::new(1.0, Color32::from_black_alpha(160)), StrokeKind::Outside); + + // ---- overlays ------------------------------------------------------------------------- + // Mask artwork is never painted; while its layer is unlocked (editable), its edge shows in + // the layer colour so it can be seen, picked and reshaped. Locking the mask hides the edge. + { + let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); + let dl = app.s.display_list(); + for item in dl.items.iter().filter(|i| i.masks.is_some()).take(2_000) { + let Some(layer) = app.s.doc.timeline.layer(item.layer).filter(|l| !l.locked) else { continue }; + let stroke = Stroke::new(1.5, to_color32(layer.color)); + for pl in item.path.flatten(&to_px.mul(&item.transform), 0.5) { + let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); + painter.add(if pl.closed { egui::Shape::closed_line(pts, stroke) } else { egui::Shape::line(pts, stroke) }); + } + } + } + let sel_stroke = Stroke::new(1.0, T.selection); + if app.tool == Tool::Select && app.drag == Drag::None + && app.palette.is_none() + && !app.modal_open() + && let Some(sp) = app.cursor_stage + && let Some((_, el)) = app.s.hit_test(to_v(sp), 3.0 / zoom) + && !app.s.selection.contains(&el) { + let b = app.s.element_bounds(el); + if !b.is_empty() { + let r = Rect::from_min_max(to_screen(b.min), to_screen(b.max)); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.55)), StrokeKind::Middle); + } + } + let transforming = app.tool == Tool::Transform; + for id in app.s.selection.clone() { + let b = app.s.element_bounds(id); + if b.is_empty() { + continue; + } + let r = Rect::from_min_max(to_screen(b.min), to_screen(b.max)).expand(1.0); + if app.tool == Tool::Subselect { + // Subselection shows outlines and points instead (below). + continue; + } + if transforming { + // Free transform shows one box for the whole selection (below); members get a hint. + painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.45)), StrokeKind::Middle); + continue; + } + painter.rect_stroke(r, 0.0, sel_stroke, StrokeKind::Middle); + for c in [r.left_top(), r.right_top(), r.left_bottom(), r.right_bottom(), r.center_top(), r.center_bottom(), r.left_center(), r.right_center()] { + let h = Rect::from_center_size(c, vec2(6.0, 6.0)); + painter.rect_filled(h, 0.0, Color32::WHITE); + painter.rect_stroke(h, 0.0, sel_stroke, StrokeKind::Middle); + } + // registration point + if let Some(e) = app.s.visible_elements().iter().find(|e| e.id == id) { + let o = to_screen(e.transform.translation()); + painter.circle(o, 3.5, Color32::WHITE, Stroke::new(1.0, Color32::BLACK)); + } + } + // Free transform box: recomputed every frame so it follows the artwork while you drag. + if transforming && let Some(b) = bounds_arr(app.s.selection_bounds()) { + let r = Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3]))).expand(1.0); + painter.rect_stroke(r, 0.0, Stroke::new(1.5, T.selection), StrokeKind::Middle); + for (h, _, _) in handles(r) { + let hr = Rect::from_center_size(h, vec2(HANDLE, HANDLE)); + painter.rect_filled(hr, 0.0, Color32::WHITE); + painter.rect_stroke(hr, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle); + } + // transformation point (centre) + let c = r.center(); + painter.circle(c, 4.0, Color32::WHITE, Stroke::new(1.0, T.selection)); + painter.line_segment([c - vec2(6.0, 0.0), c + vec2(6.0, 0.0)], Stroke::new(1.0, T.selection)); + painter.line_segment([c - vec2(0.0, 6.0), c + vec2(0.0, 6.0)], Stroke::new(1.0, T.selection)); + } + crate::pathtools::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p))); + match app.drag { + Drag::Marquee { start, cur } => { + let r = Rect::from_two_pos(to_screen(Vec2::new(start.x, start.y)), to_screen(Vec2::new(cur.x, cur.y))); + painter.rect_filled(r, 0.0, T.selection.gamma_multiply(0.12)); + painter.rect_stroke(r, 0.0, sel_stroke, StrokeKind::Middle); + } + Drag::PointMarquee { start, cur } => { + let r = Rect::from_two_pos(to_screen(Vec2::new(start.x, start.y)), to_screen(Vec2::new(cur.x, cur.y))); + painter.rect_stroke(r, 0.0, sel_stroke, StrokeKind::Middle); + } + Drag::Shape { start, cur } => draw_preview(app, &painter, to_screen(Vec2::new(start.x, start.y)), to_screen(Vec2::new(cur.x, cur.y)), zoom), + _ => {} + } + + // zoom badge + let badge = format!("{:.0}%", zoom * 100.0); + painter.text(canvas.right_bottom() + vec2(-10.0, -8.0), egui::Align2::RIGHT_BOTTOM, badge, crate::theme::font(crate::theme::Type::Data), T.text_dim); +} + +// ----- free transform --------------------------------------------------------------------------- + +/// Screen-space handle size and the rotation zone just outside each corner. +const HANDLE: f32 = 8.0; +const ROTATE_ZONE: f32 = 22.0; + +fn bounds_arr(b: anicraft_engine::geom::Rect) -> Option<[f32; 4]> { + (!b.is_empty()).then_some([b.min.x, b.min.y, b.max.x, b.max.y]) +} + +/// Handle centres in screen space with their (hx, hy) codes. +fn handles(r: Rect) -> [(Pos2, i8, i8); 8] { + let p = |hx: i8, hy: i8| pos2(r.left() + r.width() * (f32::from(hx) + 1.0) / 2.0, r.top() + r.height() * (f32::from(hy) + 1.0) / 2.0); + [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)].map(|(x, y)| (p(x, y), x, y)) +} + +/// What dragging from screen point `p` would do to a selection drawn as `r`. +fn xf_zone(r: Rect, p: Pos2) -> Option { + for (h, hx, hy) in handles(r) { + if (p.x - h.x).abs() <= HANDLE && (p.y - h.y).abs() <= HANDLE { + return Some(XfKind::Scale { hx, hy }); + } + } + if !r.contains(p) && [r.left_top(), r.right_top(), r.left_bottom(), r.right_bottom()].iter().any(|c| c.distance(p) <= ROTATE_ZONE) { + return Some(XfKind::Rotate); + } + r.expand(2.0).contains(p).then_some(XfKind::Move) +} + +/// The whole transform of a free-transform drag from `start` to `cur` (stage space). +pub(crate) fn xf_total(kind: XfKind, b: [f32; 4], start: Pos2, cur: Pos2, shift: bool, alt: bool) -> Affine { + let [x0, y0, x1, y1] = b; + let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + let about = |px: f32, py: f32, m: Affine| Affine::translate(px, py).mul(&m).mul(&Affine::translate(-px, -py)); + match kind { + XfKind::Move => { + let mut d = cur - start; + if shift { + // constrain to the dominant axis + if d.x.abs() > d.y.abs() { + d.y = 0.0; + } else { + d.x = 0.0; + } + } + Affine::translate(d.x, d.y) + } + XfKind::Scale { hx, hy } => { + let px = if alt { cx } else { [x1, cx, x0][(hx + 1) as usize] }; + let py = if alt { cy } else { [y1, cy, y0][(hy + 1) as usize] }; + let factor = |s: f32, c: f32, p: f32| { + let den = s - p; + if den.abs() < 1e-3 { 1.0 } else { (c - p) / den } + }; + let mut sx = if hx != 0 { factor(start.x, cur.x, px) } else { 1.0 }; + let mut sy = if hy != 0 { factor(start.y, cur.y, py) } else { 1.0 }; + if shift { + if hx != 0 && hy != 0 { + let m = sx.abs().max(sy.abs()); + sx = m.copysign(sx); + sy = m.copysign(sy); + } else if hx != 0 { + sy = sx.abs(); + } else { + sx = sy.abs(); + } + } + let clamp = |s: f32| if s.abs() < 0.01 { 0.01f32.copysign(if s == 0.0 { 1.0 } else { s }) } else { s }; + about(px, py, Affine::scale(clamp(sx), clamp(sy))) + } + XfKind::Rotate => { + let a0 = (start.y - cy).atan2(start.x - cx); + let a1 = (cur.y - cy).atan2(cur.x - cx); + let mut a = a1 - a0; + if shift { + let step = 15f32.to_radians(); + a = (a / step).round() * step; + } + about(cx, cy, Affine::rotate(a)) + } + } +} + +fn constrain(tool: Tool, start: Pos2, cur: Pos2, shift: bool) -> Pos2 { + if !shift { + return cur; + } + let d = cur - start; + match tool { + Tool::Line => { + let ang = d.y.atan2(d.x); + let snap = (ang / std::f32::consts::FRAC_PI_4).round() * std::f32::consts::FRAC_PI_4; + let len = d.length(); + start + vec2(snap.cos(), snap.sin()) * len + } + _ => { + let m = d.x.abs().max(d.y.abs()); + start + vec2(m * d.x.signum(), m * d.y.signum()) + } + } +} + +fn create_shape(app: &mut App, start: Pos2, cur: Pos2) { + let d = cur - start; + if d.length() < 1.0 { + return; + } + match app.tool { + Tool::Rect => { + app.run("draw.rect", json!({"x": start.x, "y": start.y, "w": d.x, "h": d.y, "radius": app.rect_radius})); + } + Tool::Oval => { + app.run("draw.ellipse", json!({"x": start.x, "y": start.y, "w": d.x, "h": d.y})); + } + Tool::Star => { + let r = d.length(); + app.run("draw.star", json!({"cx": start.x, "cy": start.y, "outer": r, "inner": r * 0.45, "points": app.star_points})); + } + Tool::Line => { + app.run("draw.line", json!({"x0": start.x, "y0": start.y, "x1": cur.x, "y1": cur.y})); + } + _ => {} + } +} + +fn draw_preview(app: &App, painter: &egui::Painter, a: Pos2, b: Pos2, zoom: f32) { + let st = app.s.style; + let fill = if st.use_fill { crate::theme::to_color32(st.fill).gamma_multiply(0.6) } else { Color32::TRANSPARENT }; + let stroke = Stroke::new((st.stroke_width * zoom).max(1.0), if st.use_stroke { crate::theme::to_color32(st.stroke) } else { T.selection }); + match app.tool { + Tool::Rect => { + let r = Rect::from_two_pos(a, b); + let rad = (app.rect_radius * zoom).min(r.width() / 2.0).min(r.height() / 2.0).clamp(0.0, 255.0) as u8; + painter.rect_filled(r, rad, fill); + painter.rect_stroke(r, rad, stroke, StrokeKind::Middle); + } + Tool::Oval => { + let r = Rect::from_two_pos(a, b); + let pts: Vec = (0..64) + .map(|i| { + let t = i as f32 / 64.0 * std::f32::consts::TAU; + r.center() + vec2(r.width() / 2.0 * t.cos(), r.height() / 2.0 * t.sin()) + }) + .collect(); + painter.add(egui::Shape::convex_polygon(pts, fill, stroke)); + } + Tool::Star => { + let rr = (b - a).length(); + let n = app.star_points.clamp(3, 64) as usize; + let pts: Vec = (0..n * 2) + .map(|i| { + let r = if i % 2 == 0 { rr } else { rr * 0.45 }; + let t = -std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::PI / n as f32; + a + vec2(r * t.cos(), r * t.sin()) + }) + .collect(); + painter.add(egui::Shape::closed_line(pts, stroke)); + } + Tool::Line => { + painter.line_segment([a, b], stroke); + } + _ => {} + } +} + +#[cfg(test)] +mod xf_tests { + use super::*; + + const B: [f32; 4] = [0.0, 0.0, 100.0, 50.0]; + + fn apply(m: &Affine, x: f32, y: f32) -> Vec2 { + m.apply(Vec2::new(x, y)) + } + + #[test] + fn corner_scale_keeps_the_opposite_corner_fixed() { + let m = xf_total(XfKind::Scale { hx: 1, hy: 1 }, B, pos2(100.0, 50.0), pos2(200.0, 100.0), false, false); + assert_eq!(apply(&m, 0.0, 0.0), Vec2::new(0.0, 0.0)); + assert_eq!(apply(&m, 100.0, 50.0), Vec2::new(200.0, 100.0)); + } + + #[test] + fn shift_keeps_proportions_and_alt_scales_from_centre() { + let m = xf_total(XfKind::Scale { hx: 1, hy: 1 }, B, pos2(100.0, 50.0), pos2(300.0, 60.0), true, false); + let p = apply(&m, 100.0, 50.0); + assert!((p.x / 100.0 - p.y / 50.0).abs() < 1e-4, "{p:?}"); + let m = xf_total(XfKind::Scale { hx: 1, hy: 0 }, B, pos2(100.0, 25.0), pos2(150.0, 25.0), false, true); + assert_eq!(apply(&m, 50.0, 25.0), Vec2::new(50.0, 25.0), "centre stays put"); + assert_eq!(apply(&m, 100.0, 0.0).x, 150.0); + } + + #[test] + fn edge_scale_only_changes_one_axis_and_never_collapses() { + let m = xf_total(XfKind::Scale { hx: 0, hy: 1 }, B, pos2(50.0, 50.0), pos2(50.0, 0.0), false, false); + assert!(m.determinant().abs() > 0.0, "clamped above zero"); + assert_eq!(m.m[0], 1.0); + } + + #[test] + fn rotate_snaps_with_shift_and_keeps_centre() { + let m = xf_total(XfKind::Rotate, B, pos2(110.0, 25.0), pos2(50.0, 100.0), true, false); + let c = apply(&m, 50.0, 25.0); + assert!(c.distance(Vec2::new(50.0, 25.0)) < 1e-3); + let angle = m.decompose().rotation.to_degrees(); + assert!((angle / 15.0 - (angle / 15.0).round()).abs() < 1e-3, "{angle}"); + } + + #[test] + fn zones() { + let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); + assert_eq!(xf_zone(r, pos2(300.0, 200.0)), Some(XfKind::Scale { hx: 1, hy: 1 })); + assert_eq!(xf_zone(r, pos2(200.0, 100.0)), Some(XfKind::Scale { hx: 0, hy: -1 })); + assert_eq!(xf_zone(r, pos2(312.0, 212.0)), Some(XfKind::Rotate)); + assert_eq!(xf_zone(r, pos2(200.0, 150.0)), Some(XfKind::Move)); + assert_eq!(xf_zone(r, pos2(500.0, 500.0)), None); + } +} diff --git a/src/theme.rs b/src/theme.rs new file mode 100644 index 00000000..ef25c4b8 --- /dev/null +++ b/src/theme.rs @@ -0,0 +1,448 @@ +//! Design tokens. Every colour, radius and target size in the shell comes from here +//! (docs/ui-guidelines.md). +//! +//! The look (ADR 0008): graphite neutrals, geometric controls, borders only where they separate +//! layout regions, flat buttons, and vibrant colour spent where it carries meaning (timeline +//! blocks, playhead, selection). Corners follow the role of a shape, not one global value: +//! structure is square, controls are softened slightly, floating surfaces are rounder. + +use egui::{Color32, CornerRadius, Shadow, Stroke, Visuals}; + +#[derive(Clone, Copy)] +pub struct Tokens { + /// Menu bar, status bar: the frame around the work. + pub chrome: Color32, + pub panel: Color32, + /// Panel headers, alternate rows, windows. + pub panel_alt: Color32, + /// Raised surfaces: buttons at rest. + pub header: Color32, + /// Buttons under the pointer. + pub hover: Color32, + /// The active tool or a toggle that is on: a lighter gray block, the icon white. + pub active: Color32, + /// Icons at rest: a step down from white so the active one stands out. + pub icon: Color32, + /// Inset surfaces: text and number fields. + pub field: Color32, + /// Lines between layout regions and around popups. + pub border: Color32, + /// Edges of checkboxes and radio buttons (≥ 3:1 so the unticked state is visible). + pub control_edge: Color32, + /// Fine grid lines inside a region (timeline cells, row rules). + pub separator: Color32, + pub text: Color32, + pub text_dim: Color32, + pub text_faint: Color32, + /// Selection, focus, active tool. + pub accent: Color32, + pub accent_dim: Color32, + /// Dark marks drawn on vibrant blocks (keyframe dots, tween arrows, labels). + pub ink: Color32, + pub pasteboard: Color32, + pub stage_shadow: Color32, + /// Timeline: span holding artwork. + pub span: Color32, + /// Timeline: empty span. + pub span_empty: Color32, + /// Timeline: frame cells of the active layer. + pub row_active: Color32, + pub tween: Color32, + pub tween_line: Color32, + pub playhead: Color32, + pub selection: Color32, + /// Destructive buttons. + pub danger: Color32, + pub error: Color32, + pub ok: Color32, + /// Library symbol kinds. + pub kind_graphic: Color32, + pub kind_movie_clip: Color32, + pub kind_button: Color32, + /// Corner radii by role (see `Shape` below). + pub radius_control: u8, + pub radius_menu: u8, + pub radius_window: u8, +} + +/// Corner shapes are chosen by what a surface *is*: +/// +/// * **Structure is square** (`0.0`): panels, section bands, the timeline grid and its blocks, +/// selections, the stage. They tile against each other; rounding would leave gaps. +/// * **Controls are softened** (`radius_control`): buttons, fields, tools, list highlights, +/// swatches, the playhead flag. Rectangular and geometric, but not sharp. +/// * **Floating surfaces are rounder** (`radius_menu`, `radius_window`): menus, tooltips, +/// dialogs and windows sit above the work, and their shape says so. +/// * **Round only where the thing is round**: keyframe dots, dials, onion-skin marks. +pub const SQUARE: f32 = 0.0; + +pub const T: Tokens = Tokens { + chrome: Color32::from_rgb(0x13, 0x13, 0x16), + panel: Color32::from_rgb(0x1b, 0x1b, 0x1f), + panel_alt: Color32::from_rgb(0x22, 0x22, 0x27), + header: Color32::from_rgb(0x2c, 0x2c, 0x32), + hover: Color32::from_rgb(0x3a, 0x3a, 0x42), + active: Color32::from_rgb(0x4a, 0x4a, 0x53), + icon: Color32::from_rgb(0xb4, 0xb4, 0xbc), + field: Color32::from_rgb(0x0e, 0x0e, 0x11), + border: Color32::from_rgb(0x36, 0x36, 0x3e), + control_edge: Color32::from_rgb(0x78, 0x78, 0x82), + separator: Color32::from_rgb(0x26, 0x26, 0x2c), + text: Color32::from_rgb(0xee, 0xee, 0xf0), + text_dim: Color32::from_rgb(0xb0, 0xb0, 0xb8), + // ≥ 4.5:1 on `panel`, so even hints stay readable. + text_faint: Color32::from_rgb(0x8e, 0x8e, 0x98), + accent: Color32::from_rgb(0x2e, 0x66, 0xf0), + accent_dim: Color32::from_rgb(0x1f, 0x35, 0x70), + ink: Color32::from_rgb(0x0e, 0x0e, 0x10), + pasteboard: Color32::from_rgb(0x2a, 0x2a, 0x30), + stage_shadow: Color32::from_black_alpha(150), + span: Color32::from_rgb(0x22, 0xc7, 0xa9), + span_empty: Color32::from_rgb(0x2e, 0x2e, 0x35), + row_active: Color32::from_rgb(0x24, 0x27, 0x33), + tween: Color32::from_rgb(0x8a, 0x5c, 0xff), + tween_line: Color32::from_rgb(0x0e, 0x0e, 0x10), + playhead: Color32::from_rgb(0xff, 0x4d, 0x3d), + selection: Color32::from_rgb(0x2e, 0x66, 0xf0), + danger: Color32::from_rgb(0xd8, 0x34, 0x2a), + error: Color32::from_rgb(0xff, 0x6e, 0x60), + ok: Color32::from_rgb(0x5f, 0xe0, 0x9a), + kind_graphic: Color32::from_rgb(0x22, 0xc7, 0xa9), + kind_movie_clip: Color32::from_rgb(0x5a, 0x8f, 0xff), + kind_button: Color32::from_rgb(0xff, 0xb5, 0x3d), + radius_control: 3, + radius_menu: 6, + radius_window: 10, +}; + +impl Tokens { + /// Control corner radius for painter calls. + pub fn rc(&self) -> f32 { + f32::from(self.radius_control) + } +} + +/// Smallest click target (WCAG 2.5.8 asks for 24 × 24; we use 28). +pub const TARGET: f32 = 28.0; +/// Tool buttons in the tools bar, and the glyph inside them. +pub const TOOL_BUTTON: f32 = 36.0; +pub const TOOL_ICON: f32 = 18.0; + +/// Depth for floating surfaces: tight and downward, so a window lifts off the work without a +/// glow around it. +fn depth(y: i8, blur: u8, alpha: u8) -> Shadow { + Shadow { offset: [0, y], blur, spread: 0, color: Color32::from_black_alpha(alpha) } +} + +pub fn apply(ctx: &egui::Context) { + install_fonts(ctx, None, None); + let t = T; + let mut v = Visuals::dark(); + v.panel_fill = t.panel; + v.window_fill = t.panel_alt; + v.extreme_bg_color = t.field; + v.text_edit_bg_color = Some(t.field); + v.faint_bg_color = t.panel_alt; + v.override_text_color = Some(t.text); + v.selection.bg_fill = t.accent_dim; + v.selection.stroke = Stroke::new(2.0, t.accent); + v.hyperlink_color = t.accent; + v.window_stroke = Stroke::new(1.0, t.border); + v.window_shadow = depth(10, 28, 150); + v.popup_shadow = depth(4, 12, 130); + v.window_corner_radius = CornerRadius::same(t.radius_window); + v.menu_corner_radius = CornerRadius::same(t.radius_menu); + for w in [&mut v.widgets.noninteractive, &mut v.widgets.inactive, &mut v.widgets.hovered, &mut v.widgets.active, &mut v.widgets.open] { + w.corner_radius = CornerRadius::same(t.radius_control); + w.expansion = 0.0; + } + // Separators, group frames and other non-interactive shapes are structure: square. + v.widgets.noninteractive.corner_radius = CornerRadius::ZERO; + // Separators and group frames: the layout lines. + v.widgets.noninteractive.bg_stroke = Stroke::new(1.0, t.border); + v.widgets.noninteractive.fg_stroke = Stroke::new(1.0, t.text_dim); + // Buttons are flat fills at rest; no border on every button. + v.widgets.inactive.weak_bg_fill = t.header; + v.widgets.inactive.bg_fill = t.header; + v.widgets.inactive.bg_stroke = Stroke::NONE; + v.widgets.inactive.fg_stroke = Stroke::new(1.5, t.text); + v.widgets.hovered.weak_bg_fill = t.hover; + v.widgets.hovered.bg_fill = t.hover; + v.widgets.hovered.bg_stroke = Stroke::NONE; + v.widgets.hovered.fg_stroke = Stroke::new(1.5, t.text); + // Pressed and keyboard-focused widgets (egui styles focus as "active"): a visible ring. + v.widgets.active.weak_bg_fill = t.accent_dim; + v.widgets.active.bg_fill = t.accent_dim; + v.widgets.active.bg_stroke = Stroke::new(2.0, t.accent); + v.widgets.active.fg_stroke = Stroke::new(1.5, Color32::WHITE); + v.widgets.open.weak_bg_fill = t.hover; + v.widgets.open.bg_fill = t.hover; + v.widgets.open.bg_stroke = Stroke::NONE; + // Same dark look whatever the OS theme is. + ctx.all_styles_mut(|s| { + s.visuals = v.clone(); + s.spacing.item_spacing = egui::vec2(8.0, 6.0); + s.spacing.button_padding = egui::vec2(10.0, 5.0); + s.spacing.interact_size = egui::vec2(TARGET, TARGET); + s.spacing.icon_width = 16.0; + s.spacing.icon_width_inner = 9.0; + s.spacing.menu_margin = egui::Margin::same(6); + // Built-in text styles follow the roles, so plain widgets match the guidelines too. + use egui::TextStyle; + s.text_styles.insert(TextStyle::Body, font(Type::Body)); + s.text_styles.insert(TextStyle::Button, font(Type::Body)); + s.text_styles.insert(TextStyle::Small, font(Type::Caption)); + s.text_styles.insert(TextStyle::Heading, font(Type::Title)); + s.text_styles.insert(TextStyle::Monospace, font(Type::Data)); + }); +} + +mod craft_fonts { + include!(concat!(env!("OUT_DIR"), "/fonts.rs")); +} + +/// Which typefaces are active (for About and diagnostics). +pub fn font_summary() -> String { + match (craft_fonts::UI_FONT, craft_fonts::MONO_FONT) { + (Some(_), Some(_)) => format!("Inter + JetBrains Mono (craft-fonts, {} KB)", craft_fonts::CRAFT_FONT_BYTES / 1024), + (Some(_), None) => "Inter + Hack (fallback)".into(), + (None, Some(_)) => "Ubuntu (fallback) + JetBrains Mono".into(), + (None, None) => "Ubuntu + Hack (built-in defaults; build with CRAFT_FONTS_DIR for Inter + JetBrains Mono)".into(), + } +} + +/// A user-chosen system font: family name, file bytes, face index. +pub type UserFont = (String, Vec, u32); + +/// Installs the UI typefaces (ADR 0005). Order in each family: the user's system font (from +/// Preferences), then the craft-fonts pair (when embedded at build time), then egui's bundled +/// fonts, which stay as fallbacks for glyph coverage. +pub fn install_fonts(ctx: &egui::Context, ui_font: Option<&UserFont>, data_font: Option<&UserFont>) { + use egui::{FontData, FontDefinitions, FontFamily}; + use std::sync::Arc; + let mut defs = FontDefinitions::default(); + for (bytes, name, family) in [(craft_fonts::UI_FONT, "craft-inter", FontFamily::Proportional), (craft_fonts::MONO_FONT, "craft-jetbrains-mono", FontFamily::Monospace)] { + if let Some(b) = bytes { + defs.font_data.insert(name.to_owned(), Arc::new(FontData::from_static(b))); + defs.families.entry(family).or_default().insert(0, name.to_owned()); + } + } + for (user, family) in [(ui_font, FontFamily::Proportional), (data_font, FontFamily::Monospace)] { + if let Some((name, bytes, index)) = user { + let key = format!("user:{name}"); + let mut data = FontData::from_owned(bytes.clone()); + data.index = *index; + defs.font_data.insert(key.clone(), Arc::new(data)); + defs.families.entry(family).or_default().insert(0, key); + } + } + ctx.set_fonts(defs); +} + +/// Names of the bundled typefaces actually embedded in this build. +pub fn bundled_names() -> (&'static str, &'static str) { + (if craft_fonts::UI_FONT.is_some() { "Inter" } else { "Ubuntu" }, if craft_fonts::MONO_FONT.is_some() { "JetBrains Mono" } else { "Hack" }) +} + +/// Typographic roles (docs/ui-guidelines.md › Typography). **Prose is proportional; data is +/// monospace.** Data means values that are measured, counted or typed as codes: frame numbers, +/// timecode, rulers, coordinates, sizes, percentages, readouts, shortcut keys, paths and +/// preformatted text. Fixed-width digits do not jitter while a value changes, and columns line +/// up. Everything people *read* (labels, menus, buttons, names, dialog text, hints) stays +/// proportional. Code outside this module uses these roles, never raw font sizes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Type { + /// Dialog titles. + Title, + /// Panel and section headings (sentence case, bold; see `section`). + Heading, + /// Names and primary text: layer and symbol names, list items. + Body, + /// Secondary prose: status messages, field labels. + Label, + /// Hints, explanations, footnotes. + Caption, + /// Values and readouts: numeric fields, fps, time, coordinates, zoom. + Data, + /// Dense data: ruler ticks, playhead and badge numbers. + DataSmall, + /// The one hero number: current frame. + DataLarge, + /// Keyboard shortcuts and keycaps. + Key, + /// File paths, ids and preformatted documents (licence texts, JSON). + Path, +} + +/// Font for a role. +pub fn font(t: Type) -> egui::FontId { + use egui::FontId; + match t { + Type::Title => FontId::proportional(17.0), + Type::Heading => FontId::proportional(12.5), + Type::Body => FontId::proportional(13.0), + Type::Label => FontId::proportional(12.0), + Type::Caption => FontId::proportional(11.0), + Type::Data => FontId::monospace(12.0), + Type::DataSmall => FontId::monospace(10.0), + Type::DataLarge => FontId::monospace(14.5), + Type::Key => FontId::monospace(11.5), + Type::Path => FontId::monospace(11.0), + } +} + +/// Default colour for a role (override with `.color()` for state: error, accent…). +pub fn color(t: Type) -> Color32 { + match t { + Type::Title | Type::Heading | Type::Body | Type::Data | Type::DataLarge | Type::Path => T.text, + Type::Label | Type::DataSmall => T.text_dim, + Type::Caption | Type::Key => T.text_faint, + } +} + +/// Text in a role: font, size, colour (and weight for titles and headings). +pub fn text(t: Type, s: impl Into) -> egui::RichText { + let rt = egui::RichText::new(s).font(font(t)).color(color(t)); + match t { + Type::Title | Type::Heading => rt.strong(), + _ => rt, + } +} + +/// Buttons have no resting border, but a checkbox or radio button without one would vanish +/// when off. These give selection controls their own visible edge. +fn with_control_edges(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + ui.scope(|ui| { + let w = &mut ui.visuals_mut().widgets; + w.inactive.bg_stroke = Stroke::new(1.0, T.control_edge); + w.hovered.bg_stroke = Stroke::new(1.0, T.text_dim); + add(ui) + }) + .inner +} + +pub fn checkbox(ui: &mut egui::Ui, on: &mut bool, label: impl Into) -> egui::Response { + with_control_edges(ui, |ui| ui.checkbox(on, label)) +} + +pub fn radio_value(ui: &mut egui::Ui, current: &mut V, value: V, label: impl Into) -> egui::Response { + with_control_edges(ui, |ui| ui.radio_value(current, value, label)) +} + +/// Label column widths for forms: dialogs (Preferences) and the narrow dock. +pub const FORM_LABEL_DIALOG: f32 = 150.0; +pub const FORM_LABEL_DOCK: f32 = 78.0; + +/// A form row on a two-column grid: the label left-aligned in a fixed column, the controls after +/// it. Every row's controls start at the same x, so a form reads as one column of values. +pub fn form_row(ui: &mut egui::Ui, label_w: f32, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + ui.horizontal(|ui| { + ui.allocate_ui_with_layout(egui::vec2(label_w, TARGET), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_size(egui::vec2(label_w, TARGET)); + ui.label(text(Type::Label, label)); + }); + add(ui) + }) + .inner +} + +/// A note that belongs to the controls above it (an explanation, a preview): aligned with the +/// control column, wrapping within it, never back at the label column. +pub fn form_note(ui: &mut egui::Ui, label_w: f32, note: impl Into) { + ui.horizontal(|ui| { + // A row puts one item spacing between its label column and the controls. + ui.add_space(label_w + ui.spacing().item_spacing.x); + ui.add(egui::Label::new(note).wrap()); + }); +} + +/// How a collapsible section header looks. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Section { + /// A full-width band with layout borders and an accent edge: top-level dock sections. + Band, + /// Title followed by a horizontal rule across the row: groups inside a panel or dialog. + Rule, +} + +/// A collapsible section: a header the whole width of the row (one big click target, keyboard +/// focusable, announced as expanded/collapsed), then `add` while open. Open state is kept per +/// `id` for the session. `detail` is an optional data value shown after the title in the data +/// face (a frame number, a count). +pub fn section(ui: &mut egui::Ui, id: &str, style: Section, title: &str, detail: Option<&str>, add: impl FnOnce(&mut egui::Ui) -> R) -> Option { + use egui::{Sense, StrokeKind, pos2, vec2}; + let key = ui.make_persistent_id(("section", id)); + let mut open = ui.data_mut(|d| *d.get_temp_mut_or(key, true)); + let height = if style == Section::Band { 32.0 } else { TARGET }; + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click()); + if resp.clicked() { + open = !open; + ui.data_mut(|d| d.insert_temp(key, open)); + } + let enabled = ui.is_enabled(); + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, enabled, open, title)); + let p = ui.painter(); + let hot = resp.hovered() || resp.has_focus(); + match style { + Section::Band => { + p.rect_filled(rect, SQUARE, if hot { T.header } else { T.panel_alt }); + p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(1.0, T.border)); + p.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, T.border)); + p.rect_filled(egui::Rect::from_min_size(rect.left_top() + vec2(0.0, 1.0), vec2(3.0, rect.height() - 1.0)), SQUARE, T.accent); + } + Section::Rule => { + if hot { + p.rect_filled(rect, T.rc(), T.panel_alt); + } + } + } + if resp.has_focus() { + p.rect_stroke(rect.shrink(1.0), T.rc(), Stroke::new(2.0, T.accent), StrokeKind::Inside); + } + // Chevron: right when closed, down when open. + let left = if style == Section::Band { 10.0 } else { 2.0 }; + let chevron = egui::Rect::from_center_size(pos2(rect.left() + left + 7.0, rect.center().y), vec2(14.0, 14.0)); + let icon = if open { crate::icons::Icon::ChevronDown } else { crate::icons::Icon::ChevronRight }; + crate::icons::paint(p, chevron, icon, if hot { T.text } else { T.text_dim }); + let mut x = rect.left() + left + 20.0; + let title_g = p.layout_no_wrap(title.to_string(), font(Type::Heading), color(Type::Heading)); + let w = title_g.rect.width(); + p.galley(pos2(x, rect.center().y - title_g.rect.height() * 0.5), title_g, color(Type::Heading)); + x += w; + if let Some(d) = detail { + let g = p.layout_no_wrap(d.to_string(), font(Type::Data), T.text_dim); + x += 8.0; + let dw = g.rect.width(); + p.galley(pos2(x, rect.center().y - g.rect.height() * 0.5), g, T.text_dim); + x += dw; + } + if style == Section::Rule && x + 12.0 < rect.right() { + p.hline((x + 12.0)..=rect.right(), rect.center().y, Stroke::new(1.0, T.border)); + } + if !open { + if style == Section::Rule { + ui.add_space(2.0); + } + return None; + } + if style == Section::Rule { + ui.add_space(2.0); + } + let r = add(ui); + ui.add_space(if style == Section::Rule { 10.0 } else { 0.0 }); + Some(r) +} + +/// Runs `add` with every widget's text in `role` (e.g. numeric fields in the Data role). +pub fn with_type(ui: &mut egui::Ui, role: Type, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + ui.scope(|ui| { + ui.style_mut().override_font_id = Some(font(role)); + add(ui) + }) + .inner +} + +pub fn to_color32(c: anicraft_engine::doc::Rgba) -> Color32 { + let c = c.sanitized(); + Color32::from_rgba_unmultiplied((c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8, (c.a * 255.0).round() as u8) +} diff --git a/src/timeline.rs b/src/timeline.rs new file mode 100644 index 00000000..7173720a --- /dev/null +++ b/src/timeline.rs @@ -0,0 +1,824 @@ +//! Timeline panel: transport, layer list and a virtualised frame grid. + +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::menus; +use crate::theme::{SQUARE, T, TARGET, Type, color, font, text, to_color32, with_type}; +use anicraft_engine::doc::{Easing, Layer, LayerId, LayerKind}; +use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use serde_json::json; +use std::sync::Arc; + +const LAYER_W: f32 = 252.0; +/// Rows are click targets (≥ `theme::TARGET`). +const ROW_H: f32 = TARGET; +const RULER_H: f32 = 24.0; +/// Frame cell width at 100 % zoom, and the zoom range (Ctrl+wheel over the frames, or the +/// slider in the timeline header). +pub const CELL_DEFAULT: f32 = 12.0; +pub const CELL_RANGE: std::ops::RangeInclusive = 3.0..=48.0; +/// Width of the playhead's number flag (wider only for long frame numbers). +const HEAD_W: f32 = 22.0; + +/// Room before frame 1: what the playhead's flag needs when centred on frame 1, plus `extra` +/// points. Fixed on screen: it shrinks to a hairline once frames are wider than the flag, and +/// never grows with the zoom. +fn start_pad(cell_w: f32, extra: f32) -> f32 { + (HEAD_W * 0.5 - cell_w * 0.5).max(0.0) + 1.0 + extra +} + +/// The pixel column through the middle of a frame whose cell starts at `cell_left`: ruler +/// ticks, their numbers and the playhead line all use it, so they always line up. +fn frame_center(cell_left: f32, cell_w: f32) -> f32 { + (cell_left + cell_w * 0.5).round() + 0.5 +} +const FOOTER_H: f32 = 38.0; +/// Eye / lock / outline toggles: square targets in each layer row. +const TOGGLE: f32 = 24.0; + +/// A rectangle of frames: the layers between the anchor's and the head's rows (in the +/// current layer order) by the frames between them. View state: commands get explicit ranges. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FrameSel { + pub anchor: (LayerId, u32), + pub head: (LayerId, u32), +} + +impl FrameSel { + pub fn cell(layer: LayerId, frame: u32) -> FrameSel { + FrameSel { anchor: (layer, frame), head: (layer, frame) } + } + /// First and last selected frame. + pub fn frames(&self) -> (u32, u32) { + (self.anchor.1.min(self.head.1), self.anchor.1.max(self.head.1)) + } + /// Selected rows (indices into the layer list), or `None` when a layer went away. + fn rows(&self, layers: &[Arc]) -> Option<(usize, usize)> { + let a = layers.iter().position(|l| l.id == self.anchor.0)?; + let h = layers.iter().position(|l| l.id == self.head.0)?; + Some((a.min(h), a.max(h))) + } + pub fn layers(&self, layers: &[Arc]) -> Vec { + self.rows(layers).map(|(a, b)| layers.iter().skip(a).take(b - a + 1).map(|l| l.id).collect()).unwrap_or_default() + } + fn contains(&self, layers: &[Arc], row: usize, frame: u32) -> bool { + let (f0, f1) = self.frames(); + self.rows(layers).is_some_and(|(a, b)| row >= a && row <= b) && frame >= f0 && frame <= f1 + } + /// Whether any selected layer has a keyframe starting in the selected frames. + pub fn has_keys(&self, layers: &[Arc]) -> bool { + let (f0, f1) = self.frames(); + let ids = self.layers(layers); + layers.iter().filter(|l| ids.contains(&l.id)).any(|l| l.keyframes.iter().any(|k| k.start >= f0 && k.start <= f1)) + } +} + +/// In-progress pointer gesture on the frame grid. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum TlDrag { + #[default] + None, + /// Dragging out a frame selection. + Select, + /// Dragging the selected keyframes: grabbed at frame `grab`, currently `by` frames away. + Move { grab: u32, by: i64, grab_row: usize, rows_by: i64 }, + /// Dragging the end of the span `start..end` on `layer` to `to`. + Span { layer: LayerId, start: u32, end: u32, to: u32 }, +} + +/// Range params for the frame commands when frames are selected: `{layers, frame, count}`. +pub fn range_params(app: &App) -> Option { + let sel = app.frame_sel?; + let layers = sel.layers(&app.s.doc.timeline.layers); + if layers.is_empty() { + return None; + } + let (f0, f1) = sel.frames(); + let ids: Vec = layers.iter().map(|l| l.0).collect(); + Some(json!({"layers": ids, "frame": f0, "count": f1 - f0 + 1})) +} + +/// Frame commands that act on the frame selection. +pub const RANGE_COMMANDS: [&str; 7] = ["timeline.insert_frame", "timeline.remove_frame", "timeline.insert_keyframe", "timeline.insert_blank_keyframe", "timeline.clear_keyframe", "timeline.copy_frames", "timeline.cut_frames"]; + +/// Params for Paste Frames: the selection's top layer and first frame. +pub fn paste_params(app: &App) -> Option { + let sel = app.frame_sel?; + let top = *sel.layers(&app.s.doc.timeline.layers).first()?; + Some(json!({"layer": top.0, "frame": sel.frames().0})) +} + +/// An icon button: a full-size target around a Lucide glyph. `active` marks a toggle that is on. +fn icon_button(ui: &mut egui::Ui, tip: &str, active: bool, icon: Icon) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(vec2(TARGET + 4.0, TARGET), Sense::click()); + // Same language as the tools: a toggle that is on is a lighter gray block, icon white. + let bg = if active { + T.active + } else if resp.hovered() { + T.header + } else { + Color32::TRANSPARENT + }; + ui.painter().rect_filled(rect, T.rc(), bg); + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), icon, if active || resp.hovered() { Color32::WHITE } else { T.icon }); + resp.on_hover_text(tip) +} + +fn transport(app: &mut App, ui: &mut egui::Ui) { + if icon_button(ui, "First frame (Home)", false, Icon::First).clicked() { + app.run("timeline.first_frame", json!({})); + } + if icon_button(ui, "Previous frame (,)", false, Icon::Prev).clicked() { + app.run("timeline.prev_frame", json!({})); + } + let playing = app.playing; + if icon_button(ui, "Play / Stop (Enter)", playing, if playing { Icon::Pause } else { Icon::Play }).clicked() { + app.toggle_play(); + } + if icon_button(ui, "Next frame (.)", false, Icon::Next).clicked() { + app.run("timeline.next_frame", json!({})); + } + if icon_button(ui, "Last frame (End)", false, Icon::Last).clicked() { + app.run("timeline.last_frame", json!({})); + } + let looping = app.looping; + if icon_button(ui, "Loop playback", looping, Icon::Loop).clicked() { + app.looping = !app.looping; + } + let onion = app.onion; + if icon_button(ui, "Onion skin", onion, Icon::Onion).clicked() { + app.onion = !app.onion; + } +} + +pub fn show(app: &mut App, ui: &mut egui::Ui) { + // ---- header --------------------------------------------------------------------------- + egui::Frame::NONE.fill(T.panel_alt).inner_margin(egui::Margin::symmetric(10, 5)).show(ui, |ui| { + ui.horizontal(|ui| { + ui.label(text(Type::Heading, "Timeline")); + ui.add_space(8.0); + transport(app, ui); + ui.add_space(8.0); + let fps = app.s.doc.stage.fps; + let f = app.s.frame; + // Fixed-width readouts: digits stay put while the playhead moves. + let digits = app.s.frame_count().max(f + 1).to_string().len().max(3); + ui.label(text(Type::DataLarge, format!("{:>digits$}", f + 1)).color(T.accent)).on_hover_text("Current frame"); + ui.label(text(Type::Data, format!("{fps:.2} fps")).color(T.text_dim)).on_hover_text("Frame rate"); + ui.label(text(Type::Data, format!("{:>7.2} s", f as f32 / fps.max(1.0))).color(T.text_dim)).on_hover_text("Time at the playhead"); + ui.separator(); + // Through `invoke`, so the buttons act on the frame selection like the keys do. + let cmd = |app: &mut App, ui: &mut egui::Ui, label: &str, tip: &str, id: &'static str| { + if ui.button(label).on_hover_text(tip).clicked() { + app.invoke(id); + } + }; + cmd(app, ui, "Frame", "Insert frame (F5)", "timeline.insert_frame"); + cmd(app, ui, "Keyframe", "Insert keyframe (F6)", "timeline.insert_keyframe"); + cmd(app, ui, "Blank", "Insert blank keyframe (F7)", "timeline.insert_blank_keyframe"); + let in_tween = app.s.active_layer().and_then(|l| l.keyframe_at(app.s.frame)).and_then(|k| k.tween); + match in_tween { + Some(tw) => { + egui::ComboBox::from_id_salt("tl_ease").width(150.0).selected_text(tw.easing.label()).show_ui(ui, |ui| { + for (name, e) in Easing::PRESETS { + if ui.selectable_label(tw.easing == e, name).clicked() { + app.run("timeline.set_easing", json!({"easing": easing_param(e)})); + } + } + }); + cmd(app, ui, "Remove Tween", "Remove the classic tween from this span", "timeline.remove_tween"); + } + None => cmd(app, ui, "Create Tween", "Create a classic tween to the next keyframe", "timeline.create_tween"), + } + // Frame zoom, at the right end of the header. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut pct = app.tl_cell_w / CELL_DEFAULT * 100.0; + let (lo, hi) = (CELL_RANGE.start() / CELL_DEFAULT * 100.0, CELL_RANGE.end() / CELL_DEFAULT * 100.0); + let r = with_type(ui, Type::Data, |ui| ui.add(egui::Slider::new(&mut pct, lo..=hi).logarithmic(true).max_decimals(0).suffix(" %"))); + if r.on_hover_text("Frame width (Ctrl+wheel over the frames)").changed() { + app.tl_cell_w = (pct / 100.0 * CELL_DEFAULT).clamp(*CELL_RANGE.start(), *CELL_RANGE.end()); + } + ui.label(text(Type::Label, "Zoom")); + }); + }); + }); + + // A frame selection lives while the playhead is inside it and its layers exist. + if let Some(sel) = app.frame_sel { + let (f0, f1) = sel.frames(); + let gone = sel.layers(&app.s.doc.timeline.layers).is_empty(); + if gone || app.playing || (app.tl_drag == TlDrag::None && !(f0..=f1).contains(&app.s.frame)) { + app.frame_sel = None; + } + } + + // ---- body ----------------------------------------------------------------------------- + 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); + + let grid = Rect::from_min_max(pos2(body.left() + LAYER_W, body.top()), body.right_bottom()); + let frames_total = app.s.frame_count(); + app.tl_cell_w = app.tl_cell_w.clamp(*CELL_RANGE.start(), *CELL_RANGE.end()); + // Ctrl+wheel (or pinch) over the frames zooms about the pointer: the frame under it stays put. + // Room before frame 1: exactly what the playhead's flag needs to be drawn whole when it + // sits on frame 1 (the flag is centred on the frame), plus an optional extra gap in points + // (a preference). Fixed on screen: it does not grow with the zoom. + let pad_for = |cw: f32| start_pad(cw, app.prefs.timeline_start_gap); + if ui.rect_contains_pointer(body) { + let (zoom, hover) = ui.input(|i| (i.zoom_delta(), i.pointer.hover_pos())); + if (zoom - 1.0).abs() > 1e-4 + && let Some(h) = hover.filter(|h| h.x >= grid.left()) + { + let old = app.tl_cell_w; + let new = (old * zoom).clamp(*CELL_RANGE.start(), *CELL_RANGE.end()); + let under = (h.x - grid.left() - pad_for(old)) / old + app.tl_scroll; + app.tl_cell_w = new; + app.tl_scroll = (under - (h.x - grid.left() - pad_for(new)) / new).max(0.0); + } + } + let cell_w = app.tl_cell_w; + // Dead space before frame 1 (a preference): the playhead's flag never touches the edge. + let pad = pad_for(cell_w); + let visible_cols = ((grid.width() / cell_w).ceil() as u32).max(1); + // Scrolling, as in a web browser: the wheel scrolls the layers up and down; Shift+wheel and + // sideways wheels / trackpad swipes scroll the frames (egui turns Shift+wheel into a + // horizontal delta). Anywhere over the timeline, rows and cells included. Only visible + // rows and columns are painted, so cost is independent of document size. + let n_layers = app.s.doc.timeline.layers.len(); + let rows_visible = ((body.height() - RULER_H - FOOTER_H) / ROW_H).floor().max(1.0) as usize; + if ui.rect_contains_pointer(body) { + let d = ui.input(|i| i.smooth_scroll_delta); + if d.x != 0.0 { + app.tl_scroll = (app.tl_scroll - d.x / cell_w).max(0.0); + } + if d.y != 0.0 { + app.tl_vscroll = (app.tl_vscroll - d.y / ROW_H).max(0.0); + } + } + app.tl_vscroll = app.tl_vscroll.min(n_layers.saturating_sub(rows_visible) as f32); + if app.tl_last_layer != Some(app.s.layer) + && let Some(ai) = app.s.active_layer_index() + { + // the active layer changed (e.g. picked on the stage): bring its row into view + if (ai as f32) < app.tl_vscroll { + app.tl_vscroll = ai as f32; + } else if ai >= app.tl_vscroll as usize + rows_visible { + app.tl_vscroll = (ai + 1 - rows_visible) as f32; + } + app.tl_last_layer = Some(app.s.layer); + } + let first_row = app.tl_vscroll.floor() as usize; + let max_scroll = (frames_total + 30).saturating_sub(visible_cols) as f32; + app.tl_scroll = app.tl_scroll.min(max_scroll.max(0.0)); + // keep the playhead visible while playing + if app.playing { + let f = app.s.frame as f32; + if f < app.tl_scroll || f >= app.tl_scroll + visible_cols as f32 - 2.0 { + app.tl_scroll = (f - 2.0).max(0.0); + } + } + let scroll = app.tl_scroll; + let first = scroll.floor() as u32; + let x_of = |f: u32| grid.left() + pad + (f as f32 - scroll) * cell_w; + // The padding is dead space: a click there means frame 1, never a frame before it. + let frame_at = |x: f32| ((x - grid.left() - pad) / cell_w + scroll).floor().max(0.0) as u32; + let gp = painter.with_clip_rect(grid); + + // ruler: numbers every `step` frames, chosen so labels never collide at any zoom + let ruler = Rect::from_min_max(grid.left_top(), pos2(grid.right(), grid.top() + RULER_H)); + painter.rect_filled(ruler, 0.0, T.panel_alt); + painter.rect_filled(Rect::from_min_max(body.left_top(), pos2(grid.left(), ruler.bottom())), 0.0, T.panel_alt); + painter.text(pos2(body.left() + 10.0, ruler.center().y), Align2::LEFT_CENTER, "Layers", font(Type::Heading), color(Type::Heading)); + let step = [1u32, 2, 5, 10, 20, 50, 100, 200, 500].into_iter().find(|s| *s as f32 * cell_w >= 28.0).unwrap_or(1000); + let minor = if cell_w >= 6.0 { 1 } else { step / 5 }.max(1); + for f in first..first + visible_cols + 1 { + let x = x_of(f); + let n = f + 1; + // Ticks and numbers sit on the frame's centre, where the playhead line and the + // keyframe dots are, so "1" is exactly under the playhead on frame 1 at any zoom. + let cx = frame_center(x, cell_w); + if n % step == 0 || n == 1 { + gp.line_segment([pos2(cx, ruler.bottom() - 6.0), pos2(cx, ruler.bottom())], Stroke::new(1.0, T.text_faint)); + gp.text(pos2(cx, ruler.top() + 3.0), Align2::CENTER_TOP, n.to_string(), font(Type::DataSmall), color(Type::DataSmall)); + } else if n % minor == 0 { + gp.line_segment([pos2(cx, ruler.bottom() - 3.0), pos2(cx, ruler.bottom())], Stroke::new(1.0, T.border)); + } + } + let ruler_resp = ui.interact(ruler, ui.id().with("ruler"), Sense::click_and_drag()); + if (ruler_resp.clicked() || ruler_resp.dragged()) + && let Some(p) = ruler_resp.interact_pointer_pos() { + app.playing = false; + app.run("timeline.goto", json!({"frame": frame_at(p.x)})); + } + + // rows + let layers = app.s.doc.timeline.layers.clone(); + let active = app.s.layer; + let rows_top = ruler.bottom(); + let rows_bottom = body.bottom() - FOOTER_H; + for (i, layer) in layers.iter().enumerate().skip(first_row) { + let y = rows_top + (i - first_row) as f32 * ROW_H; + // Whole rows only: a cut-off row would sit under the footer (scroll for the rest). + if y + ROW_H > rows_bottom + 0.5 { + break; + } + let row = Rect::from_min_size(pos2(body.left(), y), vec2(body.width(), ROW_H)); + let left = Rect::from_min_max(row.left_top(), pos2(grid.left(), row.bottom())); + let is_active = layer.id == active; + painter.rect_filled(left, 0.0, if is_active { T.accent_dim } else if i % 2 == 0 { T.panel } else { T.panel_alt }); + // The layer's colour as a full-height edge bar. + painter.rect_filled(Rect::from_min_size(left.left_top(), vec2(4.0, ROW_H)), 0.0, to_color32(layer.color)); + // Mask layers carry a stencil glyph; the layers they mask are indented under them. + let name_color = if layer.visible { T.text } else { T.text_faint }; + let type_icon = |x: f32, icon: Icon| icons::paint(&painter, Rect::from_center_size(pos2(x, left.center().y), vec2(14.0, 14.0)), icon, name_color); + let name_x = match (layer.kind, layer.parent) { + (LayerKind::Mask, _) => { + type_icon(left.left() + 19.0, Icon::Mask); + left.left() + 32.0 + } + (LayerKind::Normal, Some(_)) => { + type_icon(left.left() + 33.0, Icon::Masked); + left.left() + 46.0 + } + _ => left.left() + 16.0, + }; + painter.text(pos2(name_x, left.center().y), Align2::LEFT_CENTER, &layer.name, font(Type::Body), name_color); + + // eye / lock / outline toggles: 24 × 24 targets with a hover fill + let toggle = |k: f32| Rect::from_center_size(pos2(left.right() - 16.0 - k * (TOGGLE + 2.0), left.center().y), vec2(TOGGLE, TOGGLE)); + let (eye, lock, outl) = (toggle(2.0), toggle(1.0), toggle(0.0)); + let hover = ui.input(|inp| inp.pointer.hover_pos()); + for r in [eye, lock, outl] { + if hover.is_some_and(|h| r.contains(h)) { + painter.rect_filled(r, T.rc(), T.hover); + } + } + let c_on = T.text; + let c_off = T.text_faint; + // eye and lock (state shows in the glyph and its brightness) + let glyph = |r: Rect| Rect::from_center_size(r.center(), vec2(15.0, 15.0)); + icons::paint(&painter, glyph(eye), if layer.visible { Icon::Eye } else { Icon::EyeOff }, if layer.visible { c_on } else { c_off }); + icons::paint(&painter, glyph(lock), if layer.locked { Icon::Lock } else { Icon::Unlock }, if layer.locked { c_on } else { c_off }); + // outline swatch + let sw = Rect::from_center_size(outl.center(), vec2(10.0, 10.0)); + if layer.outline { + painter.rect_stroke(sw, 0.0, Stroke::new(1.5, to_color32(layer.color)), StrokeKind::Inside); + } else { + painter.rect_filled(sw, 0.0, to_color32(layer.color)); + } + for (r, id, salt) in [(eye, "layer.toggle_visible", "eye"), (lock, "layer.toggle_lock", "lock"), (outl, "layer.toggle_outline", "outline")] { + let rr = ui.interact(r, ui.id().with((salt, layer.id.0)), Sense::click()); + if rr.clicked() { + app.run(id, json!({"layer": layer.id.0})); + } + } + let name_rect = Rect::from_min_max(left.left_top(), pos2(eye.left() - 4.0, left.bottom())); + let nr = ui.interact(name_rect, ui.id().with(("lname", layer.id.0)), Sense::click()); + if nr.clicked() { + app.run("layer.select", json!({"layer": layer.id.0})); + } + if nr.secondary_clicked() && app.s.layer != layer.id { + app.run("layer.select", json!({"layer": layer.id.0})); + } + if nr.double_clicked() { + app.invoke("layer.rename"); + } + nr.context_menu(|ui| { + ui.set_min_width(200.0); + for id in ["layer.rename", "layer.new", "layer.delete"] { + menus::cmd_item(app, ui, id); + } + ui.separator(); + for id in ["layer.toggle_visible", "layer.toggle_lock", "layer.toggle_outline"] { + menus::cmd_item(app, ui, id); + } + ui.separator(); + // Layer type, as check items: Mask (masks the layer below) and Masked. + if menus::check_item(ui, "Mask", layer.kind == LayerKind::Mask, true) { + app.run("layer.toggle_mask", json!({"layer": layer.id.0})); + } + let can_mask = layer.kind == LayerKind::Normal && app.s.doc.timeline.mask_above(i).is_some(); + if menus::check_item(ui, "Masked", layer.parent.is_some(), can_mask || layer.parent.is_some()) { + let ty = if layer.parent.is_some() { "normal" } else { "masked" }; + app.run("layer.set_type", json!({"layer": layer.id.0, "type": ty})); + } + ui.separator(); + for id in ["layer.move_up", "layer.move_down"] { + menus::cmd_item(app, ui, id); + } + }); + + // frame cells + let cells = Rect::from_min_max(pos2(grid.left(), y), pos2(grid.right(), y + ROW_H)); + let cp = painter.with_clip_rect(cells); + cp.rect_filled(cells, 0.0, if is_active { T.row_active } else { T.panel }); + for f in first..first + visible_cols + 1 { + let x = x_of(f); + if (f + 1) % 5 == 0 && cell_w >= 6.0 { + cp.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell_w, ROW_H)), 0.0, Color32::from_white_alpha(6)); + } + // Cell lines thin out with the ruler when zoomed out, so rows never turn to hatching. + if (f + 1) % minor == 0 { + cp.line_segment([pos2(x + cell_w - 0.5, y), pos2(x + cell_w - 0.5, y + ROW_H)], Stroke::new(1.0, T.separator)); + } + } + // Spans are solid square blocks, separated by a one-pixel gap rather than outlines: + // mint holds artwork, violet tweens, graphite is empty. Marks on them are ink. + for (ki, k) in layer.keyframes.iter().enumerate() { + if k.end() < first || k.start > first + visible_cols { + continue; + } + let x0 = x_of(k.start); + let x1 = x_of(k.end()); + let span = Rect::from_min_max(pos2(x0, y + 3.0), pos2(x1 - 1.0, y + ROW_H - 3.0)); + let next_adjacent = layer.keyframes.get(ki + 1).is_some_and(|n| n.start == k.end()); + let tweened = k.tween.is_some() && next_adjacent; + let empty = k.elements.is_empty(); + let fill = if tweened { + T.tween + } else if empty { + T.span_empty + } else { + T.span + }; + let mark = if empty && !tweened { T.text } else { T.ink }; + cp.rect_filled(span, SQUARE, fill); + let kc = pos2(x0 + cell_w * 0.5, y + ROW_H * 0.5); + if tweened && k.duration > 1 { + let end = pos2(x1 - cell_w * 0.5 - 4.0, kc.y); + cp.line_segment([kc + vec2(5.0, 0.0), end], Stroke::new(1.5, T.tween_line)); + cp.add(egui::Shape::convex_polygon(vec![end + vec2(0.0, -3.5), end + vec2(5.0, 0.0), end + vec2(0.0, 3.5)], T.tween_line, Stroke::NONE)); + } else if k.tween.is_some() && !next_adjacent && k.duration > 1 { + // broken tween: dashed line + let mut x = kc.x + 6.0; + while x < x1 - 6.0 { + cp.line_segment([pos2(x, kc.y), pos2((x + 3.0).min(x1 - 6.0), kc.y)], Stroke::new(1.5, mark)); + x += 6.0; + } + } else if k.duration > 1 { + let er = Rect::from_center_size(pos2(x1 - cell_w * 0.5 - 1.0, kc.y + 2.0), vec2(5.0, 7.0)); + cp.rect_stroke(er, 0.0, Stroke::new(1.2, mark), StrokeKind::Inside); + } + if empty { + cp.circle_stroke(kc, 3.5, Stroke::new(1.5, mark)); + } else { + cp.circle_filled(kc, 4.0, mark); + } + if !k.label.is_empty() { + cp.text(kc + vec2(8.0, -1.0), Align2::LEFT_CENTER, &k.label, font(Type::Caption), mark); + } + } + // Selected frames, and where a keyframe drag would drop them. + if let Some(sel) = app.frame_sel + && sel.rows(&layers).is_some_and(|(a, b)| i >= a && i <= b) + { + let (f0, f1) = sel.frames(); + let r = Rect::from_min_max(pos2(x_of(f0), y + 1.0), pos2(x_of(f1 + 1) - 1.0, y + ROW_H - 1.0)); + cp.rect_filled(r, SQUARE, T.selection.gamma_multiply(0.28)); + cp.rect_stroke(r, SQUARE, Stroke::new(2.0, T.selection), StrokeKind::Inside); + } + // Where a keyframe drag would drop them: shifted in time and, across rows, onto this row. + if let (TlDrag::Move { by, rows_by, .. }, Some(sel)) = (app.tl_drag, app.frame_sel) + && (by != 0 || rows_by != 0) + && let Some((a, b)) = sel.rows(&layers) + && let Some(src) = i64::try_from(i).ok().map(|r| r - rows_by) + && src >= a as i64 + && src <= b as i64 + { + let (f0, f1) = sel.frames(); + let g = Rect::from_min_max(pos2(x_of(f0), y + 1.0), pos2(x_of(f1 + 1) - 1.0, y + ROW_H - 1.0)).translate(vec2(by as f32 * cell_w, 0.0)); + cp.rect_stroke(g, SQUARE, Stroke::new(2.0, Color32::WHITE), StrokeKind::Inside); + } + // Span length being dragged on this row: the new end line and its length readout. + if let TlDrag::Span { layer: lid, start, end, to } = app.tl_drag + && lid == layer.id + { + // The frames gained (or given up), so the change reads as part of the span. + let (a, b) = (x_of(end.min(to)), x_of(end.max(to))); + let changed = Rect::from_min_max(pos2(a, y + 2.0), pos2(b - 1.0, y + ROW_H - 2.0)); + cp.rect_filled(changed, SQUARE, if to > end { T.selection.gamma_multiply(0.35) } else { Color32::from_black_alpha(120) }); + let x = x_of(to); + cp.line_segment([pos2(x, y + 1.0), pos2(x, y + ROW_H - 1.0)], Stroke::new(2.0, Color32::WHITE)); + let n = to - start; + let secs = n as f32 / app.s.doc.stage.fps.max(1.0); + let label = format!("{n} {} · {secs:.2} s", if n == 1 { "frame" } else { "frames" }); + let at = pos2(x + 6.0, y + ROW_H * 0.5); + let galley = painter.layout_no_wrap(label, font(Type::DataSmall), Color32::WHITE); + let (w, h) = (galley.rect.width(), galley.rect.height()); + let bg = Rect::from_min_size(at - vec2(3.0, h * 0.5 + 2.0), vec2(w + 6.0, h + 4.0)); + painter.rect_filled(bg, T.rc(), T.chrome); + painter.rect_stroke(bg, T.rc(), Stroke::new(1.0, T.border), StrokeKind::Inside); + painter.galley(bg.min + vec2(3.0, 2.0), galley, Color32::WHITE); + } + let cr = ui.interact(cells, ui.id().with(("cells", layer.id.0)), Sense::click_and_drag()); + let shift = ui.input(|inp| inp.modifiers.shift); + if cr.clicked() || cr.drag_started() || cr.secondary_clicked() { + app.timeline_focus = true; + } + // The right edge of a span is a handle: drag it to make the span longer or shorter + // (later frames move with it, as with F5 / Shift+F5). + let span_end_at = |px: f32| layer.keyframes.iter().find(|k| k.end() > first && k.start <= first + visible_cols && (x_of(k.end()) - px).abs() <= 4.0).map(|k| (k.start, k.end())); + if cr.hovered() && app.tl_drag == TlDrag::None && cr.hover_pos().and_then(|p| span_end_at(p.x)).is_some() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if matches!(app.tl_drag, TlDrag::Span { .. }) { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if cr.drag_started() + && let Some(p) = ui.input(|inp| inp.pointer.press_origin()) + && let Some((start, end)) = span_end_at(p.x) + { + app.playing = false; + app.tl_drag = TlDrag::Span { layer: layer.id, start, end, to: end }; + } + let select_here = |app: &mut App, frame: u32| { + app.playing = false; + if app.s.layer != layer.id { + app.run("layer.select", json!({"layer": layer.id.0})); + } + app.run("timeline.goto", json!({"frame": frame})); + }; + // Press on selected frames that hold keyframes: drag them. Elsewhere: select a range. + if cr.drag_started() + && app.tl_drag == TlDrag::None + && let Some(p) = ui.input(|inp| inp.pointer.press_origin()) + { + let f = frame_at(p.x); + let grab = app.frame_sel.filter(|s| s.contains(&layers, i, f) && s.has_keys(&layers)); + if grab.is_some() { + app.tl_drag = TlDrag::Move { grab: f, by: 0, grab_row: i, rows_by: 0 }; + } else { + app.frame_sel = Some(FrameSel::cell(layer.id, f)); + app.tl_drag = TlDrag::Select; + select_here(app, f); + } + } + if cr.dragged() + && let Some(p) = cr.interact_pointer_pos() + { + let f = frame_at(p.x); + match (app.tl_drag, app.frame_sel.as_mut()) { + (TlDrag::Select, Some(sel)) => { + let r = ((p.y - rows_top) / ROW_H).floor().max(0.0) as usize + first_row; + let row = r.min(layers.len().saturating_sub(1)); + if let Some(l) = layers.get(row) { + sel.head = (l.id, f); + } + } + (TlDrag::Move { grab, grab_row, .. }, Some(sel)) => { + // Never before frame 1, and only onto layers that exist. + let by = (i64::from(f) - i64::from(grab)).max(-i64::from(sel.frames().0)); + let row = ((p.y - rows_top) / ROW_H).floor() as i64 + first_row as i64; + let rows_by = match sel.rows(&layers) { + Some((a, b)) => (row - grab_row as i64).clamp(-(a as i64), layers.len() as i64 - 1 - b as i64), + None => 0, + }; + app.tl_drag = TlDrag::Move { grab, by, grab_row, rows_by }; + } + (TlDrag::Span { layer: lid, start, end, .. }, _) => { + // Snap to the nearest frame boundary; a span keeps at least one frame. + let b = ((p.x - grid.left() - pad) / cell_w + scroll).round().max(0.0) as u32; + app.tl_drag = TlDrag::Span { layer: lid, start, end, to: b.max(start + 1) }; + } + _ => {} + } + } + if cr.drag_stopped() + && let TlDrag::Span { layer: lid, start: _, end, to } = app.tl_drag + { + let lid = lid.0; + if to > end { + app.request("timeline.insert_frame", json!({"layer": lid, "frame": end - 1, "count": to - end})); + } else if to < end { + app.request("timeline.remove_frame", json!({"layer": lid, "frame": to, "count": end - to})); + } + app.tl_drag = TlDrag::None; + } + if cr.drag_stopped() { + if let (TlDrag::Move { by, rows_by, .. }, Some(sel)) = (app.tl_drag, app.frame_sel) + && (by != 0 || rows_by != 0) + { + let (f0, f1) = sel.frames(); + let ids: Vec = sel.layers(&layers).iter().map(|l| l.0).collect(); + if app.run("timeline.move_keyframes", json!({"layers": ids, "from": f0, "to": f1, "by": by, "layer_by": rows_by})).is_some() { + // The selection follows the frames: shifted in time and onto the target rows. + let shift_by = |f: u32| (i64::from(f) + by).max(0) as u32; + let row_of = |id: LayerId| layers.iter().position(|l| l.id == id).and_then(|r| layers.get((r as i64 + rows_by).max(0) as usize)).map_or(id, |l| l.id); + app.frame_sel = Some(FrameSel { anchor: (row_of(sel.anchor.0), shift_by(sel.anchor.1)), head: (row_of(sel.head.0), shift_by(sel.head.1)) }); + let n = f1 - f0 + 1; + let what = format!("{n} {}", if n == 1 { "frame" } else { "frames" }); + app.status_ok(match rows_by { + 0 => format!("Moved {what} by {by:+} — Ctrl+Z to undo"), + r => format!("Moved {what} {} {} {} — Ctrl+Z to undo", r.abs(), if r.abs() == 1 { "layer" } else { "layers" }, if r < 0 { "up" } else { "down" }), + }); + app.run("timeline.goto", json!({"frame": shift_by(app.s.frame)})); + if rows_by != 0 + && let Some(&top) = sel.layers(&layers).first() + { + let target = row_of(top); + app.run("layer.select", json!({"layer": target.0})); + } + } + } + app.tl_drag = TlDrag::None; + } + if cr.clicked() + && let Some(p) = cr.interact_pointer_pos() + { + let f = frame_at(p.x); + match app.frame_sel.as_mut() { + Some(sel) if shift => sel.head = (layer.id, f), + _ => app.frame_sel = Some(FrameSel::cell(layer.id, f)), + } + select_here(app, f); + } + // Right-click: keep a selection under the pointer, else select that frame; then offer + // the frame actions (which act on the selection). + if cr.secondary_clicked() + && let Some(p) = cr.interact_pointer_pos() + { + let f = frame_at(p.x); + if !app.frame_sel.is_some_and(|s| s.contains(&layers, i, f)) { + app.frame_sel = Some(FrameSel::cell(layer.id, f)); + select_here(app, f); + } else { + app.playing = false; + } + } + cr.context_menu(|ui| { + ui.set_min_width(220.0); + for id in ["timeline.insert_frame", "timeline.remove_frame", "timeline.insert_keyframe", "timeline.insert_blank_keyframe", "timeline.clear_keyframe"] { + menus::cmd_item(app, ui, id); + } + ui.separator(); + for id in ["timeline.cut_frames", "timeline.copy_frames", "timeline.paste_frames"] { + menus::cmd_item(app, ui, id); + } + ui.separator(); + let tween = app.s.active_layer().and_then(|l| l.keyframe_at(app.s.frame)).and_then(|k| k.tween); + match tween { + Some(t) => { + menus::cmd_item(app, ui, "timeline.remove_tween"); + ui.menu_button("Ease", |ui| { + for (name, e) in Easing::PRESETS { + if ui.selectable_label(t.easing == e, name).clicked() { + app.run("timeline.set_easing", json!({"easing": easing_param(e)})); + ui.close(); + } + } + }); + } + None => menus::cmd_item(app, ui, "timeline.create_tween"), + } + }); + painter.line_segment([row.left_bottom(), row.right_bottom()], Stroke::new(1.0, T.separator)); + } + // Layout lines: layer list | frame grid, and the header above. + painter.line_segment([pos2(grid.left(), body.top()), pos2(grid.left(), body.bottom())], Stroke::new(1.0, T.border)); + painter.line_segment([body.left_top(), body.right_top()], Stroke::new(1.0, T.border)); + + // end-of-timeline marker + let end_x = x_of(frames_total); + if end_x > grid.left() && end_x < grid.right() { + painter.line_segment([pos2(end_x, rows_top), pos2(end_x, body.bottom())], Stroke::new(1.0, T.text_faint.gamma_multiply(0.5))); + } + + // playhead + let px = x_of(app.s.frame); + if px + cell_w > grid.left() && px < grid.right() { + // The same pixel as the ruler tick for this frame. + let cx = frame_center(px, cell_w); + // The flag fits its number; it never grows with the zoom. + let label = (app.s.frame + 1).to_string(); + let tw = painter.layout_no_wrap(label.clone(), font(Type::DataSmall), Color32::WHITE).rect.width(); + let head = Rect::from_center_size(pos2(cx, ruler.center().y), vec2((tw + 8.0).max(HEAD_W), RULER_H - 4.0)); + // The frame's band, centred on the same pixel column as the line and the flag: an odd + // whole-pixel width around a half-pixel centre puts both edges on pixel boundaries, + // equally far from the line. + let band = (cell_w.round() as i32 | 1) as f32; + painter.with_clip_rect(grid).rect_filled(Rect::from_min_max(pos2(cx - band * 0.5, rows_top), pos2(cx + band * 0.5, body.bottom())), 0.0, T.playhead.gamma_multiply(0.12)); + painter.with_clip_rect(grid).line_segment([pos2(cx, ruler.bottom()), pos2(cx, body.bottom())], Stroke::new(1.5, T.playhead)); + painter.with_clip_rect(grid).rect_filled(head, T.rc(), T.playhead); + painter.with_clip_rect(grid).text(head.center(), Align2::CENTER_CENTER, label, font(Type::DataSmall), Color32::WHITE); + } + + // footer buttons for layers + let footer = Rect::from_min_max(pos2(body.left(), body.bottom() - FOOTER_H), pos2(grid.left(), body.bottom())); + if n_layers > rows_visible { + let more = format!("{}–{} of {} layers", first_row + 1, (first_row + rows_visible).min(n_layers), n_layers); + painter.text(pos2(grid.left() - 8.0, footer.top() - 4.0), Align2::RIGHT_BOTTOM, more, font(Type::Caption), color(Type::Caption)); + } + { + painter.rect_filled(footer, 0.0, T.panel_alt); + painter.line_segment([footer.left_top(), footer.right_top()], Stroke::new(1.0, T.border)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(footer.shrink2(vec2(8.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); + if child.button("+ Layer").on_hover_text("New layer").clicked() { + app.run("layer.new", json!({})); + } + if child.add_enabled(layers.len() > 1, egui::Button::new("Delete")).on_hover_text("Delete the active layer").clicked() { + app.request("layer.delete", json!({})); + } + if child.button("Up").clicked() { + app.run("layer.move_up", json!({})); + } + if child.button("Down").clicked() { + app.run("layer.move_down", json!({})); + } + } + + // Horizontal scrollbar under the frames: the thumb is the visible part of the timeline. + let bar = Rect::from_min_max(pos2(grid.left(), body.bottom() - FOOTER_H), body.right_bottom()); + painter.rect_filled(bar, 0.0, T.panel_alt); + painter.line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, T.border)); + let track = bar.shrink2(vec2(10.0, (FOOTER_H - 12.0) * 0.5)); + let content = (frames_total + 30).max(visible_cols) as f32; + let frac = (visible_cols as f32 / content).clamp(0.05, 1.0); + let thumb_w = (track.width() * frac).max(TARGET); + let travel = (track.width() - thumb_w).max(1.0); + let max_s = (content - visible_cols as f32).max(0.0); + let t = if max_s > 0.0 { (app.tl_scroll / max_s).clamp(0.0, 1.0) } else { 0.0 }; + let thumb = Rect::from_min_size(pos2(track.left() + t * travel, track.top()), vec2(thumb_w, track.height())); + let sr = ui.interact(bar, ui.id().with("tl_hscroll"), Sense::click_and_drag()); + if sr.dragged() && max_s > 0.0 { + app.tl_scroll = (app.tl_scroll + sr.drag_delta().x / travel * max_s).clamp(0.0, max_s); + } else if sr.clicked() + && let Some(p) = sr.interact_pointer_pos() + && max_s > 0.0 + { + // A click on the track pages to that spot. + app.tl_scroll = (((p.x - track.left() - thumb_w * 0.5) / travel) * max_s).clamp(0.0, max_s); + } + painter.rect_filled(track, T.rc(), T.field); + painter.rect_filled(thumb, T.rc(), if sr.hovered() || sr.dragged() { T.control_edge } else { T.hover }); + sr.on_hover_text("Scroll the timeline (or Shift+wheel anywhere over it)"); +} + +/// Engine param for an easing preset. +pub fn easing_param(e: Easing) -> serde_json::Value { + match e { + Easing::Linear => json!("Linear"), + Easing::QuadIn => json!("QuadIn"), + Easing::QuadOut => json!("QuadOut"), + Easing::QuadInOut => json!("QuadInOut"), + Easing::CubicIn => json!("CubicIn"), + Easing::CubicOut => json!("CubicOut"), + Easing::CubicInOut => json!("CubicInOut"), + Easing::Classic(s) => json!({"classic": s}), + Easing::CubicBezier(a, b, c, d) => json!({"bezier": [a, b, c, d]}), + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + fn layers(n: u64) -> Vec> { + (1..=n).map(|i| Arc::new(Layer::new(LayerId(i), format!("L{i}")))).collect() + } + + #[test] + fn the_playhead_flag_fits_at_frame_one_at_every_zoom_and_padding_stays_small() { + let left = 100.0; + let mut cw = *CELL_RANGE.start(); + while cw <= *CELL_RANGE.end() { + let pad = start_pad(cw, 0.0); + // Frame 1's centre, as the ruler and the playhead draw it. + let c = frame_center(left + pad, cw); + assert!(c - HEAD_W * 0.5 >= left - 0.5, "flag clipped at cell width {cw}: centre {c}"); + // The padding is room for the flag, not a frame's worth that grows with the zoom. + assert!(pad <= HEAD_W * 0.5 + 1.0, "pad {pad} at cell width {cw}"); + cw += 0.5; + } + assert_eq!(start_pad(48.0, 0.0), 1.0, "wide frames need only a hairline"); + assert_eq!(start_pad(48.0, 10.0), 11.0, "the preference adds points"); + } + + #[test] + fn ticks_and_the_playhead_share_a_pixel_column() { + // Same cell, same column, whatever the fractional position or width. + for (x, cw) in [(100.3, 12.0), (99.9, 7.5), (250.49, 3.0), (10.0, 47.25)] { + let c = frame_center(x, cw); + assert_eq!(c.fract(), 0.5, "centred on a pixel"); + assert!((c - (x + cw * 0.5)).abs() <= 1.0); + } + } + + #[test] + fn a_selection_spans_rows_and_frames_in_either_direction() { + let ls = layers(4); + // Dragged up and to the left. + let sel = FrameSel { anchor: (LayerId(3), 9), head: (LayerId(2), 4) }; + assert_eq!(sel.frames(), (4, 9)); + assert_eq!(sel.layers(&ls), vec![LayerId(2), LayerId(3)]); + assert!(sel.contains(&ls, 1, 4) && sel.contains(&ls, 2, 9)); + assert!(!sel.contains(&ls, 0, 5) && !sel.contains(&ls, 1, 10)); + // Each new layer has one keyframe at frame 0. + assert!(!sel.has_keys(&ls)); + assert!(FrameSel::cell(LayerId(1), 0).has_keys(&ls)); + // A deleted layer invalidates the selection. + assert!(FrameSel { anchor: (LayerId(9), 0), head: (LayerId(1), 0) }.layers(&ls).is_empty()); + } +}