diff --git a/AGENTS.md b/AGENTS.md index 5e187b89..2132c555 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009) crates/svg L2 SVG import: shapes, groups, use, styles, gradients, clips/masks → mask layers, text crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format -crates/gpu L3 wgpu stage renderer (the default stage): tile binning, compute coverage, bitmaps, filters (ADR 0019, 0031) +crates/gpu L3 wgpu stage renderer (the default stage): tile binning, compute coverage, bitmaps, filters (ADR 0019, 0029, 0032) crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve/mcp src/ L5 egui shell (app, menus, stage, timeline, panels, theme) ``` @@ -31,7 +31,10 @@ a new crate needs a row here and in its `LAYERS` table. * **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/`. + decisions as ADRs in `docs/adr/`. **ADR numbers never move:** take the next number above + every ADR and every reservation in `docs/adr/README.md`, and reserve it there in the same + PR. An open PR keeps its number until it merges or closes, so no one renumbers because + another PR merged first; maintainers reserve the numbers outside PRs already use. * **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. @@ -40,6 +43,9 @@ a new crate needs a row here and in its `LAYERS` table. (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. +* **Interface text is translatable** (ADR 0040, `docs/localisation.md`): write English through + `tr!` / `trn!` / `tr_noop!`, one template per sentence, and translate keys only where they are + drawn. Command ids, the CLI, MCP and the file format stay English. Check with `--lang pseudo`. * **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 @@ -104,8 +110,8 @@ a new crate needs a row here and in its `LAYERS` table. workspace produce artifacts with the same names, so a single shared folder lets one track's build overwrite another's and tests run against the wrong code. Before opening or updating a PR, bring in `origin/main` and keep shared files (CHANGELOG, roadmap, Cargo.lock, the - workspace map) conflict-free. ADR numbers are assigned by the lead when a task starts, so - parallel tracks never collide. A track never merges its own PR: the lead reviews it + workspace map) conflict-free. ADR numbers are reserved in `docs/adr/README.md` when a task + starts and never move (see below). A track never merges its own PR: the lead reviews it (principal engineer and senior designer) and merges it when CI is green, one at a time. * **A new command namespace** needs a plug-in policy (`plugin_may_call` in `crates/engine/src/cmds_plugin.rs`); a test fails until it has one. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8d14d0f5..0ee9d2b8 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,7 +19,7 @@ shaders or SDK code). | Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | | Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) | | emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) | -| `assets/icons/anicraft-*.svg` (16 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound) | Align panel, layer-type, Width tool, Camera, Brush, Eraser and Eyedropper tool icons, the timeline's mute toggle | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | +| `assets/icons/anicraft-*.svg` (19 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | | `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | (`icons/.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | | `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) | @@ -58,6 +58,13 @@ here. | Inter Regular | UI prose (primary) | The Inter Project Authors (Rasmus Andersson) | SIL OFL 1.1, shipped as `OFL-Inter.txt` | | JetBrains Mono Regular | UI data: timeline, readouts, values, shortcuts (primary) | The JetBrains Mono Project Authors | SIL OFL 1.1, shipped as `OFL-JetBrainsMono.txt` | +### Optional build input: craft-i18n (not files in this repo) + +Builds made with `CRAFT_I18N_DIR` (ADR 0040) embed the interface catalogs of the shared +[storytold/craft-i18n](https://github.com/storytold/craft-i18n) repository +(`locales//common.tsv` and `anicraft.tsv`), MIT OR Apache-2.0, by its translators +(credited in its own `ATTRIBUTION.md`). No catalog file is committed here. + No font *files* are committed. Every committed image, icon and sound (the two tiny test sounds) is listed above; everything else is either embedded by a dependency crate or generated by our code. @@ -72,6 +79,8 @@ OR Apache-2.0) is noted in the table. |---|---|---|---| | Signed-area coverage accumulation rasterizer | `crates/render/src/raster.rs` | Raph Levien, *font-rs* (2016), , Apache-2.0; also stb_truetype v2 (public domain) | Our implementation follows the published accumulate-and-prefix-sum approach. Credited here; Apache-2.0 includes a patent licence. | | Tile binning with per-row backdrops; per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019). | +| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), , Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. | +| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). | | Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | | | Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. | | Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs`, `crates/gpu/src/fine.wgsl` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. | @@ -80,6 +89,7 @@ OR Apache-2.0) is noted in the table. | Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). | | Bevel and gradient filters in SVG export (`feComposite` arithmetic, `feComponentTransfer` tables) | `crates/render/src/svg.rs` | W3C Filter Effects Module Level 1 / SVG 1.1 filters | W3C Royalty-Free Patent Policy. | | Timeline playback semantics for actions (stop, play, go to frame or label, next/previous frame and scene; button Up/Over/Down/Hit states; mouse events) | `crates/actions`, `crates/doc/src/player.rs` | Behaviour learned from Adobe's public *ActionScript 3.0 Reference* (`MovieClip`, `SimpleButton`, `MouseEvent`) and the public Animate user guide on buttons, plus observation (ADR 0013, ADR 0024) | Clean room: no Adobe code, SDKs or players; names used nominatively. | +| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the action IR | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `EventDispatcher.addEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. | | Cubic-Bézier easing (CSS model) | `crates/doc/src/easing.rs` | W3C CSS Easing Functions Level 1 | W3C Royalty-Free Patent Policy. | | SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. | | Marching-squares contour tracing (Paint Bucket regions, Brush outlines) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. | @@ -95,10 +105,13 @@ OR Apache-2.0) is noted in the table. | Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | | | Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. | | Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). | +| Stroke caps, joins, miter limit and dash patterns (`butt`/`square` caps, miter length and limit, dash arrays restarting per subpath, zero-length round-capped dashes as dots) | `crates/doc/src/stroke_style.rs`, `crates/render/src/stroke.rs`, SVG/HTML/Lottie export, `crates/svg` | W3C SVG 1.1 §11.4 and SVG 2 / CSS Fill and Stroke Module Level 3 (stroke properties); WHATWG HTML canvas line styles; the public Lottie JSON schema (`lc`, `lj`, `ml`, `d`); public descriptions of XFL `SolidStroke`/`DashedStroke`/`DottedStroke` attributes | W3C Royalty-Free Patent Policy; open specifications. | | Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. | | Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. | | Eraser (the swept tip as a fill in the planar merge whose regions are dropped; exact fill areas by Green's theorem with five-point Gauss–Legendre quadrature) and Eyedropper | `crates/engine/src/cmds_erase.rs`, `crates/engine/src/cmds_paint.rs` | Green's theorem and Gauss–Legendre quadrature (public mathematical results); behaviour of Animate's Eraser and Eyedropper learned from Adobe's public help and observation | Own implementation (ADR 0034); no Adobe code or presets. | | WebAssembly plug-in host (module validation, limits, fuel, resumable host calls) | `crates/plugins` | W3C WebAssembly Core Specification 1.0 / 2.0 (W3C Royalty-Free Patent Policy); the `wasmi` interpreter (MIT OR Apache-2.0) | Host model ported from PhotoCraft's filter plug-ins (same project family and licence) and extended with the AniCraft request ABI (ADR 0017). | +| Selection tool on raw shapes: bending an edge (least-squares control-point move), following a bent edge in every shape that shares it, snapping, a marquee that cuts | `crates/geom/src/raw.rs`, `crates/geom/src/planar.rs`, `crates/engine/src/cmds_raw.rs` | Bernstein polynomials and least squares (public mathematical results); behaviour of Animate's Selection tool learned from issue #42, Adobe's public help and observation | Own implementation (ADR 0041); no Adobe code. | +| Inverse kinematics by cyclic coordinate descent (bone drags, `bone.solve`), with joint limits as a clamp per step | `crates/doc/src/armature.rs` | L.-C. T. Wang and C. C. Chen, *A combined optimization method for solving the inverse kinematics problem of mechanical manipulators*, IEEE Trans. Robotics and Automation 7(4), 1991; C. Welman, *Inverse Kinematics and Geometric Constraints for Articulated Figure Manipulation*, MSc thesis, Simon Fraser University, 1993 | Published algorithm; own implementation (ADR 0043). | | De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | | | WAV (RIFF WAVE) reading and writing: PCM 8/16/24/32-bit, IEEE float, `WAVE_FORMAT_EXTENSIBLE` | `crates/audio/src/wav.rs` | Microsoft/IBM, *Multimedia Programming Interface and Data Specifications 1.0* (1991), and Microsoft's public `WAVE_FORMAT_EXTENSIBLE` description | Public file format descriptions. | | Resampling by cubic Hermite (Catmull-Rom) interpolation | `crates/audio/src/mix.rs` | E. Catmull and R. Rom, *A class of local interpolating splines* (1974); R. Keys, *Cubic convolution interpolation for digital image processing* (1981) | Public mathematical results. | diff --git a/CHANGELOG.md b/CHANGELOG.md index ed6f70a4..19a9b140 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,195 @@ ## Unreleased +* **Motion path points pinned to frames** (ADR 0049, M2). As in Animate, a motion tween's + position keyframes are now points on its path: move the object at a frame and the path gets a + point there that the object passes exactly on that frame, whatever else you do to the path. + * Moving the object between the ends adds a pinned point where you put it; after the last + position keyframe the path carries on to the new place. The eases on X and Y time the + object between pinned points as they did between the ends. + * Pinned points are diamonds with their frame number on the stage, and Selection can drag + them. With Subselection, right-click any point to **Pin to Frame** (the playhead's frame) + or **Unpin**. Properties › Frame has **Pin Here** / **Unpin**, and F6 inside a path tween + pins where the object is. + * The Motion Editor draws a pinned frame's X and Y keys in blue; dragging one moves its + point. The timeline marks pinned frames with a larger diamond. + * Adding and deleting points keeps the pins on their points; deleting a pinned point, or + unpinning it, removes its frame's X and Y keys and the motion flows as before. + * Older files open and play exactly as they did (only the ends are pinned). + * Headless: new `motion.pin_point` and `motion.unpin_point`; `motion.info` and the path + commands report `pins`. + +* **Stroke caps, joins, miter limit, and dashed and dotted lines** (ADR 0046, M7). Properties › + Stroke has Animate's rows: **Style** (Solid, Dashed with a dash and gap editor, Dotted with + dot spacing), **Cap** (None, Round, Square), **Join** (Miter, Round, Bevel) and **Miter** + (the limit past which corners are bevelled). The drawing tools' options set them for new + strokes, the Ink Bottle gives them and the Eyedropper picks them. + * Drawn exactly by the CPU renderer and the GPU stage: butt and square caps, miter joins with + their limit, dashes by arc length along curves (restarting on each subpath, an offset into + the pattern), round dots one width across, and dashes that keep a width profile's widths. + Patterns finer than a pixel draw solid and lighter. No slower than round strokes. + * SVG, HTML canvas and Lottie export write caps, joins, miter limit and dashes; SVG import + reads `stroke-linecap`, `stroke-linejoin`, `stroke-miterlimit`, `stroke-dasharray` and + `stroke-dashoffset`; Animate documents bring their caps, joins, miter limit, dashed and + dotted strokes (ragged, stipple and hatched strokes are drawn solid and reported). + * Merge drawing keeps a dashed line's style on every piece it is cut into; shape tweens blend + miter limits and dash lengths. Older files open unchanged. + * Headless: new `stroke.set_style`; `cap`, `join`, `miter`, `style`, `dash`, `dash_offset` + and `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. +* **Onion skin controls and Edit Multiple Frames** (ADR 0047, M1). Onion skin works as Animate + users expect: + * **Markers** on the frame ruler: drag the start and end brackets to choose how many frames + show before and after the playhead. The onion menu (the arrow next to the timeline's onion + buttons, a right-click on the ruler, or View › Onion Skin Options) has Always Show Markers, + Anchor Markers (they stay put when the playhead moves), and the Onion 2, Onion 5 and Onion + All presets. + * Frames before the playhead are tinted blue and frames after it green, each fainter the + farther it is. Pick your own colours or turn tinting or fading off in the menu; **Outlines** + draws onion frames as outlines only, and **Keyframes Only** shows only keyframes. Your + choices are remembered. + * Onion frames now show over a background layer (they used to be hidden under it), and locked + layers are left out, as in Animate. + * **Edit Multiple Frames** (the timeline button next to Onion Skin) shows every keyframe + between the markers at full strength. Click, Shift-click, marquee or Select All to select + artwork on all of them, then drag it or use the arrow keys to move it everywhere at once: + one undo step. A motion tween's path moves with its object. + * Headless: `frames.artwork` lists the artwork on those keyframes and + `frames.edit_multiple` moves it. +* **ActionScript that controls the timeline now runs** (ADR 0013 tier 2). Frame scripts in + Animate documents, and ones you type in the Actions panel, play in Test Movie and in the + HTML canvas export when they use the ActionScript 3.0 most animation and e-learning files + use: `stop()`, `play()`, `gotoAndPlay`/`gotoAndStop` by frame or label (and scene), + `nextFrame()`, `prevFrame()`, `nextScene()`, `prevScene()`, on this timeline or on named + instances (`hero_mc.gotoAndStop("run")`, `MovieClip(parent).play()`); button and movie clip + listeners (`btn.addEventListener(MouseEvent.CLICK, onClick)` for click, mouse down and up, + roll over and out, with a named or inline function); `trace`; and setting `x`, `y`, + `alpha`, `visible`, `rotation`, `scaleX` and `scaleY`. + * A script runs whole or not at all. Anything else (variables, `if`, loops, reading + properties) keeps it from running, and AniCraft says where: the Script view lists each + problem with its line and column above the code and marks the lines (click one to go + there), or says the script runs. Test Movie's Output begins with which scripts run and + which don't, and why. + * `navigateToURL` and other calls that reach outside the movie are ignored and noted. + * The XFL import report lists the frame scripts that run apart from those only kept. + * Headless: `script.set` and `script.list` say `runs` and `problems`; new `script.check` + compiles a text without storing it. A new XFL corpus package, `interactive`, plays its + ActionScript through the player. +* **Selection across layers** (ADR 0044, issue #42, M1). A selection can hold artwork on several + layers, as in Animate: + * The Selection tool's **marquee** selects on every visible, unlocked layer, cutting raw fills + and lines at its edges on each layer (and taking the cut back when you let go of it). + **Shift-click** adds or removes artwork on any layer; **Select All** (Ctrl+A) takes every + unlocked layer. Locked and hidden layers are never selected; locking or hiding a layer lets + go of what was selected on it. + * Move, nudge, delete, duplicate, arrange (within each layer), transforms, alpha, fill and + stroke, filters, blending, break apart and width profiles act on every selected layer, one + undo step per gesture. Inside a tween each layer gets its own keyframe. + * Align and distribute work across the layers; Free Transform's box covers the whole + selection; copy keeps each layer's artwork apart, and paste puts it back on those layers + (or on the active layer and the ones below, creating missing layers in another document). + * **Convert to Symbol** (F8) of a selection on several layers keeps those layers inside the + symbol and places the instance on the topmost of them. + * The **timeline** shows a square in the layer's colour after the name of every layer with + selected artwork. **Properties** says "6 elements on 4 layers", shows the combined box's + position, and marks values that differ as "mixed". + * Headless: `element.select` takes ids on any layer (and `layer?`); `doc.info` reports + `selection_layers`; per-layer commands report the `layers` they ran on. + * Clicking a layer's name in the timeline selects all of its artwork at the playhead and + makes it active, as in Animate (`layer.select {select: true}`). + * Not yet: "mixed" on every Properties row. + +* **Interface languages** (ADR 0040, first slice; `docs/localisation.md`). Every string the + window shows, and every name a screen reader announces, can now be translated. + * Preferences › Appearance › **Language**: *System language* by default, or any language + this build has, named in itself. A change shows at once. `--lang ` sets it for one + run. + * Translations come from the Craft family's shared **craft-i18n** catalogs, built in with + `CRAFT_I18N_DIR`; a missing one shows the English. craft-i18n has no AniCraft catalog yet, + so builds are English for now: `scripts/i18n-extract.sh` lists every string for + translators (and, with a craft-i18n checkout, how much each language already covers). + * A **pseudo-locale** (`--lang pseudo`) draws everything accented, longer and bracketed, to + find text that skipped translation or gets cut off. + * Messages that say how to undo show your Undo key as this computer writes it (⌘Z on a + Mac, and a rebound key wherever it is), instead of a fixed "Ctrl+Z". + * Menus, the command palette and the shortcut sheet translate the command registry's labels + as they are drawn; command ids, `.anicraft` files, `anicraft-cli` and MCP stay English. + * For developers: `tr!`, `trn!` (plurals by CLDR rules), `trc!` and `tr_noop!`; a test fails + on new interface text that skips them. Not yet: engine messages, right-to-left languages + (egui can't lay them out yet), Chinese, Japanese and Korean (need a font). + +* **Bone tool and inverse kinematics, first slice** (ADR 0043, M7). Join symbol instances into + an armature and pose it: + * With the **Bone tool** (M), drag from one symbol instance to another: a bone joins them and + both move to a new **armature layer** (bone icon in the timeline). Drag from a bone's end to + the next instance to continue the chain; drag from any instance of the armature to branch. + * Bones show on the stage as wedges from their round joint to their end, in the armature + layer's colour; click one to select it (selection colour). + * With the **Selection tool**, drag a bone or an instance to pose the armature by inverse + kinematics: the bones above it turn so it follows the pointer; an unreachable point leaves + the chain stretched straight toward it. Drag the root instance to move the whole armature. + Each drag is one undo step. + * A pose at another frame keys it; poses tween with the span's easing and are exact at their + keyframes. Every export, the GPU stage and Test Movie show them. + * **Properties › Bone**: the joint angle at the playhead, Constrain rotation with min and + max (kept in every pose), Pin (the bone and those it hangs from stay put while you drag + below it), and Remove Bone (also Delete). Removing frees the instances where they are, on + a layer of their own; it asks first when the armature has more than one pose. + * Headless: `bone.add`, `bone.remove`, `bone.set_limits`, `bone.pin`, `bone.pose`, + `bone.solve` (IK) and `bone.info`; plug-ins may call them. A 64-bone chain solves in about + 5 ms from rest. + * Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import of + armature layers, editing armature members' colour effects in place. + +* **Subselection on raw drawings, Snap to Objects, and merging everywhere** (ADR 0042, issue + #42). With Object Drawing off: + * Click a raw line or fill with the **Subselection tool** (A) to see the points of everything + connected to it: hollow squares, one per shared corner. Click a point to select it (Shift + adds or removes). The curve handles of the selected points, and of the edge you clicked, + show as lines ending in dots. + * Drag a point to move it together with the other selected points; every shape that shares + a point moves with it, and it snaps as with the Selection tool. Drag a handle to change the + curve; a fill and its outline change together. + * Drag a line or fill to move everything connected to it. A marquee shows the shapes it + touches on the active layer and selects the points inside it. Arrow keys move the selected + points 1 screen pixel (Shift: 10). Each drag or press is one undo step. + * **Snap to Objects**, in View › Snapping, as the magnet under the tools and in the + selection tools' options, turns snapping on and off. It is on by default. + * **The Paint Bucket** fills a raw drawing exactly up to its lines and fill edges, and the + fill joins any fill of its colour it touches. Recolouring a fill joins it to its new + colour's neighbours. + * **Pasted** raw shapes (Paste and Paste in Place) cut and join the drawing they land on. + * **Animate files**: raw shapes open as raw shapes, merged into one drawing per keyframe. + Drawing objects and groups stay objects. + * **Gradient and bitmap fills** now merge like solid ones, each piece keeping its part of the + gradient. Strokes with a width profile are still drawn as objects. + + Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on + `raw.move_point`, `draw.snap_to_objects`, and `object` on `paint.bucket`; plug-ins may call + them. + +* **The Selection tool on raw drawings** (ADR 0041, issue #42). With Object Drawing off, the + Selection tool now edits raw strokes and fills the way Animate does: + * Drag an unselected line or the edge of a fill to **bend** it. The segment becomes a curve + through the point you drag, its ends stay put, and a fill under an outline (or next to it) + bends with it. Straight lines stay straight until you drag them. + * Drag an unselected **corner or end** to move it. Every raw shape that shares the point + moves with it, so the drawing stays joined; where a line ends on an edge, the edge moves + too. + * Drag a fill to move only that fill, not its outline. Drag anything selected to move the + selection. + * A small corner or curve mark next to the pointer shows what a drag will do. + * Dragged points and selections **snap** to corners, ends, lines and fill edges within 10 + screen pixels, at any zoom, with a ring where they snap. Arrow-key nudges join ends within + 0.2 px at their midpoint, and an end that comes within 0.2 px of a line goes onto it + without changing the line. + * The **marquee** selects the parts of raw fills and lines under it, cut at its edges, and + objects wholly inside it; Shift adds more. If you click away without changing them, the + drawing is whole again: selecting is never an undo step and leaves a saved file saved. + * Each drag is one undo step, and what it changed merges again when you let go. + + Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, + and `snap`/`from` on `element.translate`; plug-ins may call them. + * **Sound effects, layer volume and sounds inside symbols** (ADR 0039, M5 second slice). * Properties › Sound has an **Effect**, as in Animate: Left channel, Right channel, Fade left to right, Fade right to left, Fade in and Fade out, shaped over the time the sound is diff --git a/Cargo.lock b/Cargo.lock index eeee024e..695d6fde 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -223,6 +223,7 @@ dependencies = [ "rfd", "serde", "serde_json", + "sys-locale", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -3810,6 +3811,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "tag_ptr" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 2b2bc8ad..15bb9237 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -98,6 +98,8 @@ fontdb.workspace = true anicraft-audio.workspace = true serde_json.workspace = true web-time.workspace = true +# The system's interface language, for the default language (ADR 0040; MIT OR Apache-2.0). +sys-locale = "0.3" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] eframe.workspace = true @@ -114,6 +116,8 @@ eframe = { version = "0.36", default-features = false, features = ["accesskit", wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" +# In the browser the page's language (navigator.languages) is the system's. +sys-locale = { version = "0.3", features = ["js"] } web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] } [build-dependencies] diff --git a/README.md b/README.md index 2f12e70f..1770b5e9 100644 --- a/README.md +++ b/README.md @@ -194,8 +194,8 @@ The details, including the server entry for other MCP clients, are in [`docs/mcp [**docs/roadmap.md**](docs/roadmap.md) has the honest status by dimension, milestones M0–M8 and what's next. -**What's missing:** audio layers, ActionScript (frame scripts are counted -on import but not kept yet, ADR 0013), motion tweens from XFL, a GPU renderer, and macOS and Linux CI runners +**What's missing:** audio layers, ActionScript beyond the timeline subset (frame scripts +are kept, and those that control the timeline run; ADR 0013), motion tweens from XFL, a GPU renderer, and macOS and Linux CI runners (AniCraft is verified on Windows so far). **Workspace:** strict downward-only layering, checked by `cargo test`: diff --git a/assets/icons/anicraft-bone.svg b/assets/icons/anicraft-bone.svg new file mode 100644 index 00000000..f0cb8553 --- /dev/null +++ b/assets/icons/anicraft-bone.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-edit-multiple.svg b/assets/icons/anicraft-edit-multiple.svg new file mode 100644 index 00000000..fa1e9281 --- /dev/null +++ b/assets/icons/anicraft-edit-multiple.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-magnet.svg b/assets/icons/anicraft-magnet.svg new file mode 100644 index 00000000..976b3c0a --- /dev/null +++ b/assets/icons/anicraft-magnet.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/build.rs b/build.rs index 02e5873b..fbd5c89c 100644 --- a/build.rs +++ b/build.rs @@ -1,10 +1,13 @@ -//! Optional font build input (the Craft family convention, as in PhotoCraft), and the app icon +//! Optional build inputs (the Craft family convention, as in PhotoCraft), and the app icon //! embedded in the Windows executable. //! //! `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. +//! +//! `CRAFT_I18N_DIR=` embeds the interface catalogs (ADR 0040); without it +//! the interface is English. Neither repository is ever a Cargo dependency. use std::path::{Path, PathBuf}; @@ -123,8 +126,92 @@ fn main() { } } 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"); + let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); + let out = out_dir.join("fonts.rs"); if let Err(e) = std::fs::write(&out, code) { println!("cargo:warning=could not write {}: {e}", out.display()); } + let out = out_dir.join("craft_i18n.rs"); + if let Err(e) = std::fs::write(&out, craft_i18n()) { + println!("cargo:warning=could not write {}: {e}", out.display()); + } +} + +/// AniCraft's own catalog in a craft-i18n locale: `locales//anicraft.tsv`. +const APP_CATALOG: &str = "anicraft.tsv"; + +/// `CRAFT_I18N` (ADR 0040), as craft-i18n's `docs/integration.md` describes: one +/// `(locale, common.tsv, anicraft.tsv)` entry per locale with AniCraft's own catalog, and the +/// base language of a regional one (`pt` for `pt-br`) so it can fall back, embedded with +/// `include_str!`. Without `CRAFT_I18N_DIR` the list is empty and the interface is English. +/// `CRAFT_I18N_REQUIRED=1` makes a missing or empty checkout an error (for releases). +fn craft_i18n() -> String { + println!("cargo:rerun-if-env-changed=CRAFT_I18N_DIR"); + let required = required("CRAFT_I18N_REQUIRED"); + let entries = match std::env::var_os("CRAFT_I18N_DIR").filter(|d| !d.is_empty()) { + // Not canonicalized: on Windows that gives `\\?\C:\…`. + Some(dir) => i18n_locales(&PathBuf::from(dir).join("locales")).unwrap_or_else(|e| { + if required { + fail(&format!("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR: {e}")); + } + println!("cargo:warning=CRAFT_I18N_DIR: {e}; the interface is English only"); + Vec::new() + }), + None => { + if required { + fail("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR is not set"); + } + Vec::new() + } + }; + let mut code = String::from("// Generated by build.rs (CRAFT_I18N_DIR catalog input).\npub static CRAFT_I18N: &[(&str, &str, &str)] = &[\n"); + let include = |p: &Option| p.as_ref().map_or_else(|| "\"\"".to_string(), |p| format!("include_str!({:?})", p.display().to_string())); + for (locale, common, app) in entries { + code.push_str(&format!(" ({locale:?}, {}, {}),\n", include(&common), include(&app))); + } + code.push_str("];\n"); + code +} + +/// `(locale, common.tsv, anicraft.tsv)` for every locale under `dir` with AniCraft's catalog, +/// and for the base language of each regional one. +type I18nEntry = (String, Option, Option); + +fn i18n_locales(dir: &Path) -> Result, String> { + // `include_str!` resolves a relative path against the generated file, not this crate. + if !dir.is_absolute() { + return Err(format!("{} is not an absolute path", dir.display())); + } + let list = std::fs::read_dir(dir).map_err(|e| format!("{} is not a craft-i18n checkout ({e})", dir.display()))?; + println!("cargo:rerun-if-changed={}", dir.display()); + let file = |locale: &str, name: &str| Some(dir.join(locale).join(name)).filter(|p| p.is_file()); + let mut wanted: Vec = Vec::new(); + for path in list.flatten().map(|e| e.path()) { + let Some(locale) = path.file_name().and_then(|n| n.to_str()).map(str::to_ascii_lowercase) else { continue }; + if !path.join(APP_CATALOG).is_file() { + continue; + } + // A regional locale (last subtag two letters or three digits) falls back to its base. + if let Some((base, region)) = locale.rsplit_once('-') + && ((region.len() == 2 && region.chars().all(|c| c.is_ascii_alphabetic())) || (region.len() == 3 && region.chars().all(|c| c.is_ascii_digit()))) + && dir.join(base).is_dir() + { + wanted.push(base.to_string()); + } + wanted.push(locale); + } + wanted.sort(); + wanted.dedup(); + if wanted.is_empty() { + return Err(format!("{} has no locale with {APP_CATALOG} yet", dir.display())); + } + let mut out = Vec::new(); + for locale in wanted { + let (common, app) = (file(&locale, "common.tsv"), file(&locale, APP_CATALOG)); + for p in common.iter().chain(app.iter()) { + println!("cargo:rerun-if-changed={}", p.display()); + } + out.push((locale, common, app)); + } + Ok(out) } diff --git a/crates/actions/src/as3/lex.rs b/crates/actions/src/as3/lex.rs new file mode 100644 index 00000000..2fc83245 --- /dev/null +++ b/crates/actions/src/as3/lex.rs @@ -0,0 +1,244 @@ +//! The lexer: source text to tokens with their line and column (ECMA-262 3rd edition §7, with +//! ActionScript 3.0's extra punctuators). Bounded: it stops with a problem after +//! [`super::MAX_TOKENS`] tokens. + +use super::{MAX_TOKENS, Pos, Problem}; + +/// A token's kind. +#[derive(Clone, Debug, PartialEq)] +pub enum Tok { + /// An identifier or a keyword (the parser tells them apart). + Name(String), + Num(f64), + Str(String), + /// A punctuator, as written (`(`, `===`, `>>>=`, …). + Punct(&'static str), + Eof, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Token { + pub tok: Tok, + pub pos: Pos, + /// A line break comes before it (for semicolon insertion). + pub nl: bool, +} + +/// Longest first, so the scan takes the longest punctuator that matches. +const PUNCTS: [&str; 54] = [ + ">>>=", "...", "===", "!==", ">>>", "<<=", ">>=", "&&=", "||=", "::", "..", "==", "!=", "<=", ">=", "&&", "||", "++", "--", "<<", ">>", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", ".<", "{", "}", "(", ")", "[", "]", ";", ",", "<", ">", "+", "-", "*", "/", "%", "&", "|", "^", "!", "~", "?", ":", "=", ".", +]; + +fn ident_start(c: char) -> bool { + c.is_alphabetic() || c == '_' || c == '$' +} + +fn ident_part(c: char) -> bool { + c.is_alphanumeric() || c == '_' || c == '$' +} + +struct Lexer<'a> { + src: &'a str, + /// Byte offset of the next character. + at: usize, + line: u32, + col: u32, +} + +impl Lexer<'_> { + fn peek(&self) -> Option { + self.src.get(self.at..).and_then(|s| s.chars().next()) + } + + fn peek2(&self) -> Option { + self.src.get(self.at..).and_then(|s| s.chars().nth(1)) + } + + fn pos(&self) -> Pos { + Pos { line: self.line, column: self.col } + } + + /// Takes one character; a CR LF pair counts as one line break. + fn bump(&mut self) -> Option { + let c = self.peek()?; + self.at += c.len_utf8(); + match c { + '\r' if self.peek() == Some('\n') => {} + '\n' | '\r' | '\u{2028}' | '\u{2029}' => { + self.line = self.line.saturating_add(1); + self.col = 1; + } + _ => self.col = self.col.saturating_add(1), + } + Some(c) + } + + /// Skips white space and comments; `true` when a line break was among them. + fn skip(&mut self) -> Result { + let mut nl = false; + loop { + match self.peek() { + Some('\n' | '\r' | '\u{2028}' | '\u{2029}') => { + nl = true; + self.bump(); + } + Some(c) if c.is_whitespace() || c == '\u{feff}' => { + self.bump(); + } + Some('/') if self.peek2() == Some('/') => { + while self.peek().is_some_and(|c| !matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')) { + self.bump(); + } + } + Some('/') if self.peek2() == Some('*') => { + let start = self.pos(); + self.bump(); + self.bump(); + loop { + match self.bump() { + None => return Err(Problem::at(start, "this comment is never closed (a `*/` is missing)")), + Some('*') if self.peek() == Some('/') => { + self.bump(); + break; + } + Some('\n' | '\r' | '\u{2028}' | '\u{2029}') => nl = true, + Some(_) => {} + } + } + } + _ => return Ok(nl), + } + } + } + + fn number(&mut self, start: Pos) -> Result { + let from = self.at; + if self.peek() == Some('0') && matches!(self.peek2(), Some('x' | 'X')) { + self.bump(); + self.bump(); + let mut v = 0f64; + let mut digits = 0; + while let Some(d) = self.peek().and_then(|c| c.to_digit(16)) { + v = v * 16.0 + f64::from(d); + digits += 1; + self.bump(); + } + if digits == 0 { + return Err(Problem::at(start, "a hexadecimal number needs digits after `0x`")); + } + if self.peek().is_some_and(ident_part) { + return Err(Problem::at(self.pos(), "a number can't run straight into a name")); + } + return Ok(v); + } + while self.peek().is_some_and(|c| c.is_ascii_digit()) { + self.bump(); + } + if self.peek() == Some('.') && self.peek2().is_none_or(|c| c != '.') { + self.bump(); + while self.peek().is_some_and(|c| c.is_ascii_digit()) { + self.bump(); + } + } + if matches!(self.peek(), Some('e' | 'E')) { + let save = (self.at, self.line, self.col); + self.bump(); + if matches!(self.peek(), Some('+' | '-')) { + self.bump(); + } + if !self.peek().is_some_and(|c| c.is_ascii_digit()) { + (self.at, self.line, self.col) = save; + return Err(Problem::at(self.pos(), "a number's exponent needs digits")); + } + while self.peek().is_some_and(|c| c.is_ascii_digit()) { + self.bump(); + } + } + if self.peek().is_some_and(ident_part) { + return Err(Problem::at(self.pos(), "a number can't run straight into a name")); + } + let text = self.src.get(from..self.at).unwrap_or("0"); + text.parse::().map_err(|_| Problem::at(start, "this isn't a number")) + } + + fn string(&mut self, quote: char, start: Pos) -> Result { + self.bump(); + let mut s = String::new(); + loop { + let here = self.pos(); + match self.bump() { + None | Some('\n' | '\r' | '\u{2028}' | '\u{2029}') => return Err(Problem::at(start, "this string is never closed (its quote is missing on this line)")), + Some(c) if c == quote => return Ok(s), + Some('\\') => match self.bump() { + None => return Err(Problem::at(start, "this string is never closed")), + Some('n') => s.push('\n'), + Some('t') => s.push('\t'), + Some('r') => s.push('\r'), + Some('b') => s.push('\u{8}'), + Some('f') => s.push('\u{c}'), + Some('v') => s.push('\u{b}'), + Some('0') if !self.peek().is_some_and(|c| c.is_ascii_digit()) => s.push('\0'), + Some('x') => s.push(self.hex(2, here)?), + Some('u') => s.push(self.hex(4, here)?), + // A backslash before a line break continues the string on the next line. + Some('\n' | '\u{2028}' | '\u{2029}') => {} + Some('\r') => { + if self.peek() == Some('\n') { + self.bump(); + } + } + Some(c) => s.push(c), + }, + Some(c) => s.push(c), + } + } + } + + fn hex(&mut self, n: usize, at: Pos) -> Result { + let mut v = 0u32; + for _ in 0..n { + let d = self.peek().and_then(|c| c.to_digit(16)).ok_or_else(|| Problem::at(at, "this escape needs hexadecimal digits"))?; + v = v * 16 + d; + self.bump(); + } + char::from_u32(v).ok_or_else(|| Problem::at(at, "this escape isn't a character")) + } +} + +/// The tokens of `src`, ending with [`Tok::Eof`]. +pub fn tokens(src: &str) -> Result, Problem> { + let mut lx = Lexer { src, at: 0, line: 1, col: 1 }; + let mut out = Vec::new(); + loop { + let nl = lx.skip()?; + let pos = lx.pos(); + if out.len() >= MAX_TOKENS { + return Err(Problem::at(pos, format!("the script is longer than {MAX_TOKENS} tokens"))); + } + let Some(c) = lx.peek() else { + out.push(Token { tok: Tok::Eof, pos, nl: true }); + return Ok(out); + }; + let tok = if ident_start(c) { + let from = lx.at; + while lx.peek().is_some_and(ident_part) { + lx.bump(); + } + Tok::Name(src.get(from..lx.at).unwrap_or_default().to_string()) + } else if c.is_ascii_digit() || (c == '.' && lx.peek2().is_some_and(|d| d.is_ascii_digit())) { + Tok::Num(lx.number(pos)?) + } else if c == '"' || c == '\'' { + Tok::Str(lx.string(c, pos)?) + } else { + let rest = src.get(lx.at..).unwrap_or_default(); + let Some(p) = PUNCTS.iter().find(|p| rest.starts_with(**p)) else { + return Err(Problem::at(pos, format!("unexpected character {c:?}"))); + }; + for _ in 0..p.chars().count() { + lx.bump(); + } + Tok::Punct(p) + }; + out.push(Token { tok, pos, nl }); + } +} diff --git a/crates/actions/src/as3/lower.rs b/crates/actions/src/as3/lower.rs new file mode 100644 index 00000000..6597f57a --- /dev/null +++ b/crates/actions/src/as3/lower.rs @@ -0,0 +1,609 @@ +//! Lowering: the syntax tree to the action IR. It accepts only what it can say exactly in the +//! IR and reports everything else where it is, so a script either runs whole or not at all. + +use super::parse::{E, Expr, Func, S, Stmt}; +use super::{Compiled, Listener, MAX_INLINE_DEPTH, MAX_LISTENERS, MAX_PROBLEMS, Pos, Problem, ScriptOp}; +use crate::{Action, ButtonEvent, FrameRef, MAX_ACTIONS, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property, Target, valid_instance_name}; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// The timeline methods a script may call (on this timeline or on a named instance). +const METHODS: [&str; 8] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene"]; +/// Names a script's own function can't take: they would hide the timeline's methods. +const BUILTINS: [&str; 11] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene", "trace", "addEventListener", "removeEventListener"]; +/// Calls that would reach outside the movie: ignored, and noted. +const OUTSIDE: [&str; 4] = ["navigateToURL", "sendToURL", "fscommand", "fsCommand"]; +/// Type casts that leave an instance path as it is (`MovieClip(parent)`). +const CASTS: [&str; 7] = ["MovieClip", "Object", "Sprite", "DisplayObject", "DisplayObjectContainer", "InteractiveObject", "SimpleButton"]; + +/// A constant value, as ActionScript computes it. +#[derive(Clone, Debug, PartialEq)] +enum Val { + Num(f64), + Str(String), + Bool(bool), + Null, + Undefined, +} + +impl Val { + fn number(&self) -> f64 { + match self { + Val::Num(n) => *n, + Val::Bool(b) => f64::from(u8::from(*b)), + Val::Null => 0.0, + Val::Undefined => f64::NAN, + Val::Str(s) => { + // ECMA-262 §9.3.1: a decimal number with optional sign and exponent (Rust would + // also read "inf" and "nan"). + let t = s.trim(); + match t.trim_start_matches(['+', '-']) { + "" if t.is_empty() => 0.0, + "Infinity" => if t.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY }, + u if u.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-')) => t.parse().unwrap_or(f64::NAN), + _ => f64::NAN, + } + } + } + } + + fn text(&self) -> String { + match self { + Val::Num(n) => number_text(*n), + Val::Str(s) => s.clone(), + Val::Bool(b) => b.to_string(), + Val::Null => "null".into(), + Val::Undefined => "undefined".into(), + } + } +} + +/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without +/// a point, exponents outside 1e-6 … 1e21. +pub(super) fn number_text(n: f64) -> String { + if n.is_nan() { + return "NaN".into(); + } + if n.is_infinite() { + return if n > 0.0 { "Infinity".into() } else { "-Infinity".into() }; + } + if n == 0.0 { + return "0".into(); + } + let a = n.abs(); + if (1e-6..1e21).contains(&a) { + return format!("{n}"); + } + let s = format!("{n:e}"); + match s.split_once('e') { + Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"), + _ => s, + } +} + +/// Where lowering is. +#[derive(Clone, Default)] +struct Cx { + /// Inside a listener's function: its event parameter and the instance it listens on (what + /// `e.currentTarget` is). + event: Option<(String, Vec)>, + /// Inside a listener (or a function it calls): listeners can't be added there yet. + in_listener: bool, + /// Inside a function body (functions can't be declared there). + in_function: bool, + /// The parameters of the function being lowered (they can't be read). + params: Vec, + /// The script's functions being lowered, innermost last (to refuse recursion). + stack: Vec, +} + +struct Lower<'a> { + funcs: BTreeMap<&'a str, &'a Func>, + problems: Vec, + notes: Vec, + listeners: usize, + /// Statements lowered so far, counting each inlined copy (calls can fan out). + work: usize, +} + +/// Most statements lowered for one script, inlined copies included. +const MAX_WORK: usize = 100_000; + +/// Whether the statement list ended in a `return`. +type Returned = bool; + +impl<'a> Lower<'a> { + fn problem(&mut self, pos: Pos, msg: impl Into) { + if self.problems.len() < MAX_PROBLEMS * 4 { + self.problems.push(Problem::at(pos, msg)); + } + } + + fn note(&mut self, pos: Pos, msg: impl Into) { + if self.notes.len() < MAX_PROBLEMS * 4 { + self.notes.push(Problem::at(pos, msg)); + } + } + + fn stmts(&mut self, list: &'a [Stmt], cx: &Cx, out: &mut Vec) -> Returned { + for s in list { + if self.stmt(s, cx, out) { + return true; + } + } + false + } + + fn stmt(&mut self, s: &'a Stmt, cx: &Cx, out: &mut Vec) -> Returned { + self.work += 1; + if self.work > MAX_WORK { + if self.work == MAX_WORK + 1 { + self.problem(s.pos, format!("the script's functions call each other into more than {MAX_WORK} statements")); + } + return true; + } + match &s.kind { + S::Empty | S::Import => {} + // Declared functions run where they are called or listened for. + S::Function(_) => { + if cx.in_function { + self.problem(s.pos, "functions declared inside functions aren't supported yet"); + } + } + S::Block(b) => return self.stmts(b, cx, out), + S::Var(w) => self.problem(s.pos, format!("variables (`{w}`) aren't supported yet")), + S::If(..) => self.problem(s.pos, "`if` statements aren't supported yet"), + S::Other(w, _) => { + let what = match *w { + "for" | "while" | "do" => format!("`{w}` loops aren't supported yet"), + _ => format!("`{w}` statements aren't supported yet"), + }; + self.problem(s.pos, what); + } + S::Return(None) => return true, + S::Return(Some(e)) => { + if self.constant(e, cx).is_err() { + self.problem(e.pos, "returning a value isn't supported"); + } + return true; + } + S::Expr(e) => self.expr_stmt(e, cx, out), + } + false + } + + fn expr_stmt(&mut self, e: &'a Expr, cx: &Cx, out: &mut Vec) { + match &e.kind { + E::Call(callee, args) => self.call(e.pos, callee, args, cx, out), + E::Assign("=", lhs, rhs) => self.assign(e.pos, lhs, rhs, cx, out), + E::Assign(op, _, _) => self.problem(e.pos, format!("`{op}` reads a value first; only `=` with a value is supported")), + E::Comma(list) => { + for x in list { + self.expr_stmt(x, cx, out); + } + } + // A literal alone does nothing (`"use strict"`). + E::Num(_) | E::Str(_) | E::Bool(_) | E::Null => {} + E::Unary("++" | "--", _) | E::Postfix(..) => self.problem(e.pos, "`++` and `--` read a value first and aren't supported"), + _ => self.problem(e.pos, "only calls (such as `stop()`) and settings (such as `hero_mc.x = 10`) run as statements"), + } + } + + fn call(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + match &callee.kind { + E::Name(n) => { + let n = n.as_str(); + if let Some(f) = self.funcs.get(n).copied() { + return self.inline(pos, f, args, cx, out); + } + match n { + "trace" => self.trace(pos, args, cx, out), + "addEventListener" => self.listen(pos, Vec::new(), args, cx, out), + n if METHODS.contains(&n) => self.method(pos, Vec::new(), n, args, cx, out), + n if OUTSIDE.contains(&n) => self.note(pos, format!("`{n}` is ignored: a movie here can't open web pages or reach outside itself")), + "removeEventListener" => self.problem(pos, "removing listeners isn't supported yet"), + n if CASTS.contains(&n) => self.problem(pos, format!("`{n}(…)` alone does nothing; call a method on it, as in `{n}(parent).play()`")), + n => self.problem(pos, format!("`{n}` isn't declared in this frame script (functions from other frames, and the rest of the language, aren't supported yet)")), + } + } + E::Member(obj, m) => { + let m = m.as_str(); + if OUTSIDE.contains(&m) || (matches!(&obj.kind, E::Name(o) if o == "ExternalInterface") && matches!(m, "call" | "addCallback")) { + return self.note(pos, format!("`{m}` is ignored: a movie here can't open web pages or reach outside itself")); + } + let known = METHODS.contains(&m) || m == "addEventListener"; + if !known { + let msg = if m == "removeEventListener" { "removing listeners isn't supported yet".to_string() } else { format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, and `addEventListener`, are)") }; + return self.problem(pos, msg); + } + let Some(t) = self.target(obj, cx) else { return }; + if m == "addEventListener" { self.listen(pos, t, args, cx, out) } else { self.method(pos, t, m, args, cx, out) } + } + _ => self.problem(pos, "only named functions and methods can be called"), + } + } + + /// A call to one of the script's own functions: its body runs in place. + fn inline(&mut self, pos: Pos, f: &'a Func, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + let name = f.name.clone().unwrap_or_default(); + if cx.stack.contains(&name) { + return self.problem(pos, format!("`{name}` calls itself; recursion isn't supported")); + } + if cx.stack.len() >= MAX_INLINE_DEPTH { + return self.problem(pos, format!("functions call each other more than {MAX_INLINE_DEPTH} deep")); + } + // Arguments are passed but never read (a parameter read is reported in the body). + for a in args { + let passes_event = matches!((&a.kind, &cx.event), (E::Name(n), Some((e, _))) if n == e); + if !passes_event && self.constant(a, cx).is_err() { + self.problem(a.pos, "arguments are values or the event; computing them isn't supported"); + } + } + if args.len() < f.params.iter().filter(|p| !p.default && !p.rest).count() { + return self.problem(pos, format!("`{name}` needs more arguments than this call passes")); + } + let mut inner = Cx { event: None, in_listener: cx.in_listener, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() }; + inner.stack.push(name); + self.stmts(&f.body, &inner, out); + } + + fn trace(&mut self, pos: Pos, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + let mut parts = Vec::new(); + for a in args { + match self.constant(a, cx) { + Ok(v) => parts.push(v.text()), + Err(p) => return self.problems.push(p), + } + } + let message = parts.join(" "); + if message.chars().count() > MAX_TRACE_CHARS { + return self.problem(pos, format!("a trace message is at most {MAX_TRACE_CHARS} characters")); + } + out.push(ScriptOp::Action(Action::Trace { message })); + } + + /// A timeline method on the instance at `path`. + fn method(&mut self, pos: Pos, path: Vec, m: &str, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + let Some(target) = self.path(pos, &path) else { return }; + let none = |l: &mut Self| { + if args.is_empty() { + true + } else { + l.problem(pos, format!("`{m}()` takes no arguments")); + false + } + }; + let action = match m { + "stop" if none(self) => Action::Stop { target }, + "play" if none(self) => Action::Play { target }, + "nextFrame" if none(self) => Action::NextFrame { target }, + "prevFrame" if none(self) => Action::PrevFrame { target }, + "nextScene" | "prevScene" => { + if !none(self) { + return; + } + // Scenes belong to the main timeline; on this timeline the player checks that + // it is the main one (a movie clip has no other scenes). + if !target.is_this() { + return self.problem(pos, format!("call `{m}()` in the main timeline's own script: scenes belong to the main timeline")); + } + if m == "nextScene" { Action::NextScene } else { Action::PrevScene } + } + "gotoAndPlay" | "gotoAndStop" => { + let (Some(f), true) = (args.first(), args.len() <= 2) else { + return self.problem(pos, format!("`{m}` takes a frame, and optionally a scene")); + }; + let frame = match self.constant(f, cx) { + Ok(Val::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1), + Ok(Val::Num(_)) => return self.problem(f.pos, format!("a frame number is a whole number from 1 to {}", u64::from(MAX_FRAME) + 1)), + Ok(Val::Str(s)) if label_ok(&s) => FrameRef::Label(s), + Ok(Val::Str(_)) => return self.problem(f.pos, format!("a frame label is 1 to {MAX_LABEL_CHARS} printable characters")), + Ok(_) => return self.problem(f.pos, "the frame is a number or a label"), + Err(p) => return self.problems.push(p), + }; + let scene = match args.get(1).map(|s| (s.pos, self.constant(s, cx))) { + None | Some((_, Ok(Val::Null | Val::Undefined))) => None, + Some((_, Ok(Val::Str(s)))) if label_ok(&s) => Some(s), + Some((p, Ok(_))) => return self.problem(p, "the scene is its name, as a string"), + Some((_, Err(p))) => return self.problems.push(p), + }; + if m == "gotoAndPlay" { Action::GotoAndPlay { target, frame, scene } } else { Action::GotoAndStop { target, frame, scene } } + } + _ => return, + }; + out.push(ScriptOp::Action(action)); + } + + /// `target.addEventListener(event, function)`. + fn listen(&mut self, pos: Pos, path: Vec, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + if cx.in_listener { + return self.problem(pos, "adding a listener from inside a listener isn't supported yet"); + } + let Some(target) = self.path(pos, &path) else { return }; + let (Some(ev), Some(handler), true) = (args.first(), args.get(1), args.len() <= 5) else { + return self.problem(pos, "`addEventListener` takes an event and a function"); + }; + let Some(event) = self.event(ev) else { return }; + if let Some(c) = args.get(2) + && !matches!(self.constant(c, cx), Ok(Val::Bool(false) | Val::Null | Val::Undefined)) + { + return self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported"); + } + for extra in args.iter().skip(3) { + if self.constant(extra, cx).is_err() { + return self.problem(extra.pos, "listener priority and weak references are values"); + } + } + let (f, function) = match &handler.kind { + E::Name(n) => match self.funcs.get(n.as_str()).copied() { + Some(f) => (f, n.clone()), + None => return self.problem(handler.pos, format!("`{n}` isn't a function declared in this frame script")), + }, + E::Function(f) => (&**f, format!("function at line {}", f.pos.line)), + _ => return self.problem(handler.pos, "the listener is a function declared in this frame script, or written in place"), + }; + // The event is passed to the function: it takes exactly one argument. + let required = f.params.iter().filter(|p| !p.default && !p.rest).count(); + let Some(first) = f.params.first().filter(|_| required <= 1) else { + return self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); + }; + if cx.stack.contains(&function) { + return self.problem(pos, format!("`{function}` adds itself as a listener; recursion isn't supported")); + } + if self.listeners >= MAX_LISTENERS { + return self.problem(pos, format!("a frame script adds at most {MAX_LISTENERS} listeners")); + } + self.listeners += 1; + let mut inner = Cx { event: Some((first.name.clone(), path)), in_listener: true, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() }; + inner.stack.push(function.clone()); + let mut body = Vec::new(); + self.stmts(&f.body, &inner, &mut body); + let actions: Vec = body + .into_iter() + .filter_map(|op| match op { + ScriptOp::Action(a) => Some(a), + ScriptOp::Listen(_) => None, + }) + .collect(); + if actions.len() > MAX_ACTIONS { + return self.problem(f.pos, format!("a listener runs at most {MAX_ACTIONS} actions")); + } + out.push(ScriptOp::Listen(Listener { target, event, function, actions: Arc::new(actions) })); + } + + /// The mouse event an `addEventListener` names. + fn event(&mut self, e: &Expr) -> Option { + let (pos, name, constant) = match &e.kind { + E::Member(o, k) if matches!(&o.kind, E::Name(c) if c == "MouseEvent" || c == "Event" || c.ends_with("Event")) => { + let class = if let E::Name(c) = &o.kind { c.as_str() } else { "" }; + (e.pos, format!("{class}.{k}"), if class == "MouseEvent" { k.as_str() } else { "" }) + } + E::Str(s) => (e.pos, format!("\"{s}\""), match s.as_str() { + "click" => "CLICK", + "mouseDown" => "MOUSE_DOWN", + "mouseUp" => "MOUSE_UP", + "rollOver" => "ROLL_OVER", + "rollOut" => "ROLL_OUT", + "mouseOver" => "MOUSE_OVER", + "mouseOut" => "MOUSE_OUT", + _ => "", + }), + _ => { + self.problem(e.pos, "the event is a constant such as `MouseEvent.CLICK`"); + return None; + } + }; + let ev = match constant { + "CLICK" => ButtonEvent::Click, + "MOUSE_DOWN" => ButtonEvent::Press, + "MOUSE_UP" => ButtonEvent::Release, + "ROLL_OVER" | "MOUSE_OVER" => ButtonEvent::Over, + "ROLL_OUT" | "MOUSE_OUT" => ButtonEvent::Out, + _ => { + self.problem(pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT are)")); + return None; + } + }; + Some(ev) + } + + /// `x = value` on this timeline or `path.x = value`. + fn assign(&mut self, pos: Pos, lhs: &'a Expr, rhs: &'a Expr, cx: &Cx, out: &mut Vec) { + let (obj, prop) = match &lhs.kind { + E::Member(o, p) => (Some(&**o), p.as_str()), + E::Name(n) => (None, n.as_str()), + _ => return self.problem(pos, "only instance properties can be set"), + }; + let property = match prop { + "x" => Property::X, + "y" => Property::Y, + "alpha" => Property::Alpha, + "visible" => Property::Visible, + "rotation" => Property::Rotation, + "scaleX" => Property::ScaleX, + "scaleY" => Property::ScaleY, + "buttonMode" | "useHandCursor" => return self.note(pos, format!("`{prop}` is ignored: the pointer is a hand over everything clickable here")), + p if obj.is_none() => return self.problem(pos, format!("setting `{p}` isn't supported: variables don't run yet")), + p => return self.problem(pos, format!("setting `{p}` isn't supported yet (x, y, alpha, visible, rotation, scaleX and scaleY are)")), + }; + let path = match obj { + Some(o) => match self.target(o, cx) { + Some(t) => t, + None => return, + }, + None => Vec::new(), + }; + let Some(target) = self.path(pos, &path) else { return }; + let value = match self.constant(rhs, cx) { + Ok(v @ (Val::Num(_) | Val::Bool(_))) => v.number(), + Ok(_) => return self.problem(rhs.pos, format!("`{prop}` is set to a number{}", if property == Property::Visible { " or true or false" } else { "" })), + Err(p) => return self.problems.push(p), + }; + if !value.is_finite() { + return self.problem(rhs.pos, "the value must be a finite number"); + } + out.push(ScriptOp::Action(Action::SetProperty { target, property, value })); + } + + /// An instance path as names (`root`, `parent` and instance names), relative to the + /// script's timeline; `None` after reporting why it isn't one. + fn target(&mut self, e: &Expr, cx: &Cx) -> Option> { + let mut path = match &e.kind { + E::This => Vec::new(), + E::Name(n) if n == "root" || n == "parent" => vec![n.clone()], + E::Name(n) if n == "stage" => { + self.problem(e.pos, "the stage isn't supported as a target"); + return None; + } + E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => { + self.problem(e.pos, format!("the event `{n}` isn't an instance; `{n}.currentTarget` is the one listened to")); + return None; + } + E::Name(n) if cx.params.contains(n) => { + self.problem(e.pos, format!("reading the parameter `{n}` isn't supported")); + return None; + } + E::Name(n) => vec![n.clone()], + E::Member(o, m) if m == "currentTarget" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => cx.event.as_ref().map(|(_, t)| t.clone()).unwrap_or_default(), + E::Member(o, m) if m == "target" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => { + self.problem(e.pos, "`target` can be a part inside the instance; use `currentTarget`, the instance listened to"); + return None; + } + E::Member(o, m) => { + let mut p = self.target(o, cx)?; + p.push(m.clone()); + p + } + E::Call(f, args) if matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1 => return args.first().and_then(|a| self.target(a, cx)), + E::Binary("as", x, _) => return self.target(x, cx), + _ => { + self.problem(e.pos, "this isn't an instance (a name path such as `hero_mc.arm_mc`, `parent` or `root`)"); + return None; + } + }; + // Every instance's `root` is the main timeline. + if let Some(i) = path.iter().rposition(|s| s == "root") { + path.drain(..i); + } + Some(path) + } + + /// The IR target for a path, checked. + fn path(&mut self, pos: Pos, path: &[String]) -> Option { + for s in path { + if !matches!(s.as_str(), "root" | "parent") && !valid_instance_name(s) { + self.problem(pos, format!("`{s}` isn't an instance name AniCraft can address (1-64 letters, digits, `_` or `$`)")); + return None; + } + } + let t = Target::new(path.join(".")); + match t.segments() { + Ok(_) => Some(t), + Err(e) => { + self.problem(pos, e); + None + } + } + } + + /// A value computed from literals (`"Score: " + 10`, `-5`, `0.5`). + fn constant(&self, e: &Expr, cx: &Cx) -> Result { + Ok(match &e.kind { + E::Num(n) => Val::Num(*n), + E::Str(s) => Val::Str(s.clone()), + E::Bool(b) => Val::Bool(*b), + E::Null => Val::Null, + E::Name(n) if n == "undefined" => Val::Undefined, + E::Name(n) if n == "NaN" => Val::Num(f64::NAN), + E::Name(n) if n == "Infinity" => Val::Num(f64::INFINITY), + E::Unary("-", x) => Val::Num(-self.constant(x, cx)?.number()), + E::Unary("+", x) => Val::Num(self.constant(x, cx)?.number()), + E::Unary("!", x) => Val::Bool(!truthy(&self.constant(x, cx)?)), + E::Binary(op @ ("+" | "-" | "*" | "/" | "%"), a, b) => { + let (a, b) = (self.constant(a, cx)?, self.constant(b, cx)?); + match *op { + "+" if matches!(a, Val::Str(_)) || matches!(b, Val::Str(_)) => { + let s = a.text() + &b.text(); + if s.len() > MAX_TRACE_CHARS * 4 { + return Err(Problem::at(e.pos, "this text is too long")); + } + Val::Str(s) + } + "+" => Val::Num(a.number() + b.number()), + "-" => Val::Num(a.number() - b.number()), + "*" => Val::Num(a.number() * b.number()), + "/" => Val::Num(a.number() / b.number()), + _ => Val::Num(a.number() % b.number()), + } + } + E::Name(n) => { + let msg = if cx.event.as_ref().is_some_and(|(p, _)| p == n) { format!("reading the event `{n}` isn't supported") } else { format!("reading `{n}` isn't supported: only values written out (numbers, strings, true, false) and `+` of them are") }; + return Err(Problem::at(e.pos, msg)); + } + E::Member(..) => { + let mut root = e; + while let E::Member(o, _) = &root.kind { + root = o; + } + let msg = match &root.kind { + E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => format!("reading the event `{n}` isn't supported"), + _ => "reading properties isn't supported: only values written out (numbers, strings, true, false) and `+` of them are".into(), + }; + return Err(Problem::at(e.pos, msg)); + } + _ => return Err(Problem::at(e.pos, "only values written out (numbers, strings, true, false) and `+` of them are supported here")), + }) + } +} + +fn truthy(v: &Val) -> bool { + match v { + Val::Num(n) => *n != 0.0 && !n.is_nan(), + Val::Str(s) => !s.is_empty(), + Val::Bool(b) => *b, + Val::Null | Val::Undefined => false, + } +} + +fn label_ok(s: &str) -> bool { + let n = s.chars().count(); + (1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace()) +} + +/// The statements' top-level function declarations (also those in plain blocks, which +/// ActionScript hoists too). +fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, problems: &mut Vec) { + for s in list { + match &s.kind { + S::Function(f) => { + let Some(n) = f.name.as_deref() else { continue }; + if BUILTINS.contains(&n) || CASTS.contains(&n) { + problems.push(Problem::at(s.pos, format!("a function named `{n}` would hide ActionScript's own `{n}`"))); + } else if funcs.insert(n, f).is_some() { + problems.push(Problem::at(s.pos, format!("`{n}` is declared twice"))); + } + } + S::Block(b) => declare(b, funcs, problems), + _ => {} + } + } +} + +pub(super) fn lower(prog: &[Stmt]) -> Result> { + let mut funcs = BTreeMap::new(); + let mut problems = Vec::new(); + declare(prog, &mut funcs, &mut problems); + let mut l = Lower { funcs, problems, notes: Vec::new(), listeners: 0, work: 0 }; + let mut ops = Vec::new(); + l.stmts(prog, &Cx::default(), &mut ops); + if ops.len() > MAX_ACTIONS { + l.problems.push(Problem::whole(format!("a frame script runs at most {MAX_ACTIONS} steps"))); + } + let tidy = |mut v: Vec| { + v.sort(); + v.dedup(); + v.truncate(MAX_PROBLEMS); + v + }; + if l.problems.is_empty() { Ok(Compiled { ops, notes: tidy(l.notes) }) } else { Err(tidy(l.problems)) } +} diff --git a/crates/actions/src/as3/mod.rs b/crates/actions/src/as3/mod.rs new file mode 100644 index 00000000..191bd386 --- /dev/null +++ b/crates/actions/src/as3/mod.rs @@ -0,0 +1,133 @@ +//! The ActionScript 3.0 timeline subset (ADR 0013 tier 2): a hand-written lexer and +//! recursive-descent parser, and a lowering to the action IR. +//! +//! What runs is what most Animate frame scripts do: `stop()`, `play()`, `gotoAndPlay` and +//! `gotoAndStop` by frame number or label (and scene), `nextFrame()`, `prevFrame()`, +//! `nextScene()` and `prevScene()`, on this timeline or on instance-name paths +//! (`hero_mc.gotoAndStop("run")`, `MovieClip(this.parent).play()`); mouse listeners +//! (`btn.addEventListener(MouseEvent.CLICK, onClick)` with `function onClick(e:MouseEvent):void +//! { … }` made of those calls, or an inline function); `trace` of literals and their `+`; and +//! setting `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX` and `scaleY` on named instances to +//! values. A function declared in the script and called from it runs in place. +//! +//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all: +//! nothing is ever half-run. Calls that would reach outside the movie (`navigateToURL`, +//! `fscommand`, `ExternalInterface`) are ignored and listed as notes. +//! +//! Learned from the ECMAScript 3rd edition standard (ECMA-262) and Adobe's public ActionScript +//! 3.0 language reference; no Adobe code. Everything is bounded: source length, token count, +//! nesting depth, inlining depth, actions, listeners and problems. + +mod lex; +mod lower; +mod parse; + +use crate::{Action, ButtonEvent, Target}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +/// Longest script that runs, in bytes (far more than frame scripts written by hand). +pub const MAX_RUN_BYTES: usize = 256 * 1024; +/// Most tokens in a script that runs. +pub const MAX_TOKENS: usize = 65_536; +/// Deepest nesting of statements and expressions. +pub const MAX_DEPTH: usize = 64; +/// Deepest chain of calls to the script's own functions. +pub const MAX_INLINE_DEPTH: usize = 16; +/// Most listeners one script adds. +pub const MAX_LISTENERS: usize = 64; +/// Most problems reported for one script. +pub const MAX_PROBLEMS: usize = 32; + +/// A place in the script: 1-based line and column (in characters; a tab is one). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct Pos { + pub line: u32, + pub column: u32, +} + +/// Why a script doesn't run (or, as a note, what in it is ignored). `line` and `column` are 0 +/// when it is about the whole script. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Problem { + pub line: u32, + pub column: u32, + pub message: String, +} + +impl Problem { + pub fn at(pos: Pos, message: impl Into) -> Problem { + Problem { line: pos.line, column: pos.column, message: message.into() } + } + pub fn whole(message: impl Into) -> Problem { + Problem { line: 0, column: 0, message: message.into() } + } + pub fn pos(&self) -> Option { + (self.line > 0).then_some(Pos { line: self.line, column: self.column }) + } +} + +impl std::fmt::Display for Problem { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.line > 0 { write!(f, "line {}, column {}: {}", self.line, self.column, self.message) } else { f.write_str(&self.message) } + } +} + +/// A mouse listener a script adds: when `event` happens on `target` (a button or movie clip, +/// named from the script's timeline), `actions` run on the script's timeline. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Listener { + #[serde(default, skip_serializing_if = "Target::is_this")] + pub target: Target, + pub event: ButtonEvent, + /// The function's name (`function at line 7` for an inline one): adding the same function + /// for the same event again changes nothing, as in ActionScript. + pub function: String, + pub actions: Arc>, +} + +impl Listener { + pub fn describe(&self) -> String { + let body = if self.actions.is_empty() { "nothing".to_string() } else { self.actions.iter().map(Action::describe).collect::>().join("; ") }; + format!("On {} ({}): {body}", self.event.key(), self.target) + } +} + +/// One step of a script, in source order. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ScriptOp { + Action(Action), + Listen(Listener), +} + +impl ScriptOp { + pub fn describe(&self) -> String { + match self { + ScriptOp::Action(a) => a.describe(), + ScriptOp::Listen(l) => l.describe(), + } + } +} + +/// A script that runs: its steps, and what in it is ignored. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Compiled { + pub ops: Vec, + /// Calls that are ignored (they would reach outside the movie, or do nothing here). + pub notes: Vec, +} + +/// Compiles ActionScript 3.0 source to the action IR, or says why it doesn't run (the +/// problems sorted by position, at most [`MAX_PROBLEMS`]). +pub fn compile(src: &str) -> Result> { + if src.len() > MAX_RUN_BYTES { + return Err(vec![Problem::whole(format!("the script is longer than {} KiB, the most that runs", MAX_RUN_BYTES / 1024))]); + } + let toks = lex::tokens(src).map_err(|p| vec![p])?; + let prog = parse::parse(&toks).map_err(|p| vec![p])?; + lower::lower(&prog) +} + +#[cfg(test)] +mod tests; diff --git a/crates/actions/src/as3/parse.rs b/crates/actions/src/as3/parse.rs new file mode 100644 index 00000000..ccdea22d --- /dev/null +++ b/crates/actions/src/as3/parse.rs @@ -0,0 +1,736 @@ +//! The parser: tokens to a syntax tree, by recursive descent (the grammar of ECMA-262 3rd +//! edition §11–14, with ActionScript 3.0's type annotations, `import`, `as`, `is`, rest +//! parameters and `for each`). It reads more of the language than AniCraft runs, so lowering +//! can say exactly which construct isn't run and where; what it reads but never runs (loop +//! headers, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting +//! deeper than [`super::MAX_DEPTH`] is a problem, not a stack overflow. + +use super::lex::{Tok, Token}; +use super::{MAX_DEPTH, Pos, Problem}; + +#[derive(Clone, Debug, PartialEq)] +pub struct Expr { + pub pos: Pos, + pub kind: E, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum E { + Num(f64), + Str(String), + Bool(bool), + Null, + This, + Name(String), + /// `a.b` + Member(Box, String), + /// `a[b]` + Index(Box, Box), + Call(Box, Vec), + New(Box, Vec), + /// A prefix operator (`!`, `-`, `typeof`, `++`, …). + Unary(&'static str, Box), + /// `x++`, `x--` + Postfix(&'static str, Box), + Binary(&'static str, Box, Box), + /// `=`, `+=`, … + Assign(&'static str, Box, Box), + Cond(Box, Box, Box), + Function(Box), + Array(Vec), + Object(Vec<(String, Expr)>), + /// `a, b` + Comma(Vec), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Param { + pub name: String, + pub pos: Pos, + pub default: bool, + pub rest: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Func { + pub name: Option, + pub pos: Pos, + pub params: Vec, + pub body: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Stmt { + pub pos: Pos, + pub kind: S, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum S { + Expr(Expr), + Import, + Function(Func), + /// `var`, `const`. + Var(&'static str), + If(Expr, Vec, Vec), + Return(Option), + Block(Vec), + Empty, + /// A statement the parser reads but lowering never runs, by its keyword (`for`, `while`, + /// `switch`, …), with the statements inside it. + Other(&'static str, Vec), +} + +/// Words that can't name a variable or function (ActionScript 3.0's reserved words). +const RESERVED: [&str; 46] = [ + "as", "break", "case", "catch", "class", "const", "continue", "default", "delete", "do", "else", "extends", "false", "finally", "for", "function", "if", "implements", "import", "in", "instanceof", "interface", "internal", "is", "native", "new", "null", "package", "private", "protected", "public", "return", "super", "switch", "this", "throw", "to", "true", "try", "typeof", "use", "var", "void", "while", "with", "include", +]; + +/// Attribute words that may stand before a declaration in a frame script. +const ATTRIBUTES: [&str; 9] = ["public", "private", "protected", "internal", "static", "override", "final", "dynamic", "native"]; + +pub fn reserved(s: &str) -> bool { + RESERVED.contains(&s) +} + +struct Parser<'a> { + toks: &'a [Token], + i: usize, + depth: usize, +} + +type R = Result; + +/// What a token reads as in a message. +fn shown(t: &Tok) -> String { + match t { + Tok::Name(n) => format!("`{n}`"), + Tok::Num(_) => "a number".into(), + Tok::Str(_) => "a string".into(), + Tok::Punct(p) => format!("`{p}`"), + Tok::Eof => "the end of the script".into(), + } +} + +impl<'a> Parser<'a> { + fn tok(&self) -> &'a Tok { + self.toks.get(self.i).map_or(&Tok::Eof, |t| &t.tok) + } + + fn tok_at(&self, k: usize) -> &'a Tok { + self.toks.get(self.i + k).map_or(&Tok::Eof, |t| &t.tok) + } + + fn pos(&self) -> Pos { + self.toks.get(self.i).or(self.toks.last()).map_or(Pos { line: 1, column: 1 }, |t| t.pos) + } + + fn nl(&self) -> bool { + self.toks.get(self.i).is_none_or(|t| t.nl) + } + + fn next(&mut self) -> &'a Tok { + let t = self.tok(); + if self.i < self.toks.len() { + self.i += 1; + } + t + } + + fn is(&self, p: &str) -> bool { + matches!(self.tok(), Tok::Punct(q) if *q == p) + } + + fn is_word(&self, w: &str) -> bool { + matches!(self.tok(), Tok::Name(n) if n == w) + } + + fn eat(&mut self, p: &str) -> bool { + if self.is(p) { + self.i += 1; + true + } else { + false + } + } + + fn eat_word(&mut self, w: &str) -> bool { + if self.is_word(w) { + self.i += 1; + true + } else { + false + } + } + + fn expect(&mut self, p: &str, what: &str) -> R<()> { + if self.eat(p) { Ok(()) } else { Err(self.unexpected(&format!("`{p}` {what}"))) } + } + + fn unexpected(&self, wanted: &str) -> Problem { + Problem::at(self.pos(), format!("expected {wanted}, found {}", shown(self.tok()))) + } + + /// Enters one level of nesting. + fn deeper(&mut self) -> R<()> { + self.depth += 1; + if self.depth > MAX_DEPTH { Err(Problem::at(self.pos(), format!("the code is nested more than {MAX_DEPTH} levels deep"))) } else { Ok(()) } + } + + fn name(&mut self, what: &str) -> R<(String, Pos)> { + let pos = self.pos(); + match self.tok() { + Tok::Name(n) if !reserved(n) => { + self.i += 1; + Ok((n.clone(), pos)) + } + _ => Err(self.unexpected(what)), + } + } + + /// The end of a statement: `;`, or a line break, `}` or the end (semicolon insertion). + fn end(&mut self) -> R<()> { + if self.eat(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl() { + Ok(()) + } else { + Err(self.unexpected("`;` or a new line")) + } + } + + /// Skips a balanced `( … )`, `[ … ]` or `{ … }` starting at the current token. + fn skip_group(&mut self) -> R<()> { + let start = self.pos(); + let mut stack: Vec<&str> = Vec::new(); + loop { + match self.next() { + Tok::Punct(p @ ("(" | "[" | "{")) => { + stack.push(match *p { + "(" => ")", + "[" => "]", + _ => "}", + }); + if stack.len() > MAX_DEPTH { + return Err(Problem::at(start, format!("the code is nested more than {MAX_DEPTH} levels deep"))); + } + } + Tok::Punct(p @ (")" | "]" | "}")) => { + if stack.pop() != Some(*p) { + return Err(Problem::at(self.toks.get(self.i.saturating_sub(1)).map_or(start, |t| t.pos), format!("`{p}` doesn't match an opening bracket"))); + } + if stack.is_empty() { + return Ok(()); + } + } + Tok::Eof => return Err(Problem::at(start, "this bracket is never closed")), + _ if stack.is_empty() => return Err(Problem::at(start, "expected a bracket")), + _ => {} + } + } + } + + /// `: Type` (read and dropped: `*`, `void`, `a.b.C`, `Vector.`). + fn annotation(&mut self) -> R<()> { + if !self.eat(":") { + return Ok(()); + } + self.type_name() + } + + fn type_name(&mut self) -> R<()> { + if self.eat("*") || self.eat_word("void") { + return Ok(()); + } + self.name("a type")?; + loop { + if self.eat(".<") { + self.deeper()?; + self.type_name()?; + self.depth -= 1; + // `>>` closes two generics at once. + if !self.eat(">") { + return Err(self.unexpected("`>` to close the type")); + } + } else if self.eat(".") { + self.name("a type")?; + } else { + return Ok(()); + } + } + } + + fn program(&mut self) -> R> { + let mut out = Vec::new(); + while !matches!(self.tok(), Tok::Eof) { + out.push(self.statement()?); + } + Ok(out) + } + + fn block(&mut self) -> R> { + self.expect("{", "to open the block")?; + let mut out = Vec::new(); + while !self.eat("}") { + if matches!(self.tok(), Tok::Eof) { + return Err(self.unexpected("`}` to close the block")); + } + out.push(self.statement()?); + } + Ok(out) + } + + /// A statement as a body (`if (…) stmt`): a block's statements, or one statement. + fn body(&mut self) -> R> { + if self.is("{") { + let pos = self.pos(); + let b = self.block()?; + Ok(vec![Stmt { pos, kind: S::Block(b) }]) + } else { + Ok(vec![self.statement()?]) + } + } + + fn statement(&mut self) -> R { + self.deeper()?; + let s = self.statement_inner(); + self.depth -= 1; + s + } + + fn statement_inner(&mut self) -> R { + let pos = self.pos(); + let kind = match self.tok() { + Tok::Punct(";") => { + self.i += 1; + S::Empty + } + Tok::Punct("{") => S::Block(self.block()?), + Tok::Name(w) => match w.as_str() { + "import" => { + self.i += 1; + self.name("a package name after `import`")?; + while self.eat(".") { + if !self.eat("*") { + self.name("a name")?; + } + } + self.end()?; + S::Import + } + "function" if matches!(self.tok_at(1), Tok::Name(_)) => { + self.i += 1; + S::Function(self.function(pos, true)?) + } + "var" | "const" => { + let w = if w == "var" { "var" } else { "const" }; + self.i += 1; + loop { + self.name("a variable name")?; + self.annotation()?; + if self.eat("=") { + self.assign()?; + } + if !self.eat(",") { + break; + } + } + self.end()?; + S::Var(w) + } + "if" => { + self.i += 1; + self.expect("(", "after `if`")?; + let c = self.expr()?; + self.expect(")", "after the condition")?; + let then = self.body()?; + let other = if self.eat_word("else") { self.body()? } else { Vec::new() }; + S::If(c, then, other) + } + "return" => { + self.i += 1; + let e = if self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl() { None } else { Some(self.expr()?) }; + self.end()?; + S::Return(e) + } + "for" => { + self.i += 1; + self.eat_word("each"); + self.skip_group()?; + S::Other("for", self.body()?) + } + "while" => { + self.i += 1; + self.skip_group()?; + S::Other("while", self.body()?) + } + "do" => { + self.i += 1; + let b = self.body()?; + if !self.eat_word("while") { + return Err(self.unexpected("`while` after the `do` body")); + } + self.skip_group()?; + self.end()?; + S::Other("do", b) + } + "with" => { + self.i += 1; + self.skip_group()?; + S::Other("with", self.body()?) + } + "switch" => { + self.i += 1; + self.skip_group()?; + self.skip_group()?; + S::Other("switch", Vec::new()) + } + "try" => { + self.i += 1; + let mut inner = self.block()?; + let mut any = false; + while self.eat_word("catch") { + any = true; + self.skip_group()?; + inner.extend(self.block()?); + } + if self.eat_word("finally") { + any = true; + inner.extend(self.block()?); + } + if !any { + return Err(self.unexpected("`catch` or `finally` after the `try` block")); + } + S::Other("try", inner) + } + "break" | "continue" | "throw" => { + let w = match w.as_str() { + "break" => "break", + "continue" => "continue", + _ => "throw", + }; + self.i += 1; + if !(self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl()) { + self.expr()?; + } + self.end()?; + S::Other(w, Vec::new()) + } + // Applications, not timeline scripts (ADR 0013 tier 3). + "package" | "class" | "interface" | "namespace" | "use" | "include" | "default" => { + let w = w.clone(); + return Err(Problem::at(pos, format!("`{w}` belongs to class files and isn't supported in frame scripts"))); + } + a if ATTRIBUTES.contains(&a) && matches!(self.tok_at(1), Tok::Name(_)) => { + let a = a.to_string(); + return Err(Problem::at(pos, format!("`{a}` declarations belong to classes and aren't supported in frame scripts"))); + } + _ => { + let e = self.expr()?; + if self.is(":") { + return Err(Problem::at(pos, "statement labels aren't supported")); + } + self.end()?; + S::Expr(e) + } + }, + _ => { + let e = self.expr()?; + self.end()?; + S::Expr(e) + } + }; + Ok(Stmt { pos, kind }) + } + + /// After `function`: an optional name, the parameters, the result type and the body. + fn function(&mut self, pos: Pos, named: bool) -> R { + let name = if named || matches!(self.tok(), Tok::Name(n) if !reserved(n)) { Some(self.name("a function name")?.0) } else { None }; + // Getters and setters are class members. + if matches!(name.as_deref(), Some("get" | "set")) && matches!(self.tok(), Tok::Name(_)) { + return Err(Problem::at(pos, "getters and setters belong to classes and aren't supported in frame scripts")); + } + self.expect("(", "to open the parameter list")?; + let mut params = Vec::new(); + if !self.eat(")") { + loop { + let rest = self.eat("..."); + let (n, p) = self.name("a parameter name")?; + self.annotation()?; + let default = self.eat("="); + if default { + self.assign()?; + } + params.push(Param { name: n, pos: p, default, rest }); + if self.eat(")") { + break; + } + self.expect(",", "or `)` after the parameter")?; + } + } + self.annotation()?; + let body = self.block()?; + Ok(Func { name, pos, params, body }) + } + + /// An expression (`a, b` included). + fn expr(&mut self) -> R { + let first = self.assign()?; + if !self.is(",") { + return Ok(first); + } + let pos = first.pos; + let mut list = vec![first]; + while self.eat(",") { + list.push(self.assign()?); + } + Ok(Expr { pos, kind: E::Comma(list) }) + } + + fn assign(&mut self) -> R { + self.deeper()?; + let r = self.assign_inner(); + self.depth -= 1; + r + } + + fn assign_inner(&mut self) -> R { + let lhs = self.conditional()?; + let op = match self.tok() { + Tok::Punct(p @ ("=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "&=" | "|=" | "^=" | "&&=" | "||=")) => *p, + _ => return Ok(lhs), + }; + let pos = self.pos(); + if !matches!(lhs.kind, E::Name(_) | E::Member(..) | E::Index(..)) { + return Err(Problem::at(pos, "the left side of this assignment can't be assigned to")); + } + self.i += 1; + let rhs = self.assign()?; + Ok(Expr { pos: lhs.pos, kind: E::Assign(op, Box::new(lhs), Box::new(rhs)) }) + } + + fn conditional(&mut self) -> R { + let c = self.binary(0)?; + if !self.eat("?") { + return Ok(c); + } + let a = self.assign()?; + self.expect(":", "in the `? :` expression")?; + let b = self.assign()?; + Ok(Expr { pos: c.pos, kind: E::Cond(Box::new(c), Box::new(a), Box::new(b)) }) + } + + /// Binary operators by precedence level (0 = `||`, loosest). + fn binary(&mut self, level: usize) -> R { + const LEVELS: [&[&str]; 10] = [ + &["||"], + &["&&"], + &["|"], + &["^"], + &["&"], + &["==", "!=", "===", "!=="], + &["<", ">", "<=", ">=", "instanceof", "is", "as", "in"], + &["<<", ">>", ">>>"], + &["+", "-"], + &["*", "/", "%"], + ]; + let Some(ops) = LEVELS.get(level) else { return self.unary() }; + let mut lhs = self.binary(level + 1)?; + loop { + let op = match self.tok() { + Tok::Punct(p) if ops.contains(p) => ops.iter().find(|o| *o == p).copied(), + Tok::Name(n) if ops.contains(&n.as_str()) => ops.iter().find(|o| **o == n.as_str()).copied(), + _ => None, + }; + let Some(op) = op else { return Ok(lhs) }; + self.i += 1; + // The right side of `as` and `is` is a type. + let rhs = if matches!(op, "as" | "is") { + let pos = self.pos(); + let start = self.i; + self.type_name()?; + let name = match self.toks.get(start..self.i) { + Some([Token { tok: Tok::Name(n), .. }]) => n.clone(), + _ => "*".into(), + }; + Expr { pos, kind: E::Name(name) } + } else { + self.binary(level + 1)? + }; + lhs = Expr { pos: lhs.pos, kind: E::Binary(op, Box::new(lhs), Box::new(rhs)) }; + } + } + + fn unary(&mut self) -> R { + self.deeper()?; + let r = self.unary_inner(); + self.depth -= 1; + r + } + + fn unary_inner(&mut self) -> R { + let pos = self.pos(); + let op = match self.tok() { + Tok::Punct(p @ ("!" | "~" | "-" | "+" | "++" | "--")) => Some(*p), + Tok::Name(n) if matches!(n.as_str(), "typeof" | "void" | "delete") => Some(match n.as_str() { + "typeof" => "typeof", + "void" => "void", + _ => "delete", + }), + _ => None, + }; + if let Some(op) = op { + self.i += 1; + let e = self.unary()?; + return Ok(Expr { pos, kind: E::Unary(op, Box::new(e)) }); + } + let e = self.postfix()?; + if !self.nl() + && let Tok::Punct(p @ ("++" | "--")) = self.tok() + { + self.i += 1; + return Ok(Expr { pos, kind: E::Postfix(p, Box::new(e)) }); + } + Ok(e) + } + + /// A primary expression with its member accesses, indexes and calls. + fn postfix(&mut self) -> R { + let mut e = if self.is_word("new") { self.new_expr()? } else { self.primary()? }; + loop { + let pos = self.pos(); + if self.eat(".") { + let n = match self.next() { + // Any word can follow a dot (`e.default` is a property). + Tok::Name(n) => n.clone(), + Tok::Punct("(") => { + return Err(Problem::at(pos, "XML filters aren't supported")); + } + t => return Err(Problem::at(pos, format!("expected a property name after `.`, found {}", shown(t)))), + }; + e = Expr { pos: e.pos, kind: E::Member(Box::new(e), n) }; + } else if self.is("..") || self.is("::") || self.is(".<") { + let what = match self.next() { + Tok::Punct("..") => "XML descendant access (`..`)", + Tok::Punct("::") => "namespace-qualified names (`::`)", + _ => "typed vectors (`Vector.`)", + }; + return Err(Problem::at(pos, format!("{what} isn't supported"))); + } else if self.is("[") { + self.i += 1; + let ix = self.expr()?; + self.expect("]", "to close the index")?; + e = Expr { pos: e.pos, kind: E::Index(Box::new(e), Box::new(ix)) }; + } else if self.is("(") { + let args = self.arguments()?; + e = Expr { pos: e.pos, kind: E::Call(Box::new(e), args) }; + } else { + return Ok(e); + } + } + } + + fn new_expr(&mut self) -> R { + let pos = self.pos(); + self.i += 1; + self.deeper()?; + // `new X.Y(args)`: the constructor is a name path (or another `new`). + let mut callee = if self.is_word("new") { self.new_expr()? } else { self.primary()? }; + while self.eat(".") { + let (n, _) = match self.tok() { + Tok::Name(n) => (n.clone(), self.pos()), + _ => return Err(self.unexpected("a name after `.`")), + }; + self.i += 1; + callee = Expr { pos: callee.pos, kind: E::Member(Box::new(callee), n) }; + } + if self.is(".<") { + return Err(Problem::at(self.pos(), "typed vectors (`Vector.`) aren't supported")); + } + let args = if self.is("(") { self.arguments()? } else { Vec::new() }; + self.depth -= 1; + Ok(Expr { pos, kind: E::New(Box::new(callee), args) }) + } + + fn arguments(&mut self) -> R> { + self.expect("(", "")?; + let mut args = Vec::new(); + if self.eat(")") { + return Ok(args); + } + loop { + if self.eat("...") { + return Err(Problem::at(self.pos(), "spreading arguments (`...`) isn't supported")); + } + args.push(self.assign()?); + if self.eat(")") { + return Ok(args); + } + self.expect(",", "or `)` after the argument")?; + } + } + + fn primary(&mut self) -> R { + let pos = self.pos(); + let kind = match self.next() { + Tok::Num(n) => E::Num(*n), + Tok::Str(s) => E::Str(s.clone()), + Tok::Name(n) => match n.as_str() { + "true" => E::Bool(true), + "false" => E::Bool(false), + "null" => E::Null, + "this" => E::This, + "function" => E::Function(Box::new(self.function(pos, false)?)), + "super" => return Err(Problem::at(pos, "`super` belongs to classes and isn't supported in frame scripts")), + w if reserved(w) => return Err(Problem::at(pos, format!("expected an expression, found `{w}`"))), + _ => E::Name(n.clone()), + }, + Tok::Punct("(") => { + let e = self.expr()?; + self.expect(")", "to close the parenthesis")?; + // Parentheses only group; the inner expression keeps its own position. + return Ok(e); + } + Tok::Punct("[") => { + let mut items = Vec::new(); + while !self.eat("]") { + if self.eat(",") { + continue; + } + items.push(self.assign()?); + if !self.is("]") { + self.expect(",", "or `]` in the array")?; + } + } + E::Array(items) + } + Tok::Punct("{") => { + let mut fields = Vec::new(); + while !self.eat("}") { + let key = match self.next() { + Tok::Name(n) => n.clone(), + Tok::Str(s) => s.clone(), + Tok::Num(n) => format!("{n}"), + _ => return Err(Problem::at(self.pos(), "expected a field name in the object")), + }; + self.expect(":", "after the field name")?; + fields.push((key, self.assign()?)); + if !self.is("}") { + self.expect(",", "or `}` in the object")?; + } + } + E::Object(fields) + } + Tok::Punct("/" | "/=") => return Err(Problem::at(pos, "regular expressions aren't supported")), + Tok::Punct("<") => return Err(Problem::at(pos, "XML literals aren't supported")), + t => { + self.i = self.i.saturating_sub(1); + return Err(Problem::at(pos, format!("expected an expression, found {}", shown(t)))); + } + }; + Ok(Expr { pos, kind }) + } +} + +/// The statements of a script. +pub fn parse(toks: &[Token]) -> Result, Problem> { + Parser { toks, i: 0, depth: 0 }.program() +} diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs new file mode 100644 index 00000000..7ce85de8 --- /dev/null +++ b/crates/actions/src/as3/tests.rs @@ -0,0 +1,293 @@ +use super::*; +use crate::{Action, ButtonEvent, FrameRef, Property, Target}; + +fn ok(src: &str) -> Compiled { + compile(src).unwrap_or_else(|p| panic!("{src:?} didn't compile: {p:?}")) +} + +fn actions(src: &str) -> Vec { + ok(src) + .ops + .into_iter() + .map(|o| match o { + ScriptOp::Action(a) => a, + ScriptOp::Listen(l) => panic!("unexpected listener {l:?}"), + }) + .collect() +} + +/// The first problem: (line, column, message). +fn err(src: &str) -> (u32, u32, String) { + match compile(src) { + Ok(c) => panic!("{src:?} compiled to {c:?}"), + Err(p) => { + let f = p.first().cloned().unwrap_or_else(|| Problem::whole("none")); + (f.line, f.column, f.message) + } + } +} + +fn t(s: &str) -> Target { + Target::new(s) +} + +#[test] +fn timeline_calls_lower_to_actions() { + let a = actions("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();"); + assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }, Action::NextFrame { target: t("") }, Action::PrevFrame { target: t("") }, Action::NextScene, Action::PrevScene]); + // Frames are 1-based in ActionScript, 0-based in the IR; strings are labels. + let a = actions(r#"gotoAndStop(1); gotoAndPlay("run"); gotoAndPlay(12, "Scene 2"); gotoAndStop('end', null); gotoAndStop(2 + 3);"#); + assert_eq!( + a, + vec![ + Action::GotoAndStop { target: t(""), frame: FrameRef::Number(0), scene: None }, + Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("run".into()), scene: None }, + Action::GotoAndPlay { target: t(""), frame: FrameRef::Number(11), scene: Some("Scene 2".into()) }, + Action::GotoAndStop { target: t(""), frame: FrameRef::Label("end".into()), scene: None }, + Action::GotoAndStop { target: t(""), frame: FrameRef::Number(4), scene: None }, + ] + ); +} + +#[test] +fn instance_paths_become_targets() { + let a = actions("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();"); + let targets: Vec = a.iter().map(|a| a.target().map(|t| t.0.clone()).unwrap_or_default()).collect(); + assert_eq!(targets, ["hero_mc", "hero_mc.arm_mc", "parent", "parent.parent", "root.menu", "root", "root", "parent.door"]); + assert!(a.iter().all(|x| x.check().is_ok())); +} + +#[test] +fn properties_are_set_to_values() { + let a = actions("hero_mc.x = 100;\nhero_mc.y = -20.5;\nhero_mc.alpha = .5;\nhero_mc.visible = false;\ndoor.rotation = 45;\ndoor.scaleX = 2; door.scaleY = 1.5\nalpha = 0.25;"); + assert_eq!( + a, + vec![ + Action::SetProperty { target: t("hero_mc"), property: Property::X, value: 100.0 }, + Action::SetProperty { target: t("hero_mc"), property: Property::Y, value: -20.5 }, + Action::SetProperty { target: t("hero_mc"), property: Property::Alpha, value: 0.5 }, + Action::SetProperty { target: t("hero_mc"), property: Property::Visible, value: 0.0 }, + Action::SetProperty { target: t("door"), property: Property::Rotation, value: 45.0 }, + Action::SetProperty { target: t("door"), property: Property::ScaleX, value: 2.0 }, + Action::SetProperty { target: t("door"), property: Property::ScaleY, value: 1.5 }, + Action::SetProperty { target: t(""), property: Property::Alpha, value: 0.25 }, + ] + ); +} + +#[test] +fn trace_writes_literals_and_their_sums_as_actionscript_does() { + let msgs: Vec = actions(r#"trace("hello"); trace('a' + 1 + 2); trace(1 + 2 + "a"); trace(0.1, true, null, undefined); trace(1e21, 1e-7, -0, 5 / 2, 7 % 4); trace(); trace("tab\there é \x41");"#) + .into_iter() + .map(|a| match a { + Action::Trace { message } => message, + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(msgs, ["hello", "a12", "3a", "0.1 true null undefined", "1e+21 1e-7 0 2.5 3", "", "tab\there é A"]); +} + +#[test] +fn listeners_lower_to_handlers_with_their_bodies() { + let src = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(e:MouseEvent):void {\n\tgotoAndPlay(\"walk\"); // on\n\ttrace(\"go\");\n}\nmenu.btn.addEventListener(MouseEvent.ROLL_OVER, function (event:MouseEvent):void { MovieClip(event.currentTarget).gotoAndStop(2); });\naddEventListener(\"mouseDown\", onPlay);"; + let c = ok(src); + assert_eq!(c.ops.len(), 4); + assert_eq!(c.ops[0], ScriptOp::Action(Action::Stop { target: t("") })); + let ScriptOp::Listen(l) = &c.ops[1] else { panic!("{:?}", c.ops[1]) }; + assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("play_btn", ButtonEvent::Click, "onPlay")); + assert_eq!(*l.actions, vec![Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("walk".into()), scene: None }, Action::Trace { message: "go".into() }]); + let ScriptOp::Listen(l) = &c.ops[2] else { panic!() }; + // `currentTarget` is the instance listened to, named from the script's timeline. + assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("menu.btn", ButtonEvent::Over, "function at line 10")); + assert_eq!(*l.actions, vec![Action::GotoAndStop { target: t("menu.btn"), frame: FrameRef::Number(1), scene: None }]); + let ScriptOp::Listen(l) = &c.ops[3] else { panic!() }; + assert_eq!((l.target.is_this(), l.event), (true, ButtonEvent::Press)); + assert!(l.describe().starts_with("On press (this): Go to “walk” and play"), "{}", l.describe()); + for (k, e) in [("MOUSE_UP", ButtonEvent::Release), ("ROLL_OUT", ButtonEvent::Out), ("MOUSE_OVER", ButtonEvent::Over), ("MOUSE_OUT", ButtonEvent::Out)] { + let c = ok(&format!("b.addEventListener(MouseEvent.{k}, f, false, 0, true); function f(e) {{}}")); + assert!(matches!(&c.ops[0], ScriptOp::Listen(l) if l.event == e), "{k}"); + } +} + +#[test] +fn own_functions_run_where_they_are_called() { + let a = actions("function go(n:int = 1):void { gotoAndStop(3); return; trace(\"never\"); }\ngo();\nfunction twice() { go(); go(); }\ntwice();"); + assert_eq!(a.len(), 3, "{a:?}"); + assert!(a.iter().all(|x| matches!(x, Action::GotoAndStop { frame: FrameRef::Number(2), .. }))); +} + +#[test] +fn calls_outside_the_movie_are_ignored_and_noted() { + let c = ok("navigateToURL(new URLRequest(\"https://example.com\"), \"_blank\");\nflash.net.navigateToURL(x);\nExternalInterface.call(\"f\");\nfscommand(\"quit\");\nbtn.buttonMode = true;\nstop();"); + assert_eq!(c.ops, vec![ScriptOp::Action(Action::Stop { target: t("") })]); + let lines: Vec = c.notes.iter().map(|n| n.line).collect(); + assert_eq!(lines, [1, 2, 3, 4, 5]); + assert!(c.notes[0].message.contains("navigateToURL") && c.notes[0].message.contains("ignored"), "{:?}", c.notes); +} + +#[test] +fn comments_white_space_and_semicolons_are_read_as_actionscript_does() { + // Line and block comments, CR LF line ends, no semicolons, a BOM, empty statements. + let a = actions("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\""); + assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }]); + assert_eq!(err("stop() play()"), (1, 8, "expected `;` or a new line, found `play`".into())); +} + +#[test] +fn every_problem_says_where_it_is() { + let cases: &[(&str, u32, u32, &str)] = &[ + ("stop();\nif (x) { play(); }", 2, 1, "`if` statements aren't supported yet"), + ("var n:int = 0;", 1, 1, "variables (`var`) aren't supported yet"), + (" for (var i = 0; i < 3; i++) {}", 1, 3, "`for` loops aren't supported yet"), + ("while (true) stop();", 1, 1, "`while` loops aren't supported yet"), + ("switch (x) { case 1: stop(); }", 1, 1, "`switch` statements aren't supported yet"), + ("hero.x += 5;", 1, 1, "`+=` reads a value first"), + ("hero.width = 5;", 1, 1, "setting `width` isn't supported yet"), + ("score = 5;", 1, 1, "setting `score` isn't supported: variables"), + ("foo();", 1, 1, "`foo` isn't declared in this frame script"), + ("hero.addChild(x);", 1, 1, "calling `addChild` isn't supported"), + ("gotoAndStop(0);", 1, 13, "a frame number is a whole number from 1"), + ("gotoAndStop(1.5);", 1, 13, "a frame number is a whole number"), + ("gotoAndStop(frame);", 1, 13, "reading `frame` isn't supported"), + ("gotoAndStop();", 1, 1, "`gotoAndStop` takes a frame"), + ("stop(1);", 1, 1, "`stop()` takes no arguments"), + ("hero.nextScene();", 1, 1, "call `nextScene()` in the main timeline's own script"), + ("trace(hero.x);", 1, 7, "reading properties isn't supported"), + ("trace([1]);", 1, 7, "only values written out"), + ("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "the stage isn't supported"), + ("b.addEventListener(Event.ENTER_FRAME, f); function f(e) {}", 1, 20, "listening for Event.ENTER_FRAME isn't supported yet"), + ("b.addEventListener(MouseEvent.CLICK, nope);", 1, 38, "`nope` isn't a function declared"), + ("b.addEventListener(MouseEvent.CLICK, f); function f() { stop(); }", 1, 42, "a listener function takes the event"), + ("b.addEventListener(MouseEvent.CLICK, f, true); function f(e) {}", 1, 41, "capture-phase listeners"), + ("b.addEventListener(MouseEvent.CLICK, f); function f(e) { trace(e.target.name); }", 1, 64, "reading the event `e`"), + ("b.addEventListener(MouseEvent.CLICK, f); function f(e) { e.target.play(); }", 1, 58, "`target` can be a part inside"), + ("b.addEventListener(MouseEvent.CLICK, f); function f(e) { c.addEventListener(MouseEvent.CLICK, f); }", 1, 58, "adding a listener from inside a listener"), + ("b.removeEventListener(MouseEvent.CLICK, f);", 1, 1, "removing listeners isn't supported yet"), + ("function f() { f(); } f();", 1, 16, "`f` calls itself"), + ("function stop() {}", 1, 1, "a function named `stop` would hide"), + ("function f() {} function f() {}", 1, 17, "`f` is declared twice"), + ("function f() { function g() {} } f();", 1, 16, "functions declared inside functions"), + ("function f(n) { n.play(); } f(1);", 1, 17, "reading the parameter `n`"), + ("hero_mc[\"arm\"].play();", 1, 1, "this isn't an instance"), + ("hero_mc.x = \"10\";", 1, 13, "`x` is set to a number"), + ("hero_mc.x = 1 / 0;", 1, 13, "the value must be a finite number"), + ("package { }", 1, 1, "`package` belongs to class files"), + ("class Hero {}", 1, 1, "`class` belongs to class files"), + ("public function f() {}", 1, 1, "`public` declarations belong to classes"), + ("stop(;", 1, 6, "expected an expression, found `;`"), + ("stop(", 1, 6, "expected an expression, found the end of the script"), + ("{ stop();", 1, 10, "expected `}` to close the block"), + ("trace(\"open);", 1, 7, "this string is never closed"), + ("/* never", 1, 1, "this comment is never closed"), + ("trace(3x);", 1, 8, "a number can't run straight into a name"), + ("stop(); #", 1, 9, "unexpected character '#'"), + ("var re = /ab+c/;", 1, 10, "regular expressions aren't supported"), + ("1 = 2;", 1, 3, "the left side of this assignment can't be assigned to"), + ("x++;", 1, 1, "`++` and `--` read a value first"), + ("é.play();", 1, 1, "`é` isn't an instance name AniCraft can address"), + ("\tstop();\n\t\tif (a) {}", 2, 3, "`if` statements"), + ]; + for (src, line, col, msg) in cases { + let (l, c, m) = err(src); + assert!(m.starts_with(msg) && (l, c) == (*line, *col), "{src:?}: got {l}:{c} {m:?}, want {line}:{col} {msg:?}"); + } +} + +#[test] +fn every_problem_is_listed_and_nothing_half_runs() { + let p = compile("stop();\nvar a = 1;\nif (a) {}\nplay();\nhero.width = 3;").unwrap_err(); + let at: Vec<(u32, u32)> = p.iter().map(|p| (p.line, p.column)).collect(); + assert_eq!(at, [(2, 1), (3, 1), (5, 1)]); + assert_eq!(p[0].to_string(), "line 2, column 1: variables (`var`) aren't supported yet"); + let many: String = (0..200).map(|i| format!("var v{i} = {i};\n")).collect(); + assert_eq!(compile(&many).unwrap_err().len(), MAX_PROBLEMS); +} + +#[test] +fn number_text_matches_actionscript() { + for (n, s) in [(0.0, "0"), (-0.0, "0"), (5.0, "5"), (-3.25, "-3.25"), (0.1 + 0.2, "0.30000000000000004"), (1e21, "1e+21"), (1.5e-7, "1.5e-7"), (123456789012.0, "123456789012"), (f64::NAN, "NaN"), (f64::NEG_INFINITY, "-Infinity"), (0.000001, "0.000001")] { + assert_eq!(lower::number_text(n), s, "{n}"); + } +} + +#[test] +fn limits_are_problems_not_crashes() { + let deep = format!("trace({}1{});", "(".repeat(10_000), ")".repeat(10_000)); + assert!(err(&deep).2.contains("nested more than")); + let deep = format!("{}stop();{}", "{".repeat(10_000), "}".repeat(10_000)); + assert!(err(&deep).2.contains("nested more than")); + let deep = format!("trace({}1);", "-".repeat(100_000)); + assert!(err(&deep).2.contains("nested more than")); + let deep = format!("{}1;", "a = ".repeat(10_000)); + assert!(err(&deep).2.contains("nested more than")); + let deep = format!("b.addEventListener(\"click\", {}", "function (e) { ".repeat(5_000)); + assert!(err(&deep).2.contains("nested more than")); + let long = "stop();".repeat(MAX_RUN_BYTES / 7 + 1); + assert!(err(&long).2.contains("longer than 256 KiB")); + let tokens = ";".repeat(MAX_TOKENS + 1); + assert!(err(&tokens).2.contains("tokens")); + let steps = "stop();".repeat(crate::MAX_ACTIONS + 1); + assert!(err(&steps).2.contains("at most 256 steps")); + // Calls that fan out are bounded, however deep they could go. + let mut src = String::from("function f0() { stop(); }\n"); + for i in 1..16 { + src.push_str(&format!("function f{i}() {{ {} }}\n", format!("f{}(); ", i - 1).repeat(8))); + } + src.push_str("f15();"); + let t0 = std::time::Instant::now(); + assert!(compile(&src).is_err()); + assert!(t0.elapsed().as_secs_f32() < 5.0); +} + +/// A small deterministic generator (no clock, no randomness crate). +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn pick<'a>(&mut self, v: &[&'a str]) -> &'a str { + v.get(self.next() as usize % v.len()).copied().unwrap_or("") + } +} + +#[test] +fn hostile_input_never_panics_and_ends_quickly() { + const PIECES: [&str; 64] = [ + "stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@", + ]; + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let t0 = std::time::Instant::now(); + let mut compiled = 0; + for _ in 0..4_000 { + let n = rng.next() as usize % 80; + let src: String = (0..n).map(|_| rng.pick(&PIECES)).collect(); + if compile(&src).is_ok() { + compiled += 1; + } + } + // Raw bytes as text, too. + for _ in 0..1_000 { + let n = rng.next() as usize % 200; + let bytes: Vec = (0..n).map(|_| rng.next() as u8).collect(); + let _ = compile(&String::from_utf8_lossy(&bytes)); + } + assert!(compiled > 0, "some soup should compile (empty scripts at least)"); + assert!(t0.elapsed().as_secs_f32() < 20.0, "fuzzing took {:?}", t0.elapsed()); +} + +#[test] +fn compiles_once_per_script() { + let s = crate::SourceScript::new(crate::Language::ActionScript3, "stop();"); + let a: *const crate::CompileResult = s.compiled(); + let b: *const crate::CompileResult = s.compiled(); + assert!(std::ptr::eq(a, b)); + assert!(s.runs()); + // A copy compiles on its own (its text may change); equality ignores the cache. + let c = s.clone(); + assert_eq!(c, s); + assert!(!crate::SourceScript::new(crate::Language::ActionScript1or2, "stop();").runs()); +} diff --git a/crates/actions/src/lib.rs b/crates/actions/src/lib.rs index 29ed275e..7f0eb89f 100644 --- a/crates/actions/src/lib.rs +++ b/crates/actions/src/lib.rs @@ -5,17 +5,20 @@ //! instance by its instance-name path, react to button events, write `trace` output and set a //! few instance properties. Every front end speaks it: frame actions edited in the Actions //! panel, WebAssembly frame scripts (which emit actions through the plug-in ABI) and, later, the -//! ActionScript subset and the HTML canvas exporter. The player in `anicraft-doc` runs it. -//! Scripts in another language that AniCraft keeps but doesn't run yet ([`SourceScript`], ADR -//! 0013 tier 1) sit beside the actions in [`FrameScript`]. +//! ActionScript subset ([`as3`], ADR 0013 tier 2) and the HTML canvas exporter. The player in +//! `anicraft-doc` runs it. Scripts kept as written ([`SourceScript`], ADR 0013 tier 1) sit beside +//! the actions in [`FrameScript`]; those in the ActionScript 3.0 subset compile to actions once +//! and run. //! //! This crate knows nothing about documents: targets are name paths and frames are numbers or //! labels, resolved by the player when an action runs. Frames are 0-based, as everywhere in //! the engine (the app shows them 1-based). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod as3; + use serde::{Deserialize, Serialize}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; /// Most actions in one list (a keyframe's, or one event handler's). pub const MAX_ACTIONS: usize = 256; @@ -544,18 +547,67 @@ impl Language { } /// A script kept verbatim with the document (ADR 0013 tier 1): its text exactly as written, -/// and its language. AniCraft shows and edits it; nothing runs it yet. +/// and its language. AniCraft shows and edits it, and runs it when it is in the ActionScript 3.0 +/// subset ([`SourceScript::compiled`], tier 2). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct SourceScript { #[serde(default)] pub language: Language, #[serde(default)] pub text: String, + /// The script compiled, made the first time it is asked for. A pure function of the + /// language and text, so it is never saved and never compared. + #[serde(skip)] + compiled: CompileCache, +} + +/// What [`SourceScript::compiled`] gives: the script's steps, or why it doesn't run. +pub type CompileResult = Result>; + +/// A lazily filled slot. Cloning gives an empty one, so a copy whose text is then changed +/// compiles afresh; comparing ignores it. +#[derive(Default)] +struct CompileCache(OnceLock); + +impl Clone for CompileCache { + fn clone(&self) -> Self { + CompileCache::default() + } +} + +impl PartialEq for CompileCache { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for CompileCache {} + +impl std::fmt::Debug for CompileCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(if self.0.get().is_some() { "compiled" } else { "not compiled" }) + } } impl SourceScript { pub fn new(language: Language, text: impl Into) -> SourceScript { - SourceScript { language, text: text.into() } + SourceScript { language, text: text.into(), compiled: CompileCache::default() } + } + + /// The script compiled to actions (ADR 0013 tier 2), or the problems that keep it from + /// running. Compiled once per script: the document shares scripts by `Arc`, so undo + /// snapshots, the render thread and Test Movie all reuse it. + pub fn compiled(&self) -> &CompileResult { + self.compiled.0.get_or_init(|| match self.language { + Language::ActionScript3 => as3::compile(&self.text), + Language::ActionScript1or2 => Err(vec![as3::Problem::whole("ActionScript 1.0 and 2.0 don't run; AniCraft runs a subset of ActionScript 3.0")]), + Language::Other => Err(vec![as3::Problem::whole("scripts in other languages don't run; AniCraft runs a subset of ActionScript 3.0")]), + }) + } + + /// Whether it runs (it compiled). + pub fn runs(&self) -> bool { + self.compiled().is_ok() } pub fn check(&self) -> Result<(), String> { if self.text.trim().is_empty() { @@ -573,8 +625,8 @@ impl SourceScript { } /// What runs when the playhead enters a keyframe: a list of actions, a plug-in's entry point -/// (a frame script), or a script kept verbatim that doesn't run yet (ADR 0013 tier 1). One -/// field keeps "one of these" true by construction. +/// (a frame script), or a script kept verbatim (ADR 0013 tier 1), which runs when it is in the +/// ActionScript 3.0 subset (tier 2). One field keeps "one of these" true by construction. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum FrameScript { @@ -626,7 +678,8 @@ impl FrameScript { FrameScript::Plugin(p) => format!("Frame script {} · {}", p.id, p.entry), FrameScript::Source(s) => { let n = s.lines(); - format!("Script in {} ({n} {}), kept, not run", s.language.label(), if n == 1 { "line" } else { "lines" }) + let state = if s.runs() { "runs" } else { "kept, not run" }; + format!("Script in {} ({n} {}), {state}", s.language.label(), if n == 1 { "line" } else { "lines" }) } } } @@ -754,7 +807,9 @@ mod tests { let back: FrameScript = serde_json::from_value(v).unwrap(); assert_eq!(back, s); assert_eq!(back.source().unwrap().text, text, "byte for byte"); - assert_eq!(s.describe(), "Script in ActionScript 3.0 (3 lines), kept, not run"); + assert_eq!(s.describe(), "Script in ActionScript 3.0 (3 lines), runs"); + let other = FrameScript::Source(Arc::new(SourceScript::new(Language::ActionScript1or2, "stop();"))); + assert_eq!(other.describe(), "Script in ActionScript 1.0 & 2.0 (1 line), kept, not run"); assert!(s.actions().is_empty() && !s.needs_repair()); // The language defaults to ActionScript 3.0; unknown ones are refused. let d: SourceScript = serde_json::from_value(json!({"text": "x"})).unwrap(); diff --git a/crates/doc/src/armature.rs b/crates/doc/src/armature.rs new file mode 100644 index 00000000..61d9123d --- /dev/null +++ b/crates/doc/src/armature.rs @@ -0,0 +1,490 @@ +//! Armatures (ADR 0043): bones that join symbol instances on an armature layer, poses that +//! turn them, and inverse kinematics that finds a pose from a dragged bone end. +//! +//! An armature is a tree of [`Bone`]s on a [`LayerKind::Armature`](crate::LayerKind) layer. +//! Each bone starts at a **joint** on its *parent* instance (its head) and ends on its *child* +//! instance (its tail); the child turns about the joint, carrying everything below it. An +//! instance is the child of at most one bone, and the instance no bone ends in is the root: it +//! keeps its own transform, so moving it moves the whole armature. +//! +//! A **pose** is a joint angle per bone ([`Pose`]), stored on each keyframe of the armature +//! layer and tweened between keyframes with the keyframe's easing. Angles are relative: 0 is the +//! bone as it was drawn, measured against its parent, so turning a parent carries its children. +//! Forward kinematics ([`place`]) turns a pose into the instances' transforms; it is pure, and +//! [`crate::evaluate_layer_elements`] applies it, so every renderer, export and the player see +//! the posed instances. +//! +//! Inverse kinematics ([`solve`]) is cyclic coordinate descent (CCD): sweeping from the dragged +//! bone up its chain, each joint turns so the effector points at the target, clamped to the +//! joint's limits. It works on joint angles directly, so limits are a clamp per step and the +//! result is a pose by construction. + +use crate::{Element, ElementId, Keyframe, Layer}; +use anicraft_geom::{Affine, Vec2}; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +/// Most bones in one armature. +pub const MAX_BONES: usize = 256; +/// Longest bone name kept (bytes). +pub const MAX_NAME: usize = 256; +/// Joint limits stay within a turn either way (radians). +pub const MAX_LIMIT: f32 = std::f32::consts::TAU; +/// Largest joint angle kept (radians): many turns, never infinity. +pub const MAX_ANGLE: f32 = 64.0 * std::f32::consts::TAU; +/// IK stops once the effector is this close to its target (layer units, pixels). +pub const IK_TOLERANCE: f32 = 0.01; +/// Most CCD sweeps one solve takes. +pub const IK_SWEEPS: usize = 2048; +/// How often a stalled solve bends its joints to get going again, and by how much (radians). +const IK_KICKS: usize = 4; +const IK_KICK: f32 = 0.3; + +/// Unique id of a bone within a document (from the document's id counter). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct BoneId(pub u64); + +/// How far a joint may turn either way from where the bone was drawn (radians, `min ≤ 0 ≤ max` +/// is usual but not required). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Limits { + pub min: f32, + pub max: f32, +} + +impl Limits { + /// `a` kept inside the limits. + pub fn clamp(&self, a: f32) -> f32 { + a.clamp(self.min, self.max) + } + + /// Finite, ordered and within [`MAX_LIMIT`]; `None` when nothing sane is left. + pub fn sanitized(self) -> Option { + if !(self.min.is_finite() && self.max.is_finite()) { + return None; + } + let (a, b) = (self.min.clamp(-MAX_LIMIT, MAX_LIMIT), self.max.clamp(-MAX_LIMIT, MAX_LIMIT)); + Some(Limits { min: a.min(b), max: a.max(b) }) + } +} + +/// A bone: from a joint on its parent instance to its child instance, which it turns. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Bone { + pub id: BoneId, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub name: String, + /// The instance the bone starts on (the joint is a point on it). + pub parent: ElementId, + /// The instance the bone moves. + pub child: ElementId, + /// The joint, in the parent instance's local space: the child turns about it. + pub head: Vec2, + /// The bone's end, in the child instance's local space (where a drag pulls it). + pub tail: Vec2, + /// The child's transform in the parent's local space at joint angle 0 (as it was drawn). + pub rest: Affine, + /// How far the joint may turn; `None`: freely. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limits: Option, + /// Pinned: inverse kinematics never turns it (nor the bones it hangs from), so its end stays + /// where it is while the rest of the armature follows a drag. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub pinned: bool, +} + +impl Bone { + /// `a` as this joint allows it (finite, within its limits). + pub fn allow(&self, a: f32) -> f32 { + let a = if a.is_finite() { a.clamp(-MAX_ANGLE, MAX_ANGLE) } else { 0.0 }; + self.limits.map_or(a, |l| l.clamp(a)) + } + + fn is_sane(&self) -> bool { + self.parent != self.child && self.head.x.is_finite() && self.head.y.is_finite() && self.tail.x.is_finite() && self.tail.y.is_finite() && self.rest.is_finite() && self.rest.inverse().is_some() + } +} + +/// The bones of an armature layer, each listed after the bone it hangs from. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Armature { + #[serde(default)] + pub bones: Vec, +} + +impl Armature { + pub fn is_empty(&self) -> bool { + self.bones.is_empty() + } + + pub fn bone(&self, id: BoneId) -> Option<&Bone> { + self.bones.iter().find(|b| b.id == id) + } + + pub fn bone_mut(&mut self, id: BoneId) -> Option<&mut Bone> { + self.bones.iter_mut().find(|b| b.id == id) + } + + /// The bone that moves instance `el` (ends in it), if any. + pub fn bone_into(&self, el: ElementId) -> Option<&Bone> { + self.bones.iter().find(|b| b.child == el) + } + + /// The bone `b` hangs from: the one that moves its parent instance. + pub fn parent_bone(&self, b: &Bone) -> Option<&Bone> { + self.bone_into(b.parent) + } + + /// Whether instance `el` is part of the armature. + pub fn contains(&self, el: ElementId) -> bool { + self.bones.iter().any(|b| b.parent == el || b.child == el) + } + + /// Every instance in the armature, roots first. + pub fn members(&self) -> Vec { + let mut out: Vec = self.roots(); + for b in &self.bones { + if !out.contains(&b.child) { + out.push(b.child); + } + } + out + } + + /// The instances no bone moves (one for an armature made with the Bone tool). + pub fn roots(&self) -> Vec { + let mut out = Vec::new(); + for b in &self.bones { + if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) { + out.push(b.parent); + } + } + out + } + + /// Bone `id` and every bone below it, in armature order. + pub fn subtree(&self, id: BoneId) -> Vec { + let mut inside: HashSet = HashSet::new(); + let mut out = Vec::new(); + for b in &self.bones { + if b.id == id || inside.contains(&b.parent) { + inside.insert(b.child); + out.push(b.id); + } + } + out + } + + /// The chain from bone `id` up to its root, `id` first (bounded by the bone count). + pub fn chain(&self, id: BoneId) -> Vec<&Bone> { + let mut out = Vec::new(); + let mut cur = self.bone(id); + while let Some(b) = cur { + if out.len() >= self.bones.len() || out.iter().any(|o: &&Bone| o.id == b.id) { + break; + } + out.push(b); + cur = self.parent_bone(b); + } + out + } + + /// Repairs a loaded armature: drops bones with non-finite numbers, repeated ids, a second + /// bone into one instance and bones in cycles; keeps every bone after its parent; keeps at + /// most [`MAX_BONES`]. Returns whether anything changed. + pub fn sanitize(&mut self) -> bool { + let before = self.bones.clone(); + let mut seen_id = HashSet::new(); + let mut seen_child = HashSet::new(); + let mut kept: Vec = Vec::new(); + for mut b in std::mem::take(&mut self.bones) { + if !b.is_sane() || !seen_id.insert(b.id) || !seen_child.insert(b.child) { + continue; + } + b.limits = b.limits.and_then(Limits::sanitized); + if b.name.len() > MAX_NAME { + let cut = (0..=MAX_NAME).rev().find(|&i| b.name.is_char_boundary(i)).unwrap_or(0); + b.name.truncate(cut); + } + kept.push(b); + } + // Order: a bone after the bone moving its parent. What never gets placed is a cycle. + let children: HashSet = kept.iter().map(|b| b.child).collect(); + let mut placed: HashSet = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(); + let mut ordered = Vec::with_capacity(kept.len()); + let mut rest = kept; + loop { + let (ready, wait): (Vec, Vec) = rest.into_iter().partition(|b| placed.contains(&b.parent)); + if ready.is_empty() { + break; + } + for b in ready { + placed.insert(b.child); + ordered.push(b); + } + rest = wait; + } + ordered.truncate(MAX_BONES); + self.bones = ordered; + self.bones != before + } +} + +/// One joint's angle in a pose (radians, 0 as drawn). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct JointAngle { + pub bone: BoneId, + pub angle: f32, +} + +/// A pose: joint angles by bone. A bone it doesn't list is as drawn (angle 0). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Pose(pub Vec); + +impl Pose { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The angle of bone `b` (0 when the pose doesn't list it). + pub fn angle(&self, b: BoneId) -> f32 { + self.0.iter().find(|j| j.bone == b).map_or(0.0, |j| j.angle) + } + + pub fn set(&mut self, b: BoneId, angle: f32) { + match self.0.iter_mut().find(|j| j.bone == b) { + Some(j) => j.angle = angle, + None => self.0.push(JointAngle { bone: b, angle }), + } + } + + /// Keeps only the bones in `keep`. + pub fn retain(&mut self, keep: impl Fn(BoneId) -> bool) { + self.0.retain(|j| keep(j.bone)); + } + + /// Every bone of `arm` at the angle its joint allows: the pose as it shows. + pub fn allowed(&self, arm: &Armature) -> Pose { + Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(self.angle(b.id)) }).collect()) + } + + /// The pose `t` of the way to `o`, joint by joint (angles blend linearly, so a joint that + /// turned a whole way round between keys turns that way in the tween). + pub fn lerp(&self, o: &Pose, t: f32, arm: &Armature) -> Pose { + Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(anicraft_geom::lerp(self.angle(b.id), o.angle(b.id), t)) }).collect()) + } + + /// Repairs a loaded pose: finite angles in range, one per bone, at most [`MAX_BONES`]. + /// Returns whether anything changed. + pub fn sanitize(&mut self) -> bool { + let before = self.0.len(); + let mut changed = false; + let mut seen = HashSet::new(); + self.0.retain(|j| seen.insert(j.bone)); + self.0.truncate(MAX_BONES); + for j in &mut self.0 { + let a = if j.angle.is_finite() { j.angle.clamp(-MAX_ANGLE, MAX_ANGLE) } else { 0.0 }; + if a.to_bits() != j.angle.to_bits() { + j.angle = a; + changed = true; + } + } + changed || self.0.len() != before + } +} + +/// `R(angle)` about point `j`. +fn turn_about(j: Vec2, angle: f32) -> Affine { + Affine::translate(j.x, j.y).mul(&Affine::rotate(angle)).mul(&Affine::translate(-j.x, -j.y)) +} + +/// Forward kinematics: the transform (in the layer's space) of every instance in `elements` +/// once `pose` turns the armature's joints. A root keeps its own transform; a child is placed +/// from its parent: `R_joint(angle) · parent · rest`. An instance whose parent isn't on the +/// keyframe keeps its own transform. +pub fn place(arm: &Armature, elements: &[Arc], pose: &Pose) -> HashMap { + let mut world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + for b in &arm.bones { + let Some(wp) = world.get(&b.parent).copied() else { continue }; + if !world.contains_key(&b.child) { + continue; + } + let j = wp.apply(b.head); + let wc = turn_about(j, b.allow(pose.angle(b.id))).mul(&wp.mul(&b.rest)); + if wc.is_finite() { + world.insert(b.child, wc); + } + } + world +} + +/// Puts the instances of `elements` where `pose` has them (copy-on-write: only instances that +/// move are cloned). Returns whether any moved. +pub fn apply(arm: &Armature, elements: &mut [Arc], pose: &Pose) -> bool { + if arm.is_empty() { + return false; + } + let world = place(arm, elements, pose); + let mut moved = false; + for e in elements.iter_mut() { + if arm.bone_into(e.id).is_none() { + continue; + } + if let Some(m) = world.get(&e.id) + && *m != e.transform + { + Arc::make_mut(e).transform = *m; + moved = true; + } + } + moved +} + +/// The pose layer `layer` has at `frame`: its covering keyframe's, or, inside a tween, the pose +/// between that keyframe's and the next one's at the tween's eased time. Exact at keyframes. +/// `None` without an armature or on an empty frame. +pub fn pose_at(layer: &Layer, frame: u32) -> Option { + let arm = layer.armature.as_deref().filter(|_| layer.kind == crate::LayerKind::Armature)?; + let idx = layer.keyframe_index_at(frame)?; + let kf: &Keyframe = layer.keyframes.get(idx)?; + let here = kf.pose.allowed(arm); + let (Some(tween), None) = (kf.tween, &kf.motion) else { return Some(here) }; + let Some(next) = layer.keyframes.get(idx + 1) else { return Some(here) }; + if next.start != kf.end() || frame == kf.start { + return Some(here); + } + let t = tween.easing.apply((frame - kf.start) as f32 / kf.duration.max(1) as f32); + Some(kf.pose.lerp(&next.pose, t, arm)) +} + +/// Where a bone is drawn: its joint (head) and end (tail), in the layer's space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BoneAt { + pub id: BoneId, + pub head: Vec2, + pub tail: Vec2, + /// The joint angle (radians, as the joint allows it). + pub angle: f32, +} + +/// Every bone's joint and end with the instances in `elements` placed as they show (posed: +/// what [`crate::evaluate_layer_elements`] gives on an armature layer). +pub fn bones_at(arm: &Armature, elements: &[Arc], pose: &Pose) -> Vec { + let world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + arm.bones + .iter() + .filter_map(|b| { + let (wp, wc) = (world.get(&b.parent)?, world.get(&b.child)?); + Some(BoneAt { id: b.id, head: wp.apply(b.head), tail: wc.apply(b.tail), angle: b.allow(pose.angle(b.id)) }) + }) + .collect() +} + +/// What a solve came to. +#[derive(Clone, Debug, PartialEq)] +pub struct Solved { + /// The new pose (every bone of the armature). + pub pose: Pose, + /// How far the effector ended from the target. + pub error: f32, + /// How many bones the drag could turn (0: the bone is pinned, or hangs from a pinned one). + pub chain: usize, +} + +/// The bones a drag of bone `id` may turn: `id` and the bones it hangs from, up to the first +/// that must stay put: a pinned bone, or one a pinned bone hangs from (turning it would move +/// the pinned bone). +pub fn movable_chain(arm: &Armature, id: BoneId) -> Vec<&Bone> { + let frozen: HashSet = arm.bones.iter().filter(|b| b.pinned).flat_map(|p| arm.chain(p.id)).map(|b| b.id).collect(); + arm.chain(id).into_iter().take_while(|b| !frozen.contains(&b.id)).collect() +} + +/// Inverse kinematics: the pose that brings point `local` of bone `id`'s child instance (its +/// local space; the bone's tail when dragging the bone end) to `target` (layer space), turning +/// only the bones [`movable_chain`] allows. `elements` are the keyframe's instances (the roots +/// at their own transforms), `pose` the pose to start from. Cyclic coordinate descent: each +/// sweep turns the joints from the dragged bone upward so the effector points at the target, +/// each clamped to its limits, until the effector is within [`IK_TOLERANCE`] or stops moving. +/// An unreachable target leaves the chain stretched straight toward it, the root where it was. +/// `None` when the armature has no bone `id` or its instances aren't on the keyframe. +pub fn solve(arm: &Armature, elements: &[Arc], pose: &Pose, id: BoneId, local: Vec2, target: Vec2) -> Option { + let bone = arm.bone(id)?; + if !(local.x.is_finite() && local.y.is_finite() && target.x.is_finite() && target.y.is_finite()) { + return None; + } + let chain: Vec<(BoneId, ElementId, Vec2)> = movable_chain(arm, id).iter().map(|b| (b.id, b.parent, b.head)).collect(); + let mut pose = pose.allowed(arm); + let effector = |pose: &Pose| -> Option<(HashMap, Vec2)> { + let world = place(arm, elements, pose); + let e = world.get(&bone.child)?.apply(local); + Some((world, e)) + }; + let (_, start) = effector(&pose)?; + let mut error = start.distance(target); + let mut best = (pose.clone(), error); + let mut kicks = 0; + for _ in 0..IK_SWEEPS { + if error < best.1 { + best = (pose.clone(), error); + } + if error <= IK_TOLERANCE || chain.is_empty() { + break; + } + let Some((world, mut e)) = effector(&pose) else { break }; + let mut turned = 0.0f32; + // From the dragged bone up: turning a joint moves only what is below it, so the joints + // above keep the places this sweep began with. + for &(b, parent, head) in &chain { + let Some(wp) = world.get(&parent) else { continue }; + let Some(joint) = arm.bone(b) else { continue }; + let j = wp.apply(head); + let (u, v) = (e - j, target - j); + if u.length() < 1e-6 || v.length() < 1e-6 { + continue; + } + let want = u.cross(v).atan2(u.dot(v)); + let cur = pose.angle(b); + let next = joint.allow(cur + want); + let by = next - cur; + if by != 0.0 { + pose.set(b, next); + e = turn_about(j, by).apply(e); + turned = turned.max(by.abs()); + } + } + let Some((_, e)) = effector(&pose) else { break }; + let was = error; + error = e.distance(target); + // Stuck: limits, a chain stretched straight at an unreachable target, or CCD's blind + // spot, a straight chain whose target lies on its own line (every joint sees angle 0). + // A few kicks bend the joints a little and descent goes on; the best pose seen wins. + if turned < 1e-7 || ((was - error).abs() < 1e-6 * was.max(1.0) && turned < 1e-4) { + if error < best.1 { + best = (pose.clone(), error); + } + if kicks >= IK_KICKS { + break; + } + kicks += 1; + for (i, &(b, _, _)) in chain.iter().enumerate() { + let Some(joint) = arm.bone(b) else { continue }; + let cur = pose.angle(b); + let kick = IK_KICK * if (i + kicks) % 2 == 0 { 1.0 } else { -1.0 }; + let next = joint.allow(cur + kick); + pose.set(b, if next != cur { next } else { joint.allow(cur - kick) }); + } + error = effector(&pose).map_or(error, |(_, e)| e.distance(target)); + continue; + } + } + if error < best.1 { + best = (pose, error); + } + Some(Solved { pose: best.0, error: best.1, chain: chain.len() }) +} + +#[cfg(test)] +#[path = "armature_tests.rs"] +mod tests; diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs new file mode 100644 index 00000000..56067e98 --- /dev/null +++ b/crates/doc/src/armature_tests.rs @@ -0,0 +1,256 @@ +//! Armatures, poses and inverse kinematics (ADR 0043). + +use super::*; +use crate::{BlendMode, ColorEffect, Document, Easing, ElementKind, Keyframe, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Symbol, SymbolId, SymbolKind, Timeline, Tween, evaluate, evaluate_layer_elements}; +use anicraft_geom::Path; +use std::f32::consts::FRAC_PI_2; + +const ROOT: ElementId = ElementId(10); +const ARM: ElementId = ElementId(11); +const HAND: ElementId = ElementId(12); +const B1: BoneId = BoneId(20); +const B2: BoneId = BoneId(21); +const SEG: SymbolId = SymbolId(1); + +fn instance(id: ElementId, x: f32, y: f32) -> Arc { + let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() }; + Arc::new(Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind }) +} + +fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone { + // Every segment is 100 px long from its registration point; bones join end to start. + Bone { id, name: String::new(), parent, child, head: Vec2::new(100.0, 0.0), tail: Vec2::new(100.0, 0.0), rest: Affine::translate(100.0, 0.0), limits: None, pinned: false } +} + +/// A three-segment chain lying along y = 100: the root from x = 100, the arm from 200 (its +/// joint), the hand from 300; the hand's end at 400. The arm and hand reach 200 px from the +/// shoulder joint at (200, 100). +fn chain() -> (Armature, Vec>) { + let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)] }; + (arm, vec![instance(ROOT, 100.0, 100.0), instance(ARM, 200.0, 100.0), instance(HAND, 300.0, 100.0)]) +} + +fn hand_end(arm: &Armature, els: &[Arc], pose: &Pose) -> Vec2 { + place(arm, els, pose)[&HAND].apply(Vec2::new(100.0, 0.0)) +} + +fn close(a: Vec2, b: Vec2, tol: f32) -> bool { + a.distance(b) <= tol +} + +#[test] +fn forward_kinematics_turns_children_about_their_joints() { + let (arm, els) = chain(); + let rest = place(&arm, &els, &Pose::default()); + assert!(close(rest[&HAND].translation(), Vec2::new(300.0, 100.0), 1e-4), "the rest pose is the drawing"); + let mut pose = Pose::default(); + pose.set(B1, FRAC_PI_2); + let w = place(&arm, &els, &pose); + // The arm turns a quarter clockwise about the shoulder (200, 100): it now points down. + assert!(close(w[&ARM].translation(), Vec2::new(200.0, 100.0), 1e-4)); + assert!(close(w[&HAND].translation(), Vec2::new(200.0, 200.0), 1e-3), "{:?}", w[&HAND]); + assert!(close(hand_end(&arm, &els, &pose), Vec2::new(200.0, 300.0), 1e-3)); + // The elbow turns relative to the arm: a quarter back makes the hand point right again. + pose.set(B2, -FRAC_PI_2); + assert!(close(hand_end(&arm, &els, &pose), Vec2::new(300.0, 200.0), 1e-3)); + // The root keeps its own transform. + assert_eq!(place(&arm, &els, &pose)[&ROOT], Affine::translate(100.0, 100.0)); +} + +#[test] +fn ik_reaches_a_reachable_target_within_half_a_pixel() { + let (arm, els) = chain(); + for target in [Vec2::new(300.0, 180.0), Vec2::new(150.0, 200.0), Vec2::new(250.0, 20.0), Vec2::new(390.0, 110.0), Vec2::new(210.0, 120.0)] { + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), target).unwrap(); + let end = hand_end(&arm, &els, &s.pose); + assert!(close(end, target, 0.5), "{target:?}: ended at {end:?} ({} px off)", s.error); + assert!((s.error - end.distance(target)).abs() < 1e-3); + assert_eq!(s.chain, 2); + // The root never moves. + assert_eq!(place(&arm, &els, &s.pose)[&ROOT], Affine::translate(100.0, 100.0)); + } +} + +#[test] +fn ik_respects_joint_limits() { + let (mut arm, els) = chain(); + let lim = Limits { min: -10f32.to_radians(), max: 10f32.to_radians() }; + arm.bone_mut(B2).unwrap().limits = Some(lim); + // A target that needs a sharp elbow: the elbow stops at its limit. + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 160.0)).unwrap(); + let a = s.pose.angle(B2); + assert!((lim.min..=lim.max).contains(&a), "elbow at {}°", a.to_degrees()); + // Evaluation clamps too, whatever a file says. + let mut wild = Pose::default(); + wild.set(B2, 3.0); + assert_eq!(wild.allowed(&arm).angle(B2), lim.max); + // A joint that may not turn at all keeps its angle. + arm.bone_mut(B1).unwrap().limits = Some(Limits { min: 0.0, max: 0.0 }); + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(300.0, 300.0)).unwrap(); + assert_eq!(s.pose.angle(B1), 0.0); +} + +#[test] +fn an_unreachable_target_stretches_the_chain_straight_and_the_root_stays() { + let (arm, els) = chain(); + let target = Vec2::new(700.0, 500.0); + let mut start = Pose::default(); + start.set(B1, 0.7); + start.set(B2, -1.2); + let s = solve(&arm, &els, &start, B2, Vec2::new(100.0, 0.0), target).unwrap(); + let w = place(&arm, &els, &s.pose); + let (shoulder, elbow, end) = (Vec2::new(200.0, 100.0), w[&HAND].translation(), hand_end(&arm, &els, &s.pose)); + let (d1, d2, dt) = ((elbow - shoulder).normalized(), (end - elbow).normalized(), (target - shoulder).normalized()); + assert!(d1.cross(d2).abs() < 1e-3 && d1.dot(d2) > 0.999, "straight: {d1:?} {d2:?}"); + assert!(d1.dot(dt) > 0.999, "pointing at the target"); + assert!((s.error - (target.distance(shoulder) - 200.0)).abs() < 0.05, "{}", s.error); + assert_eq!(w[&ROOT], Affine::translate(100.0, 100.0), "the root stays put"); +} + +#[test] +fn pinned_bones_stay_put() { + let (mut arm, els) = chain(); + arm.bone_mut(B1).unwrap().pinned = true; + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(250.0, 180.0)).unwrap(); + assert_eq!(s.pose.angle(B1), 0.0, "the pinned shoulder never turns"); + assert_eq!(s.chain, 1); + // Dragging the pinned bone itself moves nothing. + let s = solve(&arm, &els, &Pose::default(), B1, Vec2::new(100.0, 0.0), Vec2::new(0.0, 0.0)).unwrap(); + assert_eq!((s.chain, s.pose.angle(B1)), (0, 0.0)); + // A pin locks the bones it hangs from too. + arm.bone_mut(B1).unwrap().pinned = false; + arm.bone_mut(B2).unwrap().pinned = true; + assert!(movable_chain(&arm, B1).is_empty(), "turning the shoulder would move the pinned hand"); + assert!(movable_chain(&arm, B2).is_empty()); +} + +/// An armature layer: the chain at frame 0 posed straight, at frame 10 with the shoulder a +/// quarter turned, tweened with `easing`. +fn armature_layer(easing: Easing) -> Layer { + let (arm, els) = chain(); + let mut l = Layer::new(LayerId(1), "Armature_1"); + l.kind = LayerKind::Armature; + l.armature = Some(Arc::new(arm)); + let mut a = Keyframe::new(0, 10); + a.elements = els.clone(); + a.tween = Some(Tween { easing, ..Tween::default() }); + let mut b = Keyframe::new(10, 5); + b.elements = els; + b.pose.set(B1, FRAC_PI_2); + l.keyframes = vec![Arc::new(a), Arc::new(b)]; + l +} + +#[test] +fn poses_tween_and_are_exact_at_keyframes() { + let l = armature_layer(Easing::Linear); + assert_eq!(pose_at(&l, 0).unwrap().angle(B1), 0.0); + assert_eq!(pose_at(&l, 10).unwrap().angle(B1), FRAC_PI_2, "exact at the key"); + assert_eq!(pose_at(&l, 14).unwrap().angle(B1), FRAC_PI_2, "held after the last key"); + assert!((pose_at(&l, 5).unwrap().angle(B1) - FRAC_PI_2 * 0.5).abs() < 1e-6); + // The existing easing shapes the tween. + let eased = armature_layer(Easing::QuadIn); + assert!((pose_at(&eased, 5).unwrap().angle(B1) - FRAC_PI_2 * 0.25).abs() < 1e-6); + // Evaluation places the instances by the pose: at the key, exactly forward kinematics. + let (_, els) = evaluate_layer_elements(&l, 10).unwrap(); + let hand = els.iter().find(|e| e.id == HAND).unwrap(); + assert!(close(hand.transform.translation(), Vec2::new(200.0, 200.0), 1e-3)); + // Half way the hand has swung through 45° about the shoulder. + let (_, els) = evaluate_layer_elements(&l, 5).unwrap(); + let hand = els.iter().find(|e| e.id == HAND).unwrap(); + let r = std::f32::consts::FRAC_1_SQRT_2 * 100.0; + assert!(close(hand.transform.translation(), Vec2::new(200.0 + r, 100.0 + r), 1e-3), "{:?}", hand.transform); + // Without the tween the first pose holds. + let mut held = armature_layer(Easing::Linear); + Arc::make_mut(&mut held.keyframes[0]).tween = None; + assert_eq!(pose_at(&held, 9).unwrap().angle(B1), 0.0); +} + +#[test] +fn every_export_sees_the_pose() { + let mut d = Document::default(); + let mut seg = Layer::new(LayerId(2), "seg"); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); + seg.keyframes = vec![Arc::new(k)]; + d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(seg)] } })); + d.timeline_mut(0).layers = vec![Arc::new(armature_layer(Easing::Linear))]; + d.sanitize(); + let dl = evaluate(&d, 10); + let hand = dl.items.iter().find(|i| i.element == HAND).unwrap(); + assert!(close(hand.transform.apply(Vec2::new(100.0, 0.0)), Vec2::new(200.0, 300.0), 1e-3), "the display list draws the posed hand"); + // The file keeps the armature and poses. + let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap(); + assert_eq!(back, d); + assert_eq!(back.timeline(0).layers[0].keyframes[1].pose.angle(B1), FRAC_PI_2); +} + +#[test] +fn sanitize_repairs_hostile_armatures() { + let (mut arm, _) = chain(); + // Listed child first, a cycle, a second bone into the hand, a bone into itself, NaN. + let mut cyc = bone(BoneId(30), ElementId(40), ElementId(41)); + cyc.head = Vec2::new(0.0, 0.0); + let back = bone(BoneId(31), ElementId(41), ElementId(40)); + let twice = bone(BoneId(32), ROOT, HAND); + let selfie = bone(BoneId(33), ROOT, ROOT); + let mut nan = bone(BoneId(34), HAND, ElementId(50)); + nan.rest = Affine { m: [f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0] }; + let mut wide = bone(BoneId(35), HAND, ElementId(51)); + wide.limits = Some(Limits { min: 100.0, max: f32::NEG_INFINITY }); + let mut limited = bone(BoneId(36), HAND, ElementId(52)); + limited.limits = Some(Limits { min: 1.0, max: -1.0 }); + arm.bones.reverse(); + arm.bones.extend([cyc, back, twice, selfie, nan, wide, limited]); + assert!(arm.sanitize()); + let ids: Vec = arm.bones.iter().map(|b| b.id.0).collect(); + assert_eq!(ids, vec![20, 21, 35, 36], "ordered parent first; cycles, repeats and NaN gone"); + assert_eq!(arm.bone(BoneId(35)).unwrap().limits, None); + assert_eq!(arm.bone(BoneId(36)).unwrap().limits, Some(Limits { min: -1.0, max: 1.0 })); + assert!(!arm.sanitize(), "sanitizing twice changes nothing"); + let mut p = Pose(vec![JointAngle { bone: B1, angle: f32::NAN }, JointAngle { bone: B1, angle: 1.0 }, JointAngle { bone: B2, angle: 1e30 }]); + assert!(p.sanitize()); + assert_eq!(p.0.len(), 2); + assert_eq!((p.angle(B1), p.angle(B2)), (0.0, MAX_ANGLE)); + // Hostile solves return nothing rather than panicking. + let (arm, els) = chain(); + assert!(solve(&arm, &els, &Pose::default(), BoneId(999), Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)).is_none()); + assert!(solve(&arm, &els, &Pose::default(), B2, Vec2::new(f32::NAN, 0.0), Vec2::new(1.0, 1.0)).is_none()); + assert!(solve(&arm, &[], &Pose::default(), B2, Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)).is_none()); +} + +#[test] +fn tree_queries() { + let (arm, _) = chain(); + assert_eq!(arm.roots(), vec![ROOT]); + assert_eq!(arm.members(), vec![ROOT, ARM, HAND]); + assert_eq!(arm.subtree(B1), vec![B1, B2]); + assert_eq!(arm.subtree(B2), vec![B2]); + assert_eq!(arm.chain(B2).iter().map(|b| b.id).collect::>(), vec![B2, B1]); + assert_eq!(arm.bone_into(HAND).map(|b| b.id), Some(B2)); + assert!(arm.contains(ROOT) && !arm.contains(ElementId(99))); +} + +/// Long chains and targets on a straight chain's own line (CCD's blind spot) still converge. +#[test] +fn long_chains_and_collinear_targets_converge() { + for n in [2usize, 10, 64] { + let mut bones = Vec::new(); + let mut els = vec![instance(ElementId(1000), 0.0, 0.0)]; + for i in 0..n { + let (p, c) = (ElementId(1000 + i as u64), ElementId(1001 + i as u64)); + bones.push(Bone { id: BoneId(5000 + i as u64), ..bone(BoneId(0), p, c) }); + els.push(instance(c, 100.0 * (i + 1) as f32, 0.0)); + } + let arm = Armature { bones }; + let last = BoneId(5000 + n as u64 - 1); + let reach = 100.0 * n as f32; + for k in 0..12 { + // k = 0: straight ahead along the chain. + let a = k as f32 * 0.55; + let target = Vec2::new(100.0 + reach * 0.6 * a.cos(), reach * 0.6 * a.sin()); + let s = solve(&arm, &els, &Pose::default(), last, Vec2::new(100.0, 0.0), target).unwrap(); + assert!(s.error <= 0.5, "{n} bones to {target:?}: {} px off", s.error); + } + } +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 176b9d91..501f104a 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -183,7 +183,19 @@ pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_ /// [`evaluate_layer_elements`] with a motion guide: tweened elements travel along `guide` (in /// the layer's own space) from the point nearest their start to the point nearest their end, /// turning with it when the tween orients to the path. +/// +/// On an armature layer (ADR 0043) the instances are then placed by the pose at the frame +/// (tweened between pose keyframes): forward kinematics from the root's own transform. pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc]>)> { + let (start, els) = evaluate_tweened(layer, frame, guide)?; + let Some(arm) = layer.armature.as_deref().filter(|a| layer.kind == crate::LayerKind::Armature && !a.is_empty()) else { return Some((start, els)) }; + let pose = crate::armature::pose_at(layer, frame).unwrap_or_default(); + let mut els = els.into_owned(); + crate::armature::apply(arm, &mut els, &pose); + Some((start, Cow::Owned(els))) +} + +fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc]>)> { let idx = layer.keyframe_index_at(frame)?; let kf = layer.keyframes.get(idx)?; // A motion tween: its target follows the property curves (and its motion path, ADR 0030); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 1a24639c..bfdfaf64 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -7,6 +7,7 @@ pub use anicraft_audio as audio; pub use anicraft_actions as actions; +pub mod armature; mod bitmap; pub mod camera; mod filter; @@ -16,6 +17,7 @@ mod hints; pub mod motion; pub mod path_table; pub mod width; +pub mod stroke_style; pub mod player; pub mod sample; pub mod sound; @@ -24,10 +26,12 @@ pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; pub use easing::Easing; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; -pub use motion::{MotionTween, OnPath, Property, PropertyKey, Props, Track, motion_path}; +pub use motion::{MotionTween, OnPath, Pin, PinError, Property, PropertyKey, Props, Track, motion_path}; pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; +pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle}; pub use camera::Camera; +pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose}; pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; @@ -157,7 +161,8 @@ impl Paint { } } -/// Stroke style: round joins and caps, one width or a width profile (ADR 0018). +/// A line: colour, width, an optional width profile (ADR 0018) and its style: caps, joins, +/// miter limit, dashes (ADR 0046). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(from = "StrokeFile")] pub struct Stroke { @@ -167,40 +172,60 @@ pub struct Stroke { /// How the width varies along each subpath (`None`: the same everywhere). Never uniform. #[serde(default, skip_serializing_if = "Option::is_none")] pub profile: Option, + /// Caps, joins and dashes. The default (round, solid) is written as nothing, so strokes + /// without a style are stored as before. + #[serde(default, skip_serializing_if = "StrokeStyle::is_default")] + pub style: StrokeStyle, } -/// What a file may hold for a stroke (a uniform profile is dropped on load). +/// What a file may hold for a stroke (a uniform profile is dropped on load, the style is +/// sanitized). #[derive(Deserialize)] struct StrokeFile { color: Rgba, width: f32, #[serde(default)] profile: Option, + #[serde(default)] + style: StrokeStyle, } impl From for Stroke { fn from(f: StrokeFile) -> Stroke { - Stroke { color: f.color, width: f.width, profile: f.profile.filter(|p| !p.is_uniform()) } + Stroke { color: f.color, width: f.width, profile: f.profile.filter(|p| !p.is_uniform()), style: f.style.sanitized() } } } impl Stroke { - /// A stroke of one width. + /// A solid stroke of one width with round caps and joins. pub fn new(color: Rgba, width: f32) -> Stroke { - Stroke { color, width, profile: None } + Stroke { color, width, profile: None, style: StrokeStyle::default() } } pub fn with_profile(self, profile: Option) -> Stroke { Stroke { profile: profile.filter(|p| !p.is_uniform()), ..self } } + /// The same stroke with caps, joins and dashes from `style` (sanitized). + pub fn with_style(self, style: StrokeStyle) -> Stroke { + Stroke { style: style.sanitized(), ..self } + } /// The farthest the stroke reaches from its path (local units): half its nominal width - /// times the profile's widest factor. + /// times the profile's widest factor, times what miter corners and square caps add. pub fn reach(&self) -> f32 { let w = if self.width.is_finite() { self.width.max(0.0) } else { 0.0 }; - w * 0.5 * self.profile.as_ref().map_or(1.0, WidthProfile::max_factor) + w * 0.5 * self.profile.as_ref().map_or(1.0, WidthProfile::max_factor) * self.style.reach_factor() } - /// The stroke `t` of the way to `o` (shape tweens): colour, width and profile blend. + /// The stroke of a shape scaled by `k` (mean scale): the width and the dashes scale. + pub fn scaled(&self, k: f32) -> Stroke { + Stroke { width: self.width * k, style: self.style.scaled(k), ..self.clone() } + } + /// The stroke `t` of the way to `o` (shape tweens): colour, width, profile and style blend. pub fn lerp(&self, o: &Stroke, t: f32) -> Stroke { - Stroke { color: self.color.lerp(o.color, t), width: anicraft_geom::lerp(self.width, o.width, t), profile: WidthProfile::lerp(self.profile.as_ref(), o.profile.as_ref(), t) } + Stroke { + color: self.color.lerp(o.color, t), + width: anicraft_geom::lerp(self.width, o.width, t), + profile: WidthProfile::lerp(self.profile.as_ref(), o.profile.as_ref(), t), + style: self.style.lerp(&o.style, t), + } } } @@ -586,17 +611,20 @@ pub struct Keyframe { /// script (ADR 0024). Rendering and exports ignore it. #[serde(default, skip_serializing_if = "Option::is_none")] pub script: Option, + /// On an armature layer: the joint angles this keyframe poses the armature with (ADR 0043). + #[serde(default, skip_serializing_if = "Pose::is_empty")] + pub pose: Pose, } impl PartialEq for Keyframe { fn eq(&self, o: &Keyframe) -> bool { - self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.hints == o.hints && self.label == o.label && self.sound == o.sound && self.script == o.script && arcs_eq(&self.elements, &o.elements) + self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.hints == o.hints && self.label == o.label && self.sound == o.sound && self.script == o.script && self.pose == o.pose && 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, motion: None, hints: Vec::new(), label: String::new(), sound: None, script: None } + Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, hints: Vec::new(), label: String::new(), sound: None, script: None, pose: Pose::default() } } /// 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> { @@ -625,6 +653,9 @@ pub enum LayerKind { /// The camera (ADR 0027): at most one per scene timeline, always the top layer; its /// keyframes hold the camera, which views every other layer. Draws nothing itself. Camera, + /// An armature (ADR 0043): symbol instances joined by bones ([`Layer::armature`]), posed + /// on each keyframe ([`Keyframe::pose`]) and tweened between poses. + Armature, } /// Deepest nesting of folders (and a mask inside them) that is kept. @@ -662,6 +693,9 @@ pub struct Layer { /// The layer's sounds are silent (in playback and every export). #[serde(default, skip_serializing_if = "is_false")] pub muted: bool, + /// An armature layer's bones (ADR 0043); `None` on every other kind of layer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub armature: Option>, } fn is_zero(v: &f32) -> bool { @@ -687,6 +721,10 @@ impl PartialEq for Layer { && self.depth.to_bits() == o.depth.to_bits() && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted + && match (&self.armature, &o.armature) { + (Some(a), Some(b)) => arc_eq(a, b), + (a, b) => a.is_none() && b.is_none(), + } && arcs_eq(&self.keyframes, &o.keyframes) } } @@ -713,6 +751,7 @@ impl Layer { depth: 0.0, volume: 1.0, muted: false, + armature: None, } } /// The gain this layer gives its sounds: its volume, or silence when muted. @@ -1185,6 +1224,9 @@ impl Document { let mut max_id = 0u64; let scan = |l: &Layer, max_id: &mut u64| { *max_id = (*max_id).max(l.id.0); + for b in l.armature.iter().flat_map(|a| &a.bones) { + *max_id = (*max_id).max(b.id.0); + } for k in &l.keyframes { for e in &k.elements { *max_id = (*max_id).max(e.id.0); @@ -1204,6 +1246,7 @@ impl Document { Arc::make_mut(l).normalize(); sanitize_scripts(l); sanitize_depth(l); + sanitize_armature(l); scan(l, &mut max_id); } tl.repair_masks(); @@ -1226,6 +1269,7 @@ impl Document { Arc::make_mut(l).kind = LayerKind::Normal; } sanitize_depth(l); + sanitize_armature(l); scan(l, &mut max_id); } tl.repair_masks(); @@ -1248,6 +1292,36 @@ fn sanitize_depth(layer: &mut Arc) { } } +/// Repairs a loaded layer's armature (ADR 0043): only an armature layer has one, its bones are +/// sane and ordered, and its keyframes' poses are finite. Touches only what needs it. +fn sanitize_armature(layer: &mut Arc) { + let is_armature = layer.kind == LayerKind::Armature; + // (A pose on another layer's keyframe, pasted from an armature, is kept and plays no part.) + if !is_armature { + if layer.armature.is_some() { + Arc::make_mut(layer).armature = None; + } + return; + } + if let Some(a) = &layer.armature { + let mut fixed = (**a).clone(); + if fixed.sanitize() { + Arc::make_mut(layer).armature = Some(Arc::new(fixed)); + } + } + let bad = |k: &Keyframe| { + let mut p = k.pose.clone(); + p.sanitize() + }; + if layer.keyframes.iter().any(|k| bad(k)) { + for k in &mut Arc::make_mut(layer).keyframes { + if bad(k) { + Arc::make_mut(k).pose.sanitize(); + } + } + } +} + /// Repairs a loaded layer's frame scripts and instance event handlers (ADR 0024). Touches (and /// so un-shares) only keyframes that need it. fn sanitize_scripts(layer: &mut Arc) { diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 60123b4b..bbe806a3 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -13,8 +13,16 @@ //! *when* it gets where: the share of the way along the path at a frame is the share of the //! distance the X/Y curves have covered by then. With *orient to path* the object also turns //! as the path turns. Without a path the X/Y curves place the object, as before. +//! +//! Anchors of the path may be *pinned* to frames (ADR 0049): the object passes a pinned anchor +//! exactly on its frame, and the X/Y keys there hold the anchor's place. The ends are always +//! pinned, to the first and last position keys. Pins cut the motion into legs; on each leg the +//! X/Y curves time the object along the stretch of path between its two pinned anchors, as they +//! time the whole path when only the ends are pinned. Anchors that aren't pinned shape the path +//! only. use crate::{Element, ElementId, Easing}; +use anicraft_geom::edit::ANCHOR; use anicraft_geom::walk::CurveWalk; use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2}; use serde::{Deserialize, Serialize}; @@ -258,6 +266,36 @@ impl Track { } } +/// A motion path anchor pinned to a frame (ADR 0049): the object passes the anchor exactly +/// then. Only anchors between the ends are stored; the ends are pinned to the first and last +/// position keys. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Pin { + /// Frames from the span's first frame. + pub frame: u32, + /// The anchor: path command `anchor` (0 is the start). + pub anchor: u32, +} + +/// Why an anchor can't be pinned (or a pin added) where asked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PinError { + /// The tween has no motion path. + NoPath, + /// No such anchor on the path. + NoAnchor, + /// An end: always pinned to the first or last position key. + End, + /// The frame isn't strictly between the first and last position keys (these frames). + Outside(u32, u32), + /// Pins keep the path's order (a later frame on a later anchor); this one is in the way. + Order(Pin), + /// The object is off the path at that frame (an ease overshooting an end). + OffPath, + /// The path holds as many segments as it may. + Full, +} + /// A motion tween on a keyframe span (see the module docs). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MotionTween { @@ -275,6 +313,10 @@ pub struct MotionTween { /// Orient to path: the object turns as the path turns (relative to its turn at the start). #[serde(default, skip_serializing_if = "is_false")] pub orient: bool, + /// Anchors between the ends pinned to frames (ADR 0049), by frame; both frames and anchors + /// increase. Files from before pins have none: only the ends are pinned. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pins: Vec, } fn is_false(b: &bool) -> bool { @@ -350,6 +392,9 @@ pub struct OnPath<'a> { keys: Vec<(f32, Vec2)>, /// `cum[i]`: chord length from the first position key to key `i`. cum: Vec, + /// Where the legs start and end: the first position key, each pin and the last position key, + /// as an index into `keys` and the distance along the path of the anchor pinned there. + stations: Vec<(usize, f32)>, /// Direction of travel at the start, radians. start_angle: f32, } @@ -359,34 +404,46 @@ impl OnPath<'_> { &self.walk } - /// The share of the path covered `frame` frames into the span: 0 up to the first position - /// key (and without two), 1 from the last; an overshooting ease may leave 0..1 in between. - /// Where the chords add up to nothing (a path back to its start) the object keeps an even - /// pace between the first and last position keys. + /// The share of the path covered `frame` frames into the span (see [`OnPath::distance`]). pub fn progress(&self, frame: f32) -> f32 { + let l = self.walk.length(); + if l > 0.0 { self.distance(frame) / l } else { 0.0 } + } + + /// Distance along the path at `frame`: 0 up to the first position key (and without two), the + /// whole length from the last; an overshooting ease may go beyond in between. + /// + /// The pins cut the span into legs, each from one pinned anchor to the next. On a leg, the + /// position keys inside it split it again; on each of those pieces the X/Y curves run from + /// one key's position to the next, and how far along that chord they are (signed) is how far + /// along the piece's share of the leg's stretch of path the object is, the shares being the + /// chords' lengths. Where a leg's chords add up to nothing (a loop) the object keeps an even + /// pace across it. With only the ends pinned this is ADR 0030's timing, number for number. + pub fn distance(&self, frame: f32) -> f32 { + let l = self.walk.length(); let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return 0.0 }; if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 { return 0.0; } if frame >= last.0 { - return 1.0; - } - let total = self.cum.last().copied().unwrap_or(0.0); - if total <= 1e-4 { - return (frame - first.0) / (last.0 - first.0); + return l; } let i = self.keys.partition_point(|k| k.0 <= frame).saturating_sub(1); - let (Some(a), Some(b)) = (self.keys.get(i), self.keys.get(i + 1)) else { return 1.0 }; - let chord = b.1 - a.1; - let len = chord.length(); - let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 }; - let p = (self.cum.get(i).copied().unwrap_or(0.0) + along) / total; - if p.is_finite() { p } else { 0.0 } - } - - /// Distance along the path at `frame` (beyond the ends while an ease overshoots them). - pub fn distance(&self, frame: f32) -> f32 { - self.progress(frame) * self.walk.length() + let leg = self.stations.partition_point(|st| st.0 <= i).saturating_sub(1); + let (Some(&(ka, sa)), Some(&(kb, sb))) = (self.stations.get(leg), self.stations.get(leg + 1)) else { return l }; + let (Some(a), Some(b), Some(fa), Some(fb)) = (self.keys.get(i), self.keys.get(i + 1), self.keys.get(ka), self.keys.get(kb)) else { return l }; + let c0 = self.cum.get(ka).copied().unwrap_or(0.0); + let total = self.cum.get(kb).copied().unwrap_or(0.0) - c0; + let p = if total <= 1e-4 { + (frame - fa.0) / (fb.0 - fa.0) + } else { + let chord = b.1 - a.1; + let len = chord.length(); + let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 }; + (self.cum.get(i).copied().unwrap_or(0.0) - c0 + along) / total + }; + let p = if p.is_finite() { p } else { 0.0 }; + sa + p * (sb - sa) } /// The registration point at `frame`. Overshooting an end carries on along the path's @@ -414,7 +471,7 @@ impl OnPath<'_> { impl MotionTween { pub fn new(target: ElementId) -> MotionTween { - MotionTween { target, tracks: Vec::new(), path: None, orient: false } + MotionTween { target, tracks: Vec::new(), path: None, orient: false, pins: Vec::new() } } /// The first and last frames holding an X or Y key. @@ -433,18 +490,32 @@ impl MotionTween { /// path. pub fn on_path(&self, base: &Props) -> Option> { let walk = CurveWalk::new(self.path.as_ref()?)?; + let pins = self.live_pins(); let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); + // A pin's frame holds X/Y keys (commands see to it); a leg ends there all the same. + frames.extend(pins.iter().map(|p| p.frame)); frames.sort_unstable(); frames.dedup(); - let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, self.trace_at(base, f as f32))).collect(); + let keys: Vec<(f32, Vec2)> = frames.iter().map(|&f| (f as f32, self.trace_at(base, f as f32))).collect(); let mut cum = Vec::with_capacity(keys.len()); let mut d = 0.0f32; for (i, k) in keys.iter().enumerate() { d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1)); cum.push(d); } + let mut stations = vec![(0usize, 0.0f32)]; + for pin in &pins { + if let (Ok(i), Some(s)) = (frames.binary_search(&pin.frame), walk.anchor_distance(pin.anchor as usize)) + && stations.last().is_some_and(|l| l.0 < i) + { + stations.push((i, s)); + } + } + if keys.len() > 1 { + stations.push((keys.len() - 1, walk.length())); + } let t = walk.tangent(0.0); - Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum }) + Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum, stations }) } /// The registration point on each of the span's first `frames` frames (at most a day of @@ -460,13 +531,21 @@ impl MotionTween { /// A motion path through the X/Y curves' positions at their keys, as straight segments: /// the path a tween without one shows, made editable. `None` when the object doesn't move. pub fn path_from_tracks(&self, base: &Props) -> Option { + self.path_and_pins_from_tracks(base).map(|(p, _)| p) + } + + /// [`MotionTween::path_from_tracks`] with the position keys between the ends pinned to the + /// anchors they made (the first key at a place, where the object holds still a while). + pub fn path_and_pins_from_tracks(&self, base: &Props) -> Option<(Path, Vec)> { let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); frames.sort_unstable(); frames.dedup(); let mut pts: Vec = Vec::new(); + let mut pins = Vec::new(); for f in frames.into_iter().take(MAX_PATH_SEGMENTS + 1) { let q = self.trace_at(base, f as f32); if pts.last().is_none_or(|l| l.distance(q) > 1e-3) { + pins.push(Pin { frame: f, anchor: pts.len() as u32 }); pts.push(q); } } @@ -476,16 +555,64 @@ impl MotionTween { for q in rest { p.line_to(*q); } - motion_path(&p) + let path = motion_path(&p)?; + let n = path.cmds.len(); + pins.retain(|p| p.anchor > 0 && (p.anchor as usize) + 1 < n); + Some((path, pins)) + } + + /// The pins in force: between the ends in both frame and anchor, frames and anchors + /// increasing. Others are ignored (and dropped when a file is loaded). + pub fn live_pins(&self) -> Vec { + let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return Vec::new() }; + let n = path.cmds.len(); + let mut out: Vec = Vec::new(); + for p in &self.pins { + let inside = p.frame > f0 && p.frame < f1 && p.anchor > 0 && (p.anchor as usize).saturating_add(1) < n; + if inside && out.last().is_none_or(|q| q.frame < p.frame && q.anchor < p.anchor) { + out.push(*p); + } + } + out + } + + /// Every anchor tied to a frame, in order: the start at the first position key, the pins, + /// and the end at the last. A tween without a path of its own gives those of the straight + /// path its X/Y curves trace. Empty while the object doesn't move. + pub fn pinned_anchors(&self, base: &Props) -> Vec { + let Some((f0, f1)) = self.position_range().filter(|(a, b)| b > a) else { return Vec::new() }; + let (n, pins) = match &self.path { + Some(p) => (p.cmds.len(), self.live_pins()), + None => match self.path_and_pins_from_tracks(base) { + Some((p, pins)) => (p.cmds.len(), pins), + None => return Vec::new(), + }, + }; + let mut v = Vec::with_capacity(pins.len() + 2); + v.push(Pin { frame: f0, anchor: 0 }); + v.extend(pins); + v.push(Pin { frame: f1, anchor: n.saturating_sub(1) as u32 }); + v } /// Gives the tween motion path `path` (made a [`motion_path`]; false when nothing usable /// is left). Its ends become the X/Y keys at the first and last position keys, or at the /// span's first frame and frame `last` when there are none, so the curves start and end - /// where the path does. + /// where the path does; each pinned anchor's place becomes the X/Y keys on its frame. + /// + /// A tween without a path of its own shows the straight one through its position keys, + /// which are pinned to its anchors: a path with as many anchors is that one edited, and + /// keeps them pinned. Pins on anchors the new path doesn't have are let go, with their keys. pub fn set_path(&mut self, path: &Path, base: &Props, last: u32) -> bool { let Some(p) = motion_path(path) else { return false }; let Some((a, b)) = path_ends(&p) else { return false }; + if self.path.is_none() + && self.pins.is_empty() + && let Some((implied, pins)) = self.path_and_pins_from_tracks(base) + && implied.cmds.len() == p.cmds.len() + { + self.pins = pins; + } let (f0, f1) = match self.position_range() { Some((f0, f1)) if f1 > f0 => (f0, f1), _ if last > 0 => (0, last), @@ -501,7 +628,184 @@ impl MotionTween { self.set_key(prop, f1, v1, base.get(prop)); } } + let n = p.cmds.len(); self.path = Some(p); + let (keep, gone): (Vec, Vec) = self.pins.iter().partition(|q| q.anchor > 0 && (q.anchor as usize).saturating_add(1) < n); + self.pins = keep; + for q in gone { + self.remove_pin_keys(q.frame); + } + self.sync_pins(base); + true + } + + /// Writes each pinned anchor's place as the X/Y keys on its frame (leaving keys alone that + /// already hold it, so editing elsewhere keeps the timing exactly). + fn sync_pins(&mut self, base: &Props) { + let Some(path) = self.path.clone() else { return }; + for pin in self.live_pins() { + let Some(q) = path.point(pin.anchor as usize, ANCHOR) else { continue }; + for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] { + let holds = self.track(prop).and_then(|t| t.key_at(pin.frame).and_then(|i| t.keys.get(i))).is_some_and(|k| k.value == v); + if !holds { + self.set_key(prop, pin.frame, v, base.get(prop)); + } + } + } + } + + /// Removes the X/Y keys a pin held on `frame`, unless that frame is an end's. + fn remove_pin_keys(&mut self, frame: u32) { + if self.position_range().is_some_and(|(f0, f1)| f0 < frame && frame < f1) { + self.remove_track_key(Property::X, frame); + self.remove_track_key(Property::Y, frame); + } + } + + /// Pins anchor `anchor` to `frame`: the object passes it exactly then, and the X/Y keys on + /// that frame hold its place. A pin already on that frame, or that anchor's pin on another + /// frame, gives way. + pub fn pin(&mut self, anchor: usize, frame: u32, base: &Props) -> Result<(), PinError> { + let Some(path) = &self.path else { return Err(PinError::NoPath) }; + let n = path.cmds.len(); + if anchor >= n { + return Err(PinError::NoAnchor); + } + if anchor == 0 || anchor + 1 == n { + return Err(PinError::End); + } + let (f0, f1) = self.position_range().unwrap_or((0, 0)); + if !(f0 < frame && frame < f1) { + return Err(PinError::Outside(f0, f1)); + } + let Some(q) = path.point(anchor, ANCHOR) else { return Err(PinError::NoAnchor) }; + let a = anchor as u32; + let live = self.live_pins(); + if let Some(p) = live.iter().find(|p| p.frame != frame && p.anchor != a && (p.frame < frame) != (p.anchor < a)) { + return Err(PinError::Order(*p)); + } + self.pins = live; + if let Some(old) = self.pins.iter().find(|p| p.anchor == a && p.frame != frame).copied() { + self.unpin(old.frame); + } + self.pins.retain(|p| p.frame != frame); + let i = self.pins.partition_point(|p| p.frame < frame); + self.pins.insert(i, Pin { frame, anchor: a }); + for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] { + self.set_key(prop, frame, v, base.get(prop)); + } + Ok(()) + } + + /// Pins the path where the object is on `frame`: on the anchor there, or on a new one (the + /// path's shape unchanged). The anchor pinned. + pub fn pin_here(&mut self, frame: u32, base: &Props) -> Result { + if self.path.is_none() { + return Err(PinError::NoPath); + } + let (f0, f1) = self.position_range().unwrap_or((0, 0)); + if !(f0 < frame && frame < f1) { + return Err(PinError::Outside(f0, f1)); + } + if let Some(p) = self.live_pins().into_iter().find(|p| p.frame == frame) { + return Ok(p.anchor as usize); + } + let (s, l, (cmd, t)) = { + let op = self.on_path(base).ok_or(PinError::NoPath)?; + let s = op.distance(frame as f32); + (s, op.walk().length(), op.walk().locate(s)) + }; + if !(0.0..=l).contains(&s) { + return Err(PinError::OffPath); + } + let mut trial = self.clone(); + let anchor = if t <= 1e-3 { + cmd.saturating_sub(1) + } else if t >= 1.0 - 1e-3 { + cmd + } else { + if self.path.as_ref().is_some_and(|p| p.cmds.len() > MAX_PATH_SEGMENTS) { + return Err(PinError::Full); + } + if !trial.split_path(cmd, t) { + return Err(PinError::OffPath); + } + cmd + }; + trial.pin(anchor, frame, base)?; + *self = trial; + Ok(anchor) + } + + /// Splits the path's segment `cmd` at curve parameter `t` (the curve unchanged; the new + /// anchor is `cmd`). Pins after it stay on their anchors. False when there is no such + /// segment. + pub fn split_path(&mut self, cmd: usize, t: f32) -> bool { + let Some(path) = self.path.as_mut() else { return false }; + if !path.split_segment(cmd, t) { + return false; + } + for p in &mut self.pins { + if p.anchor as usize >= cmd { + p.anchor = p.anchor.saturating_add(1); + } + } + true + } + + /// Deletes anchor `i` between the ends, refitting the two segments around it as one + /// ([`Path::merge_at`]). A pin on it goes, with its keys; later pins stay on their anchors. + /// False when it can't be deleted (an end, or no such anchor). + pub fn delete_anchor(&mut self, i: usize) -> bool { + let Some(path) = self.path.as_mut() else { return false }; + if !path.merge_at(i) { + return false; + } + if let Some(frame) = self.pins.iter().find(|p| p.anchor as usize == i).map(|p| p.frame) { + self.unpin(frame); + } + for p in &mut self.pins { + if p.anchor as usize > i { + p.anchor -= 1; + } + } + true + } + + /// Lets the pin on `frame` go: its X/Y keys go with it and its anchor shapes the path only + /// (ADR 0038's behaviour). The pin, if there was one. + pub fn unpin(&mut self, frame: u32) -> Option { + let i = self.pins.iter().position(|p| p.frame == frame)?; + let pin = self.pins.remove(i); + self.remove_pin_keys(frame); + Some(pin) + } + + /// Moves anchor `anchor` (its handles with it) by `d`; an end or a pin takes its keys along. + pub fn move_anchor(&mut self, anchor: usize, d: Vec2, base: &Props, last: u32) -> bool { + let Some(mut path) = self.path.clone() else { return false }; + path.move_anchor(anchor, d) && self.set_path(&path, base, last) + } + + /// Carries the path on from its end to `to`, reached on `frame` after the last position key: + /// the old end stays pinned to its frame and the new straight stretch ends the motion. False + /// (nothing changed) when the path is full or `frame` isn't after the last position key. + pub fn extend_to(&mut self, frame: u32, to: Vec2, base: &Props) -> bool { + let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return false }; + if frame <= f1 || f1 <= f0 || path.cmds.len() > MAX_PATH_SEGMENTS { + return false; + } + let n = path.cmds.len(); + let mut longer = path.clone(); + longer.line_to(to); + let Some(longer) = motion_path(&longer).filter(|p| p.cmds.len() == n + 1) else { return false }; + let mut pins = self.live_pins(); + pins.push(Pin { frame: f1, anchor: (n - 1) as u32 }); + self.set_key(Property::X, frame, to.x, base.get(Property::X)); + self.set_key(Property::Y, frame, to.y, base.get(Property::Y)); + self.path = Some(longer); + self.pins = pins; + self.sync_pins(base); true } @@ -614,8 +918,25 @@ impl MotionTween { } /// Removes property `p`'s key at `frame`; a track left with no keys goes. Whether a key was - /// there. + /// there. Removing the X or Y key of a pinned frame lets the pin go (with both keys). pub fn remove_key(&mut self, p: Property, frame: u32) -> bool { + if !matches!(p, Property::X | Property::Y) { + return self.remove_track_key(p, frame); + } + // Only pins in force count (removing an end's keys can leave one outside the motion). + self.pins = self.live_pins(); + if self.pins.iter().any(|q| q.frame == frame) { + let had = self.track(p).is_some_and(|t| t.key_at(frame).is_some()); + self.unpin(frame); + return had; + } + let had = self.remove_track_key(p, frame); + // An end's key gone may leave pins outside the motion: they go, never to come back. + self.pins = self.live_pins(); + had + } + + fn remove_track_key(&mut self, p: Property, frame: u32) -> bool { let Some(t) = self.track_mut(p) else { return false }; let Some(i) = t.key_at(frame) else { return false }; t.keys.remove(i); @@ -647,12 +968,17 @@ impl MotionTween { Some(Track { property: t.property, keys }) }) .collect(); - let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient }; + let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new() }; let Some(op) = self.on_path(base) else { return tail }; let f = frame as f32; match op.walk().tail(op.distance(f)) { - // The cut path starts where the object is; the X/Y keys go on timing it. - Some(p) => tail.path = Some(p), + // The cut path starts where the object is; the X/Y keys go on timing it, and the + // pins after the cut stay on their anchors (the cut segment's end is anchor 1). + Some(p) => { + let (cmd, _) = op.walk().locate(op.distance(f)); + tail.pins = self.live_pins().into_iter().filter(|q| q.frame > frame && q.anchor as usize >= cmd).map(|q| Pin { frame: q.frame - frame, anchor: q.anchor + 1 - cmd as u32 }).collect(); + tail.path = Some(p); + } // Past the path's end: the object holds where the path ended. None => { let p = op.point(f); @@ -677,6 +1003,7 @@ impl MotionTween { /// duplicate or empty tracks). pub fn is_sane(&self) -> bool { self.path.as_ref().is_none_or(|p| motion_path(p).as_ref() == Some(p)) + && self.pins == self.live_pins() && self.tracks.iter().all(|t| !t.keys.is_empty() && t.is_sane()) && self.tracks.windows(2).all(|w| matches!(w, [a, b] if a.property.index() < b.property.index())) } @@ -689,6 +1016,10 @@ impl MotionTween { self.tracks.retain(|t| !t.keys.is_empty()); self.tracks.sort_by_key(|t| t.property.index()); self.tracks.dedup_by_key(|t| t.property); + self.pins.truncate(MAX_PATH_SEGMENTS); + self.pins.sort_by_key(|p| p.frame); + self.pins.dedup_by_key(|p| p.frame); + self.pins = self.live_pins(); } } @@ -1051,4 +1382,274 @@ mod tests { m.sanitize(); assert!(m.path.is_none()); } + + // ----- anchors pinned to frames (ADR 0049) ---------------------------------------------- + + /// An S through three anchors: (0, 0), (100, 0) and (200, 0), over a hump and under a dip. + fn s_path() -> Path { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(40.0, -60.0), Vec2::new(60.0, -60.0), Vec2::new(100.0, 0.0)).cubic_to(Vec2::new(140.0, 60.0), Vec2::new(160.0, 60.0), Vec2::new(200.0, 0.0)); + p + } + + /// X 0 → 200 over frames 0..20 with `ease`, Y still: the S travelled left to right. + fn along_s(ease: Easing) -> (MotionTween, Element) { + let base = el(1, 0.0, 0.0); + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, ease), (20, 200.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (20, 0.0, Easing::Linear)])]; + assert!(m.set_path(&s_path(), &Props::of(&base), 20)); + (m, base) + } + + fn anchor_at(m: &MotionTween, i: usize) -> Vec2 { + m.path.as_ref().and_then(|p| p.point(i, ANCHOR)).unwrap() + } + + #[test] + fn the_object_passes_each_pinned_anchor_on_its_frame() { + let (mut m, base) = along_s(Easing::QuadIn); + let props = Props::of(&base); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) > 10.0, "unpinned, the middle anchor is passed when the timing says"); + assert_eq!(m.pin(1, 6, &props), Ok(())); + assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }]); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "{:?}", at(&m, &base, 6.0)); + assert!(at(&m, &base, 0.0).distance(Vec2::ZERO) < 1e-3 && at(&m, &base, 20.0).distance(Vec2::new(200.0, 0.0)) < 1e-3, "the ends stay pinned"); + // Pinning where the object is adds an anchor there and moves nothing on that frame. + let was = at(&m, &base, 14.0); + assert_eq!(m.pin_here(14, &props), Ok(2)); + assert_eq!(m.path.as_ref().map(|p| p.cmds.len()), Some(4)); + assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }, Pin { frame: 14, anchor: 2 }]); + assert!(at(&m, &base, 14.0).distance(was) < 0.01, "{:?} vs {was:?}", at(&m, &base, 14.0)); + assert_eq!(m.pin_here(14, &props), Ok(2), "already pinned there"); + // Moving a pinned anchor takes the object with it on that frame, and its keys follow. + assert!(m.move_anchor(2, Vec2::new(0.0, 50.0), &props, 20)); + let a2 = anchor_at(&m, 2); + assert!(at(&m, &base, 14.0).distance(a2) < 1e-3); + assert_eq!(m.track(Property::Y).and_then(|t| t.key_at(14).map(|i| t.keys[i].value)), Some(a2.y)); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "the other pin holds"); + // What can't be pinned says why, and changes nothing. + let before = m.clone(); + assert_eq!(m.pin(1, 16, &props), Err(PinError::Order(Pin { frame: 14, anchor: 2 }))); + assert_eq!(m.pin(0, 5, &props), Err(PinError::End)); + assert_eq!(m.pin(3, 5, &props), Err(PinError::End)); + assert_eq!(m.pin(9, 5, &props), Err(PinError::NoAnchor)); + assert_eq!(m.pin(1, 25, &props), Err(PinError::Outside(0, 20))); + assert_eq!(m.pin_here(0, &props), Err(PinError::Outside(0, 20))); + assert_eq!(m, before); + // Re-pinning an anchor to another frame retimes it. + assert_eq!(m.pin(1, 4, &props), Ok(())); + assert_eq!(m.pins, vec![Pin { frame: 4, anchor: 1 }, Pin { frame: 14, anchor: 2 }]); + assert!(at(&m, &base, 4.0).distance(Vec2::new(100.0, 0.0)) < 1e-3); + assert!(m.track(Property::X).is_some_and(|t| t.key_at(6).is_none()), "the old frame's keys went with the pin"); + assert!(m.is_sane()); + } + + #[test] + fn between_pins_the_eases_time_the_object_as_before() { + // A straight path with an anchor at x = 30 pinned to frame 10: it reproduces the X curve + // exactly, eases and overshoot included, on both legs. + let base = el(1, 0.0, 0.0); + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(30.0, 0.0)).line_to(Vec2::new(100.0, 0.0)); + for second in [Easing::QuadIn, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3)] { + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::QuadIn), (20, 100.0, Easing::Linear)])]; + assert!(m.set_path(&p, &Props::of(&base), 20)); + assert_eq!(m.pin(1, 10, &Props::of(&base)), Ok(())); + if let Some(t) = m.track_mut(Property::X) { + t.keys[1].ease = second; + } + let x = m.track(Property::X).cloned().unwrap(); + for i in 0..=80 { + let f = i as f32 / 4.0; + let q = at(&m, &base, f); + assert!((q.x - x.value_at(f).unwrap()).abs() < 2e-3 && q.y.abs() < 1e-3, "{second:?} frame {f}: {q:?} vs {:?}", x.value_at(f)); + } + } + } + + #[test] + fn unpinning_gives_back_the_unpinned_motion() { + let (m, base) = along_s(Easing::CubicOut); + let props = Props::of(&base); + let mut pinned = m.clone(); + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(at(&pinned, &base, 5.0).distance(at(&m, &base, 5.0)) > 1.0, "pinning retimes"); + assert_eq!(pinned.unpin(8), Some(Pin { frame: 8, anchor: 1 })); + assert_eq!(pinned, m, "pin then unpin: the same tween, keys and all"); + assert_eq!(pinned.unpin(8), None); + // A pin added where the object was leaves its anchor behind, shaping only: the motion + // is ADR 0038's again (the split curve is the same curve). + let mut here = m.clone(); + assert!(here.pin_here(12, &props).is_ok()); + assert!(here.unpin(12).is_some()); + assert_eq!(here.path.as_ref().map(|p| p.cmds.len()), Some(4)); + for f in 0..=20 { + assert!(at(&here, &base, f as f32).distance(at(&m, &base, f as f32)) < 0.01, "frame {f}"); + } + // Removing the X (or Y) key of a pinned frame lets the pin go, with both keys. + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(pinned.remove_key(Property::X, 8)); + assert!(pinned.pins.is_empty() && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_none())); + assert_eq!(pinned, m); + // Removing the end's keys lets a pin that is no longer between the ends go; its keys + // stay as plain keys, removed one by one. + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(pinned.remove_key(Property::X, 20) && pinned.remove_key(Property::Y, 20)); + assert!(pinned.pins.is_empty(), "frame 8 is the last position key now: an end"); + assert!(pinned.remove_key(Property::X, 8)); + assert!(pinned.track(Property::X).is_some_and(|t| t.key_at(8).is_none()) && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_some())); + assert!(pinned.is_sane()); + } + + /// ADR 0030's timing as it was before pins: what files without pins must still give. + fn legacy_point(m: &MotionTween, base: &Props, frame: f32) -> Vec2 { + let walk = CurveWalk::new(m.path.as_ref().unwrap()).unwrap(); + let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| m.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); + frames.sort_unstable(); + frames.dedup(); + let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, m.trace_at(base, f as f32))).collect(); + let mut cum = Vec::new(); + let mut d = 0.0f32; + for (i, k) in keys.iter().enumerate() { + d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1)); + cum.push(d); + } + let progress = (|| { + let (first, last) = (keys.first()?, keys.last()?); + if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 { + return Some(0.0); + } + if frame >= last.0 { + return Some(1.0); + } + let total = *cum.last()?; + if total <= 1e-4 { + return Some((frame - first.0) / (last.0 - first.0)); + } + let i = keys.partition_point(|k| k.0 <= frame).saturating_sub(1); + let (a, b) = (keys.get(i)?, keys.get(i + 1)?); + let chord = b.1 - a.1; + let len = chord.length(); + let along = if len > 1e-6 { (m.trace_at(base, frame) - a.1).dot(chord) / len } else { 0.0 }; + let p = (cum[i] + along) / total; + Some(if p.is_finite() { p } else { 0.0 }) + })() + .unwrap_or(1.0); + let (s, l) = (progress * walk.length(), walk.length()); + if s < 0.0 { + walk.at(0.0) + walk.tangent(0.0) * s + } else if s > l { + walk.at(l) + walk.tangent(l) * (s - l) + } else { + walk.at(s) + } + } + + #[test] + fn tweens_without_pins_evaluate_exactly_as_before() { + let base = el(1, 0.0, 0.0); + let props = Props::of(&base); + let mut cases = Vec::new(); + for ease in [Easing::Linear, Easing::QuadOut, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3), Easing::CubicBezier(0.5, -0.6, 0.5, 1.6)] { + let mut m = diagonal(ease); + assert!(m.set_path(&quarter(100.0), &props, 20)); + cases.push(m.clone()); + // Position keys in the middle are timing keys, not pins, in ADR 0030 files. + m.set_key(Property::Y, 8, 30.0, 0.0); + m.set_key(Property::X, 13, 70.0, 0.0); + cases.push(m.clone()); + let mut s = along_s(ease).0; + s.set_key(Property::X, 5, 20.0, 0.0); + cases.push(s); + } + let mut ring = Path::new(); + ring.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(40.0, 0.0)).line_to(Vec2::new(40.0, 40.0)).line_to(Vec2::new(0.0, 40.0)).close(); + let mut l = MotionTween::new(ElementId(1)); + assert!(l.set_path(&ring, &props, 16)); + cases.push(l); + for m in &cases { + assert!(m.pins.is_empty() && m.is_sane()); + let op = m.on_path(&props).unwrap(); + for i in -4..=120 { + let f = i as f32 / 4.0; + assert_eq!(op.point(f), legacy_point(m, &props, f), "frame {f}"); + } + let json = serde_json::to_string(m).unwrap(); + assert!(!json.contains("pins"), "nothing new is written for them"); + } + } + + #[test] + fn a_path_made_from_the_tracks_keeps_their_keys_pinned() { + // Right 100 over 10 frames, then down 100: no path yet, but an anchor at the corner. + let base = el(1, 0.0, 0.0); + let props = Props::of(&base); + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::Linear), (10, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (10, 0.0, Easing::Linear), (20, 100.0, Easing::Linear)])]; + let (mut path, pins) = m.path_and_pins_from_tracks(&props).unwrap(); + assert_eq!(pins, vec![Pin { frame: 10, anchor: 1 }]); + assert_eq!(m.pinned_anchors(&props), vec![Pin { frame: 0, anchor: 0 }, Pin { frame: 10, anchor: 1 }, Pin { frame: 20, anchor: 2 }], "shown pinned before it is a path"); + // Dragging the corner up edits that path: the corner stays pinned to frame 10. + assert!(path.move_anchor(1, Vec2::new(0.0, -40.0))); + assert!(m.set_path(&path, &props, 20)); + assert_eq!(m.pins, pins); + assert!(at(&m, &base, 10.0).distance(Vec2::new(100.0, -40.0)) < 1e-3); + // A path of another shape is a new path: only its ends are pinned. + let mut fresh = m.clone(); + fresh.path = None; + fresh.pins.clear(); + assert!(fresh.set_path(&line((0.0, 0.0), (100.0, 100.0)), &props, 20)); + assert!(fresh.pins.is_empty()); + } + + #[test] + fn splitting_keeps_the_pins_after_the_cut() { + let (mut m, base) = along_s(Easing::Linear); + let props = Props::of(&base); + assert_eq!(m.pin(1, 6, &props), Ok(())); + for cut in [3u32, 6, 10] { + let tail = m.split_at(&props, cut); + let tail_base = m.apply(&base, cut as f32); + assert_eq!(tail.pins.len(), usize::from(cut < 6), "cut {cut}"); + for f in cut..=24 { + let (a, b) = (at(&m, &base, f as f32), at(&tail, &tail_base, (f - cut) as f32)); + assert!(a.distance(b) < 0.05, "cut {cut} frame {f}: {a:?} vs {b:?}"); + } + } + } + + #[test] + fn moving_on_past_the_end_carries_the_path_on() { + let (mut m, base) = along_s(Easing::Linear); + let props = Props::of(&base); + let before: Vec = (0..=20).map(|f| at(&m, &base, f as f32)).collect(); + assert!(!m.extend_to(20, Vec2::new(250.0, 50.0), &props), "only after the last position key"); + assert!(m.extend_to(28, Vec2::new(250.0, 50.0), &props)); + assert_eq!(m.position_range(), Some((0, 28))); + assert_eq!(m.pins, vec![Pin { frame: 20, anchor: 2 }], "the old end stays pinned to its frame"); + assert!(at(&m, &base, 28.0).distance(Vec2::new(250.0, 50.0)) < 1e-3); + assert!(at(&m, &base, 24.0).distance(Vec2::new(225.0, 25.0)) < 1e-2, "on to the new end in a straight line"); + for (f, b) in before.iter().enumerate() { + assert!(at(&m, &base, f as f32).distance(*b) < 1e-2, "frame {f}: as it was"); + } + } + + #[test] + fn loading_drops_pins_that_cannot_hold() { + let (mut m, _) = along_s(Easing::Linear); + m.pins = vec![Pin { frame: 5, anchor: 9 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 25, anchor: 1 }, Pin { frame: 0, anchor: 1 }]; + assert!(!m.is_sane()); + m.sanitize(); + assert!(m.is_sane()); + assert_eq!(m.pins, vec![Pin { frame: 3, anchor: 1 }]); + let json = serde_json::to_string(&m).unwrap(); + assert!(json.contains("\"pins\"")); + assert_eq!(serde_json::from_str::(&json).unwrap(), m); + // Without a path nothing is pinned. + m.path = None; + assert!(!m.is_sane()); + m.sanitize(); + assert!(m.pins.is_empty()); + } } diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index 9f272b69..e3170648 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -4,8 +4,9 @@ //! [`PlayerState`] holds what changes while a movie plays: the main timeline's scene, frame and //! playing flag, each movie clip instance's playhead, the properties actions have set, and the //! pointer. [`step`] advances it by one frame: every playing timeline moves on, the actions on -//! the keyframes they enter run, then that frame's pointer events go to the buttons under the -//! pointer and run their handlers. [`crate::evaluate_player`] draws a state. +//! the keyframes they enter run (and kept ActionScript in the subset that compiles, ADR 0013 +//! tier 2, with the mouse listeners it adds), then that frame's pointer events go to the buttons +//! under the pointer and run their handlers. [`crate::evaluate_player`] draws a state. //! //! Nothing here changes the document, so the authoring stage and every export stay //! script-free; and nothing reads a clock or a random source, so the same document, state and @@ -13,12 +14,14 @@ //! frames entered, instances walked, output lines), so a `goto` loop ends in a message instead //! of a hang. +use crate::actions::as3::{Listener, ScriptOp}; use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target}; use crate::eval::{Play, evaluate_guided, evaluate_symbol, guide_walk}; use crate::sound::Started; use crate::{Document, Element, ElementId, ElementKind, LayerKind, MAX_SYMBOL_DEPTH, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Vec2}; use std::collections::{BTreeMap, VecDeque}; +use std::sync::Arc; /// An instance's place in the movie: the element ids from the main timeline down to it (empty /// for the main timeline itself). Element ids stay the same across keyframes that hold the same @@ -35,6 +38,8 @@ pub const MAX_NODES: usize = 10_000; pub const MAX_OUTPUT_PER_STEP: usize = 1_000; /// Most pointer events one step handles. pub const MAX_EVENTS_PER_STEP: usize = 256; +/// Most listeners scripts add to one instance. +pub const MAX_LISTENERS_PER_INSTANCE: usize = 16; /// A timeline's playhead. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -103,6 +108,18 @@ impl Overrides { } } +/// A mouse listener a script added to an instance (ADR 0013 tier 2): it lives while the +/// instance (and the script's timeline) stay on the stage. +#[derive(Clone, Debug, PartialEq)] +pub struct Listening { + pub event: ButtonEvent, + /// The timeline whose script added it: the actions run there. + pub owner: InstancePath, + /// The function's name: the same function for the same event is added once. + pub function: String, + pub actions: Arc>, +} + /// Everything that changes while a movie plays. #[derive(Clone, Debug, Default, PartialEq)] pub struct PlayerState { @@ -113,6 +130,8 @@ pub struct PlayerState { pub clips: BTreeMap, /// Properties actions have set, per instance. pub props: BTreeMap, + /// Mouse listeners scripts added, per instance, in the order added. + pub listeners: BTreeMap>, /// The pointer in stage space (`None` when it is outside the movie), and whether it is down. pub pointer: Option, pub down: bool, @@ -350,7 +369,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option { for n in nodes.iter().rev() { - let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && !n.events.is_empty()); + let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && (!n.events.is_empty() || st.listeners.contains_key(&n.path))); if !n.hittable || !interactive { continue; } @@ -468,6 +487,11 @@ impl<'a, 'h> Run<'a, 'h> { } let all: std::collections::BTreeSet<&InstancePath> = self.nodes.iter().map(|n| &n.path).collect(); self.st.props.retain(|p, _| all.contains(p)); + // A listener goes with its instance, and with the timeline whose script added it. + self.st.listeners.retain(|p, list| { + list.retain(|l| all.contains(&l.owner)); + all.contains(p) && !list.is_empty() + }); for slot in [&mut self.st.hover, &mut self.st.pressed] { if slot.as_ref().is_some_and(|p| !all.contains(p)) { *slot = None; @@ -559,7 +583,7 @@ impl<'a, 'h> Run<'a, 'h> { let scripts: Vec<&'a FrameScript> = tl.layers.iter().enumerate().filter(|(ix, _)| plays(tl, *ix)).filter_map(|(_, l)| l.keyframe_starting_at(frame).and_then(|k| l.keyframes.get(k))).filter_map(|k| k.script.as_ref()).collect(); for script in scripts { match script { - FrameScript::Actions(list) => self.run_list(path, list), + FrameScript::Actions(list) => self.run_list(path, list, false), FrameScript::Plugin(p) => { let Some(i) = self.index_of(path) else { return }; let label = label_at(tl, frame); @@ -569,27 +593,80 @@ impl<'a, 'h> Run<'a, 'h> { self.out(line); } let list: Vec = run.actions.into_iter().take(crate::actions::MAX_ACTIONS).collect(); - self.run_list(path, &list); + self.run_list(path, &list, false); + } + // ActionScript in the subset runs, whole (ADR 0013 tier 2); a script outside it + // doesn't run at all. Test Movie lists which is which once, at the start, rather + // than a line every time the playhead passes. + FrameScript::Source(src) => { + if let Ok(c) = src.compiled() { + self.run_ops(path, &c.ops); + } } - // Kept with the document, not run (ADR 0013 tier 1). The Test Movie window says - // so once, rather than a line every time the playhead passes. - FrameScript::Source(_) => {} } } } - fn run_list(&mut self, owner: &[ElementId], list: &[Action]) { - for a in list { - if self.halted { - return; - } - self.actions += 1; - if self.actions > MAX_ACTIONS_PER_STEP { - self.halt(&format!("more than {MAX_ACTIONS_PER_STEP} actions")); - return; - } - self.exec(owner, a); + /// Counts one action against the step's budget; `false` when nothing more may run. + fn budget(&mut self) -> bool { + if self.halted { + return false; } + self.actions += 1; + if self.actions > MAX_ACTIONS_PER_STEP { + self.halt(&format!("more than {MAX_ACTIONS_PER_STEP} actions")); + return false; + } + true + } + + /// Runs a list of actions from timeline `owner`; `script`: they come from ActionScript. + fn run_list(&mut self, owner: &[ElementId], list: &[Action], script: bool) { + for a in list { + if !self.budget() { + return; + } + self.exec(owner, a, script); + } + } + + /// Runs a compiled script's steps (ADR 0013 tier 2), each one action of the budget. + fn run_ops(&mut self, owner: &[ElementId], ops: &[ScriptOp]) { + for op in ops { + if !self.budget() { + return; + } + match op { + ScriptOp::Action(a) => self.exec(owner, a, true), + ScriptOp::Listen(l) => self.listen(owner, l), + } + } + } + + /// `addEventListener`: the instance the listener's target names gets it (once per + /// function and event). + fn listen(&mut self, owner: &[ElementId], l: &Listener) { + self.refresh(); + let Some(from) = self.index_of(owner) else { return }; + let what = format!("Listen for {} ({})", l.event.key(), l.target); + let i = match self.resolve(from, &l.target) { + Ok(i) => i, + Err(e) => return self.out(format!("{what}: {e}")), + }; + let Some(node) = self.nodes.get(i) else { return }; + if !matches!(node.kind, NodeKind::Button | NodeKind::MovieClip) { + let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is a graphic; only buttons and movie clips get pointer events", node.name) }; + return self.out(format!("{what}: {why}")); + } + let (path, name) = (node.path.clone(), node.name.clone()); + let list = self.st.listeners.entry(path).or_default(); + if list.iter().any(|x| x.event == l.event && x.owner == owner && x.function == l.function) { + return; + } + if list.len() >= MAX_LISTENERS_PER_INSTANCE { + return self.out(format!("{what}: “{name}” already has {MAX_LISTENERS_PER_INSTANCE} listeners")); + } + list.push(Listening { event: l.event, owner: owner.to_vec(), function: l.function.clone(), actions: l.actions.clone() }); } /// The node `target` names, seen from timeline node `from`. @@ -608,11 +685,16 @@ impl<'a, 'h> Run<'a, 'h> { Ok(cur) } - fn exec(&mut self, owner: &[ElementId], a: &Action) { + /// Runs one action from timeline `owner`. `script`: it comes from ActionScript, where + /// `nextScene()` on a movie clip's timeline has no other scene to go to. + fn exec(&mut self, owner: &[ElementId], a: &Action, script: bool) { self.refresh(); let Some(from) = self.index_of(owner) else { return }; match a { Action::Trace { message } => self.out(message.clone()), + Action::NextScene | Action::PrevScene if script && !owner.is_empty() => { + self.out(format!("{}: a movie clip's timeline has one scene; call it in the main timeline's script", a.describe())); + } Action::NextScene | Action::PrevScene => { let next = if matches!(a, Action::NextScene) { self.st.scene.checked_add(1) } else { self.st.scene.checked_sub(1) }; if let Some(s) = next.filter(|s| *s < self.doc.scenes.len()) { @@ -774,14 +856,23 @@ impl<'a, 'h> Run<'a, 'h> { } } - /// Runs an instance's handler for `event` (in the timeline the instance is on). + /// Runs an instance's handler for `event` (in the timeline the instance is on), then the + /// listeners scripts added for it (each in the timeline of its script), in the order added. fn fire(&mut self, path: &[ElementId], event: ButtonEvent) { self.refresh(); let Some(n) = self.index_of(path).and_then(|i| self.nodes.get(i)) else { return }; - let Some(h) = n.events.iter().find(|h| h.event == event) else { return }; - let (actions, owner) = (h.actions.clone(), n.owner); - let Some(owner_path) = self.nodes.get(owner).map(|o| o.path.clone()) else { return }; - self.run_list(&owner_path, &actions); + let handler = n.events.iter().find(|h| h.event == event).map(|h| h.actions.clone()); + let owner_path = self.nodes.get(n.owner).map(|o| o.path.clone()); + let listeners: Vec<(InstancePath, Arc>)> = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == event).map(|l| (l.owner.clone(), l.actions.clone())).collect()).unwrap_or_default(); + if handler.is_none() && listeners.is_empty() { + return; + } + if let (Some(actions), Some(owner)) = (handler, owner_path) { + self.run_list(&owner, &actions, false); + } + for (owner, actions) in listeners { + self.run_list(&owner, &actions, true); + } self.settle(); } diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 3bb4faed..6720e447 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -341,3 +341,110 @@ fn entered_keyframes_start_their_sounds_in_clips_and_graphics_with_layer_volumes Arc::make_mut(&mut m.timeline_mut(0).layers[1]).muted = true; assert_eq!(started(&start(&m, &mut NoScripts)), vec![(1, 1.0), (3, 0.0)]); } + +// ----- ActionScript (ADR 0013 tier 2) ----------------------------------------------------------- + +/// `k` with a kept ActionScript 3.0 script in place of its actions. +fn as3(k: Arc, src: &str) -> Arc { + let mut k = (*k).clone(); + k.script = Some(FrameScript::Source(Arc::new(crate::actions::SourceScript::new(crate::actions::Language::ActionScript3, src)))); + Arc::new(k) +} + +/// The state without the listeners scripts add (hand-made actions use handlers instead). +fn lean(st: &PlayerState) -> PlayerState { + PlayerState { listeners: BTreeMap::new(), ..st.clone() } +} + +/// Plays both documents through the same pointer events and asserts the same movie: state and +/// output at every step. +fn same_movie(a: &Document, b: &Document, events: &[Vec]) { + let (mut x, mut y) = (start(a, &mut NoScripts), start(b, &mut NoScripts)); + assert_eq!((lean(&x.state), &x.output), (lean(&y.state), &y.output), "start"); + for (i, ev) in events.iter().enumerate() { + x = step(a, &x.state, ev, &mut NoScripts); + y = step(b, &y.state, ev, &mut NoScripts); + assert_eq!((lean(&x.state), &x.output), (lean(&y.state), &y.output), "step {}", i + 1); + } +} + +#[test] +fn actionscript_and_hand_made_actions_play_the_same_movie() { + // Nested clips told what to do by instance-name path. + let hand = nested(); + let mut script = nested(); + { + let l = Arc::make_mut(&mut script.timeline_mut(0).layers[0]); + l.keyframes[0] = as3(l.keyframes[0].clone(), "hero.gotoAndStop(\"run\");\nthis.hero.arm.gotoAndStop(3);"); + let arm = Arc::make_mut(&mut script.library[1]); + let al = Arc::make_mut(&mut arm.timeline.layers[0]); + al.keyframes[1] = as3(al.keyframes[1].clone(), "MovieClip(this.parent.parent).stop();"); + } + same_movie(&hand, &script, &vec![vec![]; 6]); + // A button's handlers, and the same as listeners a frame script adds. + let hand = button_doc(); + let mut script = button_doc(); + { + let tl = script.timeline_mut(0); + let l0 = Arc::make_mut(&mut tl.layers[0]); + l0.keyframes[0] = as3(l0.keyframes[0].clone(), "import flash.events.MouseEvent;\nstop();\ngo.addEventListener(MouseEvent.CLICK, onGo);\ngo.addEventListener(MouseEvent.ROLL_OVER, function (e:MouseEvent):void { trace(\"over\"); });\ngo.addEventListener(MouseEvent.ROLL_OUT, function (e:MouseEvent):void { trace(\"o\" + \"ut\"); });\nfunction onGo(e:MouseEvent):void {\n gotoAndStop(5);\n}\n"); + let l1 = Arc::make_mut(&mut tl.layers[1]); + let k = Arc::make_mut(&mut l1.keyframes[0]); + if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind { + events.clear(); + } + } + let at = |x, y| Vec2::new(x, y); + let events = vec![vec![], vec![Event::Move(at(180.0, 180.0))], vec![Event::Down(at(180.0, 180.0))], vec![Event::Up(at(181.0, 181.0))], vec![Event::Move(at(300.0, 300.0))], vec![], vec![Event::Move(at(150.0, 150.0)), Event::Leave]]; + same_movie(&hand, &script, &events); + let s = start(&script, &mut NoScripts); + assert_eq!(s.state.listeners.get(&vec![ElementId(3)]).map(Vec::len), Some(3), "three listeners on the button"); +} + +#[test] +fn a_script_outside_the_subset_does_not_run_at_all() { + let d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nif (true) { play(); }")])], vec![]); + let s = run(&d, 3); + assert!(s.state.root.playing && s.output.is_empty(), "nothing of it ran: {:?}", s.output); + assert_eq!(s.state.root.frame, 3); + // In ActionScript 1.0 & 2.0 nothing runs either. + let mut d2 = doc(vec![layer(1, vec![kf(0, 10, vec![], vec![], "")])], vec![]); + Arc::make_mut(&mut Arc::make_mut(&mut d2.timeline_mut(0).layers[0]).keyframes[0]).script = Some(FrameScript::Source(Arc::new(crate::actions::SourceScript::new(crate::actions::Language::ActionScript1or2, "stop();")))); + assert!(run(&d2, 2).state.root.playing); +} + +#[test] +fn listeners_live_with_their_instance_and_are_added_once() { + // `pad` is a movie clip with no handlers: a listener makes it clickable. It is on the stage + // for frames 0-4; the main timeline loops round 8 frames, adding the listener again each + // time it enters frame 1. + let pad = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 1, vec![rect(12, 0.0, 0.0, 20.0, 20.0)], vec![], "")])]); + let script = "pad.addEventListener(MouseEvent.CLICK, hit);\nfunction hit(e:MouseEvent):void { trace(\"hit\"); }\nghost.addEventListener(MouseEvent.CLICK, hit);"; + let d = doc(vec![layer(1, vec![as3(kf(0, 8, vec![], vec![], ""), script)]), layer(2, vec![kf(0, 5, vec![inst(3, 100, "pad", 10.0, 10.0, vec![])], vec![], ""), kf(5, 3, vec![], vec![], "")])], vec![pad]); + let path = vec![ElementId(3)]; + let s = start(&d, &mut NoScripts); + assert_eq!(s.output, ["Listen for click (ghost): no instance named “ghost” here"]); + assert!(hit(&d, &s.state, Vec2::new(15.0, 15.0)).is_some(), "the listener makes the clip clickable"); + let at = Vec2::new(15.0, 15.0); + let s = step(&d, &s.state, &[Event::Move(at), Event::Down(at), Event::Up(at)], &mut NoScripts); + assert!(s.output.iter().any(|l| l == "hit"), "{:?}", s.output); + let s = run(&d, 5); + assert!(s.state.listeners.is_empty(), "pad left the stage, and its listener with it"); + // Round the loop: the frame-1 script adds the same function again, which changes nothing. + let s = run(&d, 8); + assert_eq!(s.state.listeners.get(&path).map(Vec::len), Some(1)); + let s = run(&d, 16); + assert_eq!(s.state.listeners.get(&path).map(Vec::len), Some(1)); +} + +#[test] +fn next_scene_in_a_movie_clip_script_stays_in_its_clip() { + // A clip's own script calling nextScene(): in ActionScript the clip has one scene, so the + // main timeline stays (hand-made Next scene actions do move it, as before). + let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![as3(kf(0, 2, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], ""), "nextScene();")])]); + let mut d = doc(vec![layer(1, vec![kf(0, 4, vec![inst(3, 100, "c", 0.0, 0.0, vec![])], vec![], "")])], vec![clip]); + d.scenes.push(Arc::new(crate::Scene::new("Two"))); + let s = start(&d, &mut NoScripts); + assert_eq!(s.state.scene, 0); + assert_eq!(s.output, ["Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"]); +} diff --git a/crates/doc/src/stroke_style.rs b/crates/doc/src/stroke_style.rs new file mode 100644 index 00000000..58fdf354 --- /dev/null +++ b/crates/doc/src/stroke_style.rs @@ -0,0 +1,361 @@ +//! Stroke caps, joins, the miter limit, and dashed and dotted lines (ADR 0046). +//! +//! A [`StrokeStyle`] sits on every [`crate::Stroke`]. Its default is what every stroke had +//! before: round caps, round joins, solid, so a stroke with the default style is written to a +//! file exactly as before and older files open unchanged. Dash and dot lengths are in the +//! shape's own units, like the stroke width: scaling the shape scales them. + +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +/// How an open end of a stroke (and each dash) ends. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Cap { + /// Flat, exactly at the end (Animate's "None", SVG's `butt`). + Butt, + /// A half disc past the end. + #[default] + Round, + /// Flat, half the width past the end. + Square, +} + +impl Cap { + pub const ALL: [Cap; 3] = [Cap::Butt, Cap::Round, Cap::Square]; + + /// The name used in commands and files. + pub fn key(self) -> &'static str { + match self { + Cap::Butt => "butt", + Cap::Round => "round", + Cap::Square => "square", + } + } + + /// As Animate's Properties name it. + pub fn label(self) -> &'static str { + match self { + Cap::Butt => "None", + Cap::Round => "Round", + Cap::Square => "Square", + } + } + + /// A cap by name; `none` (Animate's word) is `butt`. + pub fn from_key(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "butt" | "none" | "flat" => Some(Cap::Butt), + "round" => Some(Cap::Round), + "square" => Some(Cap::Square), + _ => None, + } + } +} + +/// How a stroke turns its corners. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Join { + /// Sharp: the outer edges meet in a point, unless that point is farther than the miter limit + /// allows, where the corner is bevelled. + Miter, + #[default] + Round, + /// Cut straight across the outer corner. + Bevel, +} + +impl Join { + pub const ALL: [Join; 3] = [Join::Miter, Join::Round, Join::Bevel]; + + pub fn key(self) -> &'static str { + match self { + Join::Miter => "miter", + Join::Round => "round", + Join::Bevel => "bevel", + } + } + + pub fn label(self) -> &'static str { + match self { + Join::Miter => "Miter", + Join::Round => "Round", + Join::Bevel => "Bevel", + } + } + + pub fn from_key(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "miter" | "mitre" => Some(Join::Miter), + "round" => Some(Join::Round), + "bevel" => Some(Join::Bevel), + _ => None, + } + } +} + +/// The miter limit new strokes get (Animate's default). SVG's own default is 4; the SVG +/// importer sets that when a file leaves it out. +pub const DEFAULT_MITER_LIMIT: f32 = 3.0; +/// The miter limit's range: a ratio of the corner's point length to the stroke width. +pub const MIN_MITER_LIMIT: f32 = 1.0; +pub const MAX_MITER_LIMIT: f32 = 100.0; +/// Most on and off lengths in a dash pattern. +pub const MAX_DASH_ENTRIES: usize = 16; +/// Longest dash, gap or dot spacing (shape units). +pub const MAX_DASH_LENGTH: f32 = 10_000.0; +/// A pattern shorter than this (shape units) draws solid. +const MIN_PERIOD: f32 = 1e-3; + +/// A broken line: dashes, or round dots. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Dash { + /// Dashes: lengths that alternate on and off along each subpath, starting with a dash + /// (an even count, as SVG's `stroke-dasharray` repeats an odd one), each dash capped with + /// the stroke's cap. `offset` is how far into the pattern each subpath starts. + Dashed { + lengths: Arc<[f32]>, + #[serde(default)] + offset: f32, + }, + /// Round dots one stroke width across, `spacing` apart edge to edge. + Dotted { spacing: f32 }, +} + +/// The line styles Properties offers. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum DashKind { + #[default] + Solid, + Dashed, + Dotted, +} + +impl DashKind { + pub const ALL: [DashKind; 3] = [DashKind::Solid, DashKind::Dashed, DashKind::Dotted]; + + pub fn key(self) -> &'static str { + match self { + DashKind::Solid => "solid", + DashKind::Dashed => "dashed", + DashKind::Dotted => "dotted", + } + } + + pub fn label(self) -> &'static str { + match self { + DashKind::Solid => "Solid", + DashKind::Dashed => "Dashed", + DashKind::Dotted => "Dotted", + } + } + + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase(); + DashKind::ALL.into_iter().find(|k| k.key() == s) + } +} + +fn length(v: f32) -> f32 { + if v.is_finite() { v.clamp(0.0, MAX_DASH_LENGTH) } else { 0.0 } +} + +impl Dash { + /// Dashes of `on` with gaps of `off` (sanitized; `None` when that draws solid). + pub fn dashed(on: f32, off: f32) -> Option { + Dash::Dashed { lengths: vec![on, off].into(), offset: 0.0 }.sanitized() + } + + /// Dots `spacing` apart (sanitized). + pub fn dotted(spacing: f32) -> Option { + Dash::Dotted { spacing }.sanitized() + } + + /// The pattern as stored, cleaned up (a file, a command): lengths finite and in range, an + /// odd count repeated, at most [`MAX_DASH_ENTRIES`], the offset within one period. + /// `None` when it draws solid (no gaps, or nothing at all to repeat). + pub fn sanitized(self) -> Option { + match self { + Dash::Dashed { lengths, offset } => { + let mut v: Vec = lengths.iter().take(MAX_DASH_ENTRIES).map(|&x| length(x)).collect(); + if v.len() % 2 == 1 { + let again = v.clone(); + v.extend(again); + v.truncate(MAX_DASH_ENTRIES); + } + let period: f32 = v.iter().sum(); + let gaps: f32 = v.iter().skip(1).step_by(2).sum(); + if period.is_nan() || period <= MIN_PERIOD || gaps <= 0.0 { + return None; + } + let offset = if offset.is_finite() { offset.rem_euclid(period) } else { 0.0 }; + Some(Dash::Dashed { lengths: v.into(), offset }) + } + Dash::Dotted { spacing } => Some(Dash::Dotted { spacing: length(spacing) }), + } + } + + pub fn kind(&self) -> DashKind { + match self { + Dash::Dashed { .. } => DashKind::Dashed, + Dash::Dotted { .. } => DashKind::Dotted, + } + } + + /// The on/off lengths and the start offset for a stroke `width` wide (shape units). Dots are + /// zero-length dashes drawn with round caps, one width plus the spacing apart. + pub fn pattern(&self, width: f32) -> (Vec, f32) { + match self { + Dash::Dashed { lengths, offset } => (lengths.to_vec(), *offset), + Dash::Dotted { spacing } => (vec![0.0, length(width) + spacing], 0.0), + } + } + + /// The same pattern `k` times as long (the shape scaled by `k`). + pub fn scaled(&self, k: f32) -> Dash { + let k = if k.is_finite() && k > 0.0 { k } else { 1.0 }; + match self { + Dash::Dashed { lengths, offset } => Dash::Dashed { lengths: lengths.iter().map(|&x| length(x * k)).collect(), offset: offset * k }, + Dash::Dotted { spacing } => Dash::Dotted { spacing: length(spacing * k) }, + } + } + + /// `t` of the way to `o` (shape tweens): lengths blend when both are the same kind with + /// the same number of lengths; otherwise this pattern holds until the end. + pub fn lerp(a: Option<&Dash>, b: Option<&Dash>, t: f32) -> Option { + let mix = |x: f32, y: f32| x + (y - x) * t; + match (a, b) { + (Some(Dash::Dashed { lengths: la, offset: oa }), Some(Dash::Dashed { lengths: lb, offset: ob })) if la.len() == lb.len() => { + Dash::Dashed { lengths: la.iter().zip(lb.iter()).map(|(&x, &y)| mix(x, y)).collect(), offset: mix(*oa, *ob) }.sanitized() + } + (Some(Dash::Dotted { spacing: sa }), Some(Dash::Dotted { spacing: sb })) => Some(Dash::Dotted { spacing: mix(*sa, *sb) }), + _ => if t >= 1.0 { b.cloned() } else { a.cloned() }, + } + } +} + +/// Caps, joins, miter limit and dashes: everything about a stroke's outline but its width. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct StrokeStyle { + pub cap: Cap, + pub join: Join, + /// For miter joins: the longest a corner's point may reach, as a multiple of the stroke + /// width ([`MIN_MITER_LIMIT`]..=[`MAX_MITER_LIMIT`]); sharper corners are bevelled. + pub miter_limit: f32, + /// `None`: a solid line. + #[serde(skip_serializing_if = "Option::is_none")] + pub dash: Option, +} + +impl Default for StrokeStyle { + fn default() -> Self { + StrokeStyle { cap: Cap::Round, join: Join::Round, miter_limit: DEFAULT_MITER_LIMIT, dash: None } + } +} + +impl StrokeStyle { + /// Round caps and joins, solid: how strokes were before styles (written as nothing). + pub fn is_default(&self) -> bool { + *self == StrokeStyle::default() + } + + /// Cleaned up for use (a file, a command): the miter limit in range, the dash sanitized. + pub fn sanitized(self) -> StrokeStyle { + let miter_limit = if self.miter_limit.is_finite() { self.miter_limit.clamp(MIN_MITER_LIMIT, MAX_MITER_LIMIT) } else { DEFAULT_MITER_LIMIT }; + StrokeStyle { miter_limit, dash: self.dash.and_then(Dash::sanitized), ..self } + } + + pub fn dash_kind(&self) -> DashKind { + self.dash.as_ref().map_or(DashKind::Solid, Dash::kind) + } + + /// The cap the ends of each piece get: dots are always round. + pub fn effective_cap(&self) -> Cap { + if matches!(self.dash, Some(Dash::Dotted { .. })) { Cap::Round } else { self.cap } + } + + /// The farthest the outline reaches from the path, as a multiple of the half-width: miter + /// points reach the miter limit, square caps the corner of their square. + pub fn reach_factor(&self) -> f32 { + let join = if self.join == Join::Miter { self.miter_limit.clamp(MIN_MITER_LIMIT, MAX_MITER_LIMIT) } else { 1.0 }; + let cap = if self.effective_cap() == Cap::Square { std::f32::consts::SQRT_2 } else { 1.0 }; + join.max(cap) + } + + /// The style of the shape scaled by `k`: dashes scale with it. + pub fn scaled(&self, k: f32) -> StrokeStyle { + StrokeStyle { dash: self.dash.as_ref().map(|d| d.scaled(k)), ..self.clone() } + } + + /// `t` of the way to `o` (shape tweens): the miter limit and the dash lengths blend; the + /// caps and joins of the start hold until the end keyframe. + pub fn lerp(&self, o: &StrokeStyle, t: f32) -> StrokeStyle { + let pick = if t >= 1.0 { o } else { self }; + StrokeStyle { cap: pick.cap, join: pick.join, miter_limit: self.miter_limit + (o.miter_limit - self.miter_limit) * t, dash: Dash::lerp(self.dash.as_ref(), o.dash.as_ref(), t) }.sanitized() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dash_patterns_are_sanitized() { + // An odd count repeats (as in SVG); the offset wraps into one period. + let d = Dash::Dashed { lengths: vec![4.0, 2.0, 1.0].into(), offset: 15.0 }.sanitized().unwrap(); + assert_eq!(d, Dash::Dashed { lengths: vec![4.0, 2.0, 1.0, 4.0, 2.0, 1.0].into(), offset: 1.0 }); + // No gaps, or nothing at all: solid. + assert_eq!(Dash::dashed(5.0, 0.0), None); + assert_eq!(Dash::dashed(0.0, 0.0), None); + assert_eq!(Dash::Dashed { lengths: vec![].into(), offset: 0.0 }.sanitized(), None); + // Junk is clamped, never kept. + let d = Dash::Dashed { lengths: vec![f32::NAN, -3.0, 1e30, 2.0].into(), offset: f32::INFINITY }.sanitized().unwrap(); + assert_eq!(d, Dash::Dashed { lengths: vec![0.0, 0.0, MAX_DASH_LENGTH, 2.0].into(), offset: 0.0 }); + let long = Dash::Dashed { lengths: vec![1.0; 99].into(), offset: 0.0 }.sanitized().unwrap(); + assert!(matches!(long, Dash::Dashed { lengths, .. } if lengths.len() == MAX_DASH_ENTRIES)); + assert_eq!(Dash::dotted(f32::NAN), Some(Dash::Dotted { spacing: 0.0 })); + } + + #[test] + fn dots_are_round_zero_length_dashes() { + let st = StrokeStyle { cap: Cap::Butt, dash: Dash::dotted(3.0), ..StrokeStyle::default() }; + assert_eq!(st.effective_cap(), Cap::Round); + assert_eq!(st.dash.as_ref().unwrap().pattern(2.0), (vec![0.0, 5.0], 0.0)); + } + + #[test] + fn style_files_round_trip_and_default_to_round() { + assert!(StrokeStyle::default().is_default()); + let st = StrokeStyle { cap: Cap::Square, join: Join::Miter, miter_limit: 6.0, dash: Dash::dashed(6.0, 3.0) }; + let s = serde_json::to_string(&st).unwrap(); + assert_eq!(s, r#"{"cap":"square","join":"miter","miter_limit":6.0,"dash":{"kind":"dashed","lengths":[6.0,3.0],"offset":0.0}}"#); + assert_eq!(serde_json::from_str::(&s).unwrap(), st); + // Missing fields take the defaults. + assert_eq!(serde_json::from_str::(r#"{"join":"bevel"}"#).unwrap(), StrokeStyle { join: Join::Bevel, ..StrokeStyle::default() }); + assert_eq!(Cap::from_key("none"), Some(Cap::Butt)); + assert_eq!(Join::from_key("Mitre"), Some(Join::Miter)); + } + + #[test] + fn reach_covers_miters_and_square_caps() { + assert_eq!(StrokeStyle::default().reach_factor(), 1.0); + assert_eq!(StrokeStyle { join: Join::Miter, miter_limit: 5.0, ..StrokeStyle::default() }.reach_factor(), 5.0); + assert!((StrokeStyle { cap: Cap::Square, ..StrokeStyle::default() }.reach_factor() - 2f32.sqrt()).abs() < 1e-6); + } + + #[test] + fn styles_blend_in_tweens() { + let a = StrokeStyle { dash: Dash::dashed(2.0, 2.0), ..StrokeStyle::default() }; + let b = StrokeStyle { cap: Cap::Butt, miter_limit: 5.0, dash: Dash::dashed(6.0, 4.0), ..StrokeStyle::default() }; + let m = a.lerp(&b, 0.5); + assert_eq!((m.cap, m.miter_limit, m.dash), (Cap::Round, 4.0, Dash::dashed(4.0, 3.0))); + assert_eq!(a.lerp(&b, 1.0).cap, Cap::Butt); + // Different kinds hold the start's until the end. + let c = StrokeStyle { dash: Dash::dotted(1.0), ..StrokeStyle::default() }; + assert_eq!(a.lerp(&c, 0.9).dash, a.dash); + assert_eq!(a.lerp(&c, 1.0).dash, c.dash); + } +} diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index f8f1db60..ce9540f1 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -85,19 +85,20 @@ fn parse_actions(p: &Value) -> Result> { Ok(list) } -/// The symbol instance `element` (or the selected one) on the active layer's keyframe at the -/// playhead, for editing. +/// The symbol instance `element` on the active layer's keyframe at the playhead (or the selected +/// one, on its layer), for editing. fn instance_mut<'a>(s: &'a mut Session, p: &Value) -> Result<&'a mut Element> { - let id = match opt_u64(p, "element")? { - Some(id) => ElementId(id), - None => match s.selection.as_slice() { - [one] => *one, - [] => return Err(EngineError::State("select a movie clip or button instance, or pass 'element'".into())), + let (layer, id) = match opt_u64(p, "element")? { + // A selected element is looked for on its own layer. + Some(id) => (s.selection.iter().find(|(_, e)| e.0 == id).map_or(s.layer, |(l, _)| l), ElementId(id)), + None => match (s.selection.first(), s.selection.len()) { + (Some(one), 1) => one, + (None, _) => return Err(EngineError::State("select a movie clip or button instance, or pass 'element'".into())), _ => return Err(EngineError::State("select one instance".into())), }, }; let frame = s.frame; - let layer = s.layer_mut(None)?; + let layer = s.layer_mut(Some(layer))?; let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; let k = layer.keyframe_mut(i).ok_or_else(|| EngineError::State("keyframe vanished".into()))?; let e = k.elements.iter_mut().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("no element {} on the active layer at frame {}", id.0, frame + 1)))?; diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs new file mode 100644 index 00000000..a2d67fd8 --- /dev/null +++ b/crates/engine/src/cmds_bone.rs @@ -0,0 +1,445 @@ +//! Bone commands (ADR 0043): join symbol instances into an armature, take bones away, limit and +//! pin joints, pose the armature at a frame by joint angle or by inverse kinematics, and read +//! it back. +//! +//! The armature lives on an armature layer: `bone.add` moves the instances there (making the +//! layer for the first bone). Poses go through [`Session::editable_keyframe_in`], so inside a +//! pose tween they key the frame with the pose it shows, as editing any tweened object does; +//! a drag sends many `bone.solve` calls inside one gesture: one undo step. After every pose +//! edit the keyframe's instances are placed by the pose, so the file holds what shows. + +use crate::cmds_timeline::insert_keyframe_at; +use crate::params::*; +use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session}; +use anicraft_doc::armature::{self, Armature, Bone, BoneId, Limits, MAX_BONES, MAX_LIMIT, MAX_NAME}; +use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Tween, evaluate_layer_elements}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c( + "bone.add", + "Add Bone", + "{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint, stage px; default the end of the bone into `from`, else its registration point), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)", + true, + add as crate::RunFn, + ), + c("bone.remove", "Remove Bone", "{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose", true, remove), + c("bone.set_limits", "Joint Limits", "{bone, constrain?: bool (false: turns freely), min?, max? (°, −360…360, from where it was drawn)} limits how far the joint turns, in every pose", true, set_limits), + c("bone.pin", "Pin Bone", "{bone, pinned: bool} a pinned bone (and the bones it hangs from) stays put while dragging bones below it", true, pin), + c("bone.pose", "Pose Bone", "{bone?, angle? (°, the joint angle: 0 as drawn), rotate_by? (°), dx?, dy? (moves the whole armature), layer? (the armature layer, when no bone is given), frame?} keys the pose at the frame", true, pose), + c("bone.solve", "Drag Bone", "{bone, x, y (stage px: where the bone's end goes), local?: [x, y] (the point dragged, in the bone's instance's space; default its end), frame?} → {reached, error (px), chain}; inverse kinematics turns the bone and the bones above it (limits respected, pinned bones kept)", true, solve), + c("bone.info", "Armatures", "{frame?, layer?} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned", false, info), + ] +} + +/// Where an instance is at the playhead. +struct Found { + layer: LayerId, + index: usize, + kind: LayerKind, + el: Arc, +} + +/// Instance `id` on the scene at the playhead (as it shows: tweened, posed). +fn find_instance(s: &Session, id: ElementId) -> Option { + let tl = s.doc.timeline(s.scene); + tl.layers.iter().enumerate().find_map(|(index, l)| { + let (_, els) = evaluate_layer_elements(l, s.frame)?; + let el = els.iter().find(|e| e.id == id)?.clone(); + Some(Found { layer: l.id, index, kind: l.kind, el }) + }) +} + +/// The armature layer holding bone `id`, and its armature. +fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc)> { + s.doc + .timeline(s.scene) + .layers + .iter() + .filter(|l| l.kind == LayerKind::Armature) + .find_map(|l| l.armature.as_ref().filter(|a| a.bone(id).is_some()).map(|a| (l.id, a.clone()))) + .ok_or_else(|| EngineError::State(format!("no bone with id {} in this scene", id.0))) +} + +fn bone_param(p: &Value) -> Result { + opt_u64(p, "bone")?.map(BoneId).ok_or_else(|| EngineError::Param("param 'bone' (a bone id; see bone.info) is required".into())) +} + +/// Largest stage coordinate a bone point may have. +const MAX_COORD: f32 = 1_000_000.0; + +fn opt_point(p: &Value, key: &str) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be [x, y] (finite numbers within ±1,000,000)")); + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() == 2 => { + let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() <= f64::from(MAX_COORD)).map(|v| v as f32).ok_or_else(bad); + Ok(Some(Vec2::new(n(0)?, n(1)?))) + } + Some(_) => Err(bad()), + } +} + +fn unlocked(s: &Session, id: LayerId) -> Result<()> { + let tl = s.doc.timeline(s.scene); + let l = tl.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + if l.locked || tl.locked_by_folder(id) { + return Err(EngineError::State(format!("layer '{}' is locked", l.name))); + } + Ok(()) +} + +/// Takes instance `id` off the keyframe covering the playhead on layer `layer`. +fn take_off(s: &mut Session, layer: LayerId, id: ElementId) -> Result<()> { + let frame = s.frame; + let l = s.layer_mut(Some(layer))?; + if let Some(k) = l.keyframe_index_at(frame).and_then(|i| l.keyframe_mut(i)) { + k.elements.retain(|e| e.id != id); + } + Ok(()) +} + +/// A layer name `base_N` no layer of the scene has yet. +fn fresh_name(s: &Session, base: &str) -> String { + let tl = s.doc.timeline(s.scene); + (1..).map(|n| format!("{base}{n}")).find(|n| tl.layers.iter().all(|l| &l.name != n)).unwrap_or_else(|| base.to_string()) +} + +/// Places the instances of every keyframe of `layer` by its pose (after the armature changed). +fn rebake(layer: &mut Layer) { + let Some(arm) = layer.armature.clone() else { return }; + for k in &mut layer.keyframes { + let k = Arc::make_mut(k); + let pose = k.pose.allowed(&arm); + armature::apply(&arm, &mut k.elements, &pose); + } +} + +fn add(s: &mut Session, p: &Value) -> Result { + let req = |k: &str| opt_u64(p, k)?.map(ElementId).ok_or_else(|| EngineError::Param(format!("param '{k}' (an instance id) is required"))); + let (from, to) = (req("from")?, req("to")?); + let (head, tail) = (opt_point(p, "head")?, opt_point(p, "tail")?); + let name = opt_str(p, "name")?.unwrap_or("").trim().to_string(); + if name.len() > MAX_NAME { + return Err(EngineError::Param(format!("param 'name' must be at most {MAX_NAME} bytes"))); + } + if from == to { + return Err(EngineError::Param("a bone joins two different instances".into())); + } + let missing = |id: ElementId| EngineError::State(format!("no instance with id {} on the stage at frame {}", id.0, s.frame + 1)); + let f = find_instance(s, from).ok_or_else(|| missing(from))?; + let t = find_instance(s, to).ok_or_else(|| missing(to))?; + for x in [&f, &t] { + if !matches!(x.el.kind, ElementKind::Symbol { .. }) { + return Err(EngineError::State("bones join symbol instances: convert the artwork to a symbol first (Modify › Convert to Symbol, F8)".into())); + } + if !matches!(x.kind, LayerKind::Normal | LayerKind::Armature) { + return Err(EngineError::State("bones join instances on normal layers (not on guide or mask layers)".into())); + } + unlocked(s, x.layer)?; + } + let tl = s.doc.timeline(s.scene); + let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default()); + let (fa, ta) = (arm_of(&f), arm_of(&t)); + match (&fa, &ta) { + (_, Some(a)) if f.layer == t.layer && a.bone_into(to).is_some() => return Err(EngineError::State("that instance already hangs from a bone; each instance has one bone into it".into())), + (_, Some(_)) if f.layer == t.layer => return Err(EngineError::State("that instance is the armature's root: drag from the root to the other instances instead".into())), + (None, Some(_)) => return Err(EngineError::State("start the bone on the armature: drag from one of its instances to the new one".into())), + (Some(_), Some(_)) => return Err(EngineError::State("those instances are in different armatures".into())), + _ => {} + } + if fa.as_ref().is_some_and(|a| a.bones.len() >= MAX_BONES) { + return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones"))); + } + let (wf, wt) = (f.el.transform, t.el.transform); + let singular = || EngineError::State("an instance scaled to nothing can't hold a bone".into()); + let (inv_f, inv_t) = (wf.inverse().ok_or_else(singular)?, wt.inverse().ok_or_else(singular)?); + // The joint: given, else the end of the bone into `from` (a chain joins end to start), else + // its registration point. + let into_from = fa.as_ref().and_then(|a| a.bone_into(from)).map(|b| wf.apply(b.tail)); + let head = head.or(into_from).unwrap_or(wf.translation()); + let tail = tail.unwrap_or(wt.translation()); + let rest = inv_f.mul(&wt); + if !rest.is_finite() || rest.inverse().is_none() { + return Err(singular()); + } + let id = BoneId(s.doc.alloc_id()); + let bone = Bone { id, name, parent: from, child: to, head: inv_f.apply(head), tail: inv_t.apply(tail), rest, limits: None, pinned: false }; + take_off(s, t.layer, to)?; + let lid = match fa { + Some(_) => { + // Another bone on this armature: the new instance joins every pose, at angle 0. + let l = s.layer_mut(Some(f.layer))?; + let mut arm = l.armature.as_deref().cloned().unwrap_or_default(); + arm.bones.push(bone); + l.armature = Some(Arc::new(arm)); + for k in &mut l.keyframes { + Arc::make_mut(k).elements.push(t.el.clone()); + } + rebake(l); + f.layer + } + None => { + // The first bone: both instances move to a new armature layer above them, whose one + // pose spans from their keyframe to the end of the timeline. + let (start, end) = s.doc.timeline(s.scene).layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); + let end = end.max(s.frame_count()); + take_off(s, f.layer, from)?; + if s.doc.timeline(s.scene).layers.len() >= 1000 { + return Err(EngineError::State("too many layers (limit 1000)".into())); + } + let lid = LayerId(s.doc.alloc_id()); + let mut layer = Layer::new(lid, fresh_name(s, "Armature_")); + layer.kind = LayerKind::Armature; + // Bones show in the layer colour: a green that reads on light and dark artwork. + layer.color = Rgba::hex(0x2fb67c); + layer.armature = Some(Arc::new(Armature { bones: vec![bone] })); + let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); + k.elements = vec![f.el.clone(), t.el.clone()]; + k.tween = Some(Tween::default()); + layer.keyframes = vec![Arc::new(k)]; + let index = f.index.min(t.index); + let tl = s.doc.timeline_mut(s.scene); + layer.parent = tl.container_at(index, LayerKind::Armature); + tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); + tl.repair_masks(); + lid + } + }; + s.layer = lid; + s.selection.clear(); + Ok(json!({"bone": id.0, "layer": lid.0, "created": lid != f.layer})) +} + +/// How many keyframes of an armature layer hold a pose of their own (more than one: the +/// armature is animated). +pub(crate) fn poses(l: &Layer) -> usize { + l.keyframes.iter().filter(|k| !k.elements.is_empty()).count() +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let gone = arm.subtree(id); + let mut left = (*arm).clone(); + left.bones.retain(|b| !gone.contains(&b.id)); + let dissolve = left.is_empty(); + let freed: Vec = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; + let tl = s.doc.timeline(s.scene); + let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame()); + // The freed instances as they look at the playhead (or at the armature's first frame). + let at = s.frame.clamp(start, end.saturating_sub(1).max(start)); + let shown: Vec> = evaluate_layer_elements(layer, at).map(|(_, e)| e.iter().filter(|e| freed.contains(&e.id)).cloned().collect()).unwrap_or_default(); + let folder = layer.parent.filter(|p| tl.layer(*p).is_some_and(|x| x.kind == LayerKind::Folder)); + let new_id = LayerId(s.doc.alloc_id()); + let mut freed_layer = Layer::new(new_id, fresh_name(s, "Layer ")); + freed_layer.parent = folder; + let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); + k.elements = shown; + freed_layer.keyframes = vec![Arc::new(k)]; + let tl = s.doc.timeline_mut(s.scene); + if dissolve { + tl.layers.retain(|l| l.id != lid); + tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer)); + } else { + let l = tl.layer_mut(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + for k in &mut l.keyframes { + let k = Arc::make_mut(k); + k.elements.retain(|e| !freed.contains(&e.id)); + k.pose.retain(|b| !gone.contains(&b)); + } + l.armature = Some(Arc::new(left)); + rebake(l); + tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer)); + } + tl.repair_masks(); + s.layer = if dissolve { new_id } else { lid }; + s.selection.clear(); + Ok(json!({"removed": gone.iter().map(|b| b.0).collect::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "layer": new_id.0, "armature_removed": dissolve})) +} + +fn set_limits(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let constrain = opt_bool(p, "constrain")?; + let (min, max) = (opt_f32(p, "min")?, opt_f32(p, "max")?); + let deg = MAX_LIMIT.to_degrees(); + for v in [min, max].into_iter().flatten() { + if !(-deg..=deg).contains(&v) { + return Err(EngineError::Param(format!("joint limits must be between −{deg:.0}° and {deg:.0}°"))); + } + } + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let cur = arm.bone(id).and_then(|b| b.limits); + let limits = if constrain == Some(false) { + None + } else { + // Turning limits on without numbers: a quarter turn either way. + let base = cur.unwrap_or(Limits { min: -std::f32::consts::FRAC_PI_2, max: std::f32::consts::FRAC_PI_2 }); + let l = Limits { min: min.map_or(base.min, f32::to_radians), max: max.map_or(base.max, f32::to_radians) }; + if l.min > l.max { + return Err(EngineError::Param("the joint's min must be at most its max".into())); + } + Some(l) + }; + let l = s.layer_mut(Some(lid))?; + let mut arm = (*arm).clone(); + if let Some(b) = arm.bone_mut(id) { + b.limits = limits; + } + // Every pose keeps to the new limits. + for k in &mut l.keyframes { + if let Some(b) = arm.bone(id) { + let a = k.pose.angle(id); + if b.allow(a) != a { + Arc::make_mut(k).pose.set(id, b.allow(a)); + } + } + } + l.armature = Some(Arc::new(arm)); + rebake(l); + Ok(json!({"bone": id.0, "constrain": limits.is_some(), "min": limits.map(|l| l.min.to_degrees()), "max": limits.map(|l| l.max.to_degrees())})) +} + +fn pin(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let pinned = opt_bool(p, "pinned")?.ok_or_else(|| EngineError::Param("param 'pinned' (true or false) is required".into()))?; + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let mut arm = (*arm).clone(); + if let Some(b) = arm.bone_mut(id) { + b.pinned = pinned; + } + s.layer_mut(Some(lid))?.armature = Some(Arc::new(arm)); + Ok(json!({"bone": id.0, "pinned": pinned})) +} + +/// Runs `edit` on the keyframe of armature layer `lid` that a pose at `frame` changes (keying +/// the frame inside a pose tween, extending the layer past its end), then places the +/// keyframe's instances by its pose. +fn edit_pose(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Armature, &mut Keyframe) -> Result) -> Result { + if frame > MAX_FRAME { + return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); + } + let arm = s.doc.timeline(s.scene).layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?; + // Past the end a pose carries on from the last one (not a blank keyframe). + { + let l = s.layer_mut(Some(lid))?; + if l.keyframe_at(frame).is_none() && frame >= l.end_frame() && !l.locked { + insert_keyframe_at(l, frame, true)?; + } + } + let (layer, at) = (s.layer, s.frame); + s.layer = lid; + s.frame = frame; + let out = (|| { + let kf = s.editable_keyframe_in(KeyEdit::Pose)?; + let v = edit(&arm, kf)?; + kf.pose = kf.pose.allowed(&arm); + armature::apply(&arm, &mut kf.elements, &kf.pose); + Ok(v) + })(); + s.layer = layer; + s.frame = at; + out +} + +fn pose(s: &mut Session, p: &Value) -> Result { + let bone = opt_u64(p, "bone")?.map(BoneId); + let (angle, rotate_by, dx, dy) = (opt_f32(p, "angle")?, opt_f32(p, "rotate_by")?, opt_f32(p, "dx")?, opt_f32(p, "dy")?); + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); + let lid = match (bone, opt_u64(p, "layer")?) { + (Some(b), _) => find_bone(s, b)?.0, + (None, Some(l)) => LayerId(l), + (None, None) => s.layer, + }; + if bone.is_none() && (angle.is_some() || rotate_by.is_some()) { + return Err(EngineError::Param("param 'bone' says which joint 'angle' or 'rotate_by' turns".into())); + } + let v = edit_pose(s, lid, frame, |arm, kf| { + let mut out = json!({"layer": lid.0}); + if let Some(b) = bone.and_then(|b| arm.bone(b)) { + let cur = kf.pose.angle(b.id); + let next = b.allow(angle.map_or(cur, f32::to_radians) + rotate_by.unwrap_or(0.0).to_radians()); + kf.pose.set(b.id, next); + out["bone"] = json!(b.id.0); + out["angle"] = json!(next.to_degrees()); + } + if dx.is_some() || dy.is_some() { + let by = Affine::translate(dx.unwrap_or(0.0), dy.unwrap_or(0.0)); + let roots = arm.roots(); + for e in kf.elements.iter_mut().filter(|e| roots.contains(&e.id)) { + let m = by.mul(&e.transform); + let t = m.translation(); + if m.is_finite() && t.x.abs() <= MAX_COORD && t.y.abs() <= MAX_COORD { + Arc::make_mut(e).transform = m; + } + } + } + Ok(out) + })?; + Ok(v) +} + +fn solve(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let target = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if target.x.abs() > MAX_COORD || target.y.abs() > MAX_COORD { + return Err(EngineError::Param("the target must be within ±1,000,000 px".into())); + } + let local = opt_point(p, "local")?; + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); + let (lid, arm) = find_bone(s, id)?; + if armature::movable_chain(&arm, id).is_empty() { + return Err(EngineError::State("that bone is pinned, or hangs from a pinned bone: unpin it to drag it".into())); + } + let tail = arm.bone(id).map_or(Vec2::new(0.0, 0.0), |b| b.tail); + edit_pose(s, lid, frame, |arm, kf| { + let r = armature::solve(arm, &kf.elements, &kf.pose, id, local.unwrap_or(tail), target).ok_or_else(|| EngineError::State("the bone's instances aren't on this frame".into()))?; + kf.pose = r.pose; + Ok(json!({"bone": id.0, "reached": r.error <= 0.5, "error": r.error, "chain": r.chain})) + }) +} + +fn info(s: &mut Session, p: &Value) -> Result { + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); + let only = opt_u64(p, "layer")?.map(LayerId); + let tl = s.doc.timeline(s.scene); + let deg = |v: f32| v.to_degrees(); + let pt = |v: Vec2| json!([v.x, v.y]); + let list: Vec = tl + .layers + .iter() + .filter(|l| l.kind == LayerKind::Armature && only.is_none_or(|o| o == l.id)) + .filter_map(|l| { + let arm = l.armature.as_deref()?; + let pose = armature::pose_at(l, frame).unwrap_or_default(); + let (_, els) = evaluate_layer_elements(l, frame).unwrap_or((0, std::borrow::Cow::Borrowed(&[]))); + let at = armature::bones_at(arm, &els, &pose); + let bones: Vec = arm + .bones + .iter() + .map(|b| { + let g = at.iter().find(|g| g.id == b.id); + json!({ + "id": b.id.0, "name": b.name, "from": b.parent.0, "to": b.child.0, + "parent_bone": arm.parent_bone(b).map(|x| x.id.0), + "head": g.map(|g| pt(g.head)), "tail": g.map(|g| pt(g.tail)), + "angle": deg(b.allow(pose.angle(b.id))), + "min": b.limits.map(|l| deg(l.min)), "max": b.limits.map(|l| deg(l.max)), + "pinned": b.pinned, + }) + }) + .collect(); + Some(json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::>(), "poses": poses(l), "bones": bones})) + }) + .collect(); + Ok(json!({"frame": frame, "armatures": list})) +} diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index 8afb5555..df6e1423 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -170,10 +170,11 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { PaintMode::Behind => kf.elements.insert(0, Arc::new(el)), PaintMode::Normal | PaintMode::Fills => kf.elements.push(Arc::new(el)), } - s.selection = vec![id]; + s.select_only([id]); return Ok(json!({"element": id.0, "elements": [id.0], "mode": mode.key(), "merged": false})); } - s.selection = merge::merge_in_order(s, vec![el], mode.order())?; - let ids: Vec = s.selection.iter().map(|e| e.0).collect(); + let merged = merge::merge_in_order(s, vec![el], mode.order())?; + s.select_only(merged); + let ids: Vec = s.selection.id_list(); Ok(json!({"element": ids.first(), "elements": ids, "mode": mode.key(), "merged": true})) } diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index 2f099232..e8fd10a3 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -132,7 +132,7 @@ fn set(s: &mut Session, p: &Value) -> Result { s.layer = id; s.frame = frame; let out: Result = (|| { - let kf = s.editable_keyframe_in(true)?; + let kf = s.editable_keyframe_in(crate::KeyEdit::Camera)?; let i = match kf.elements.iter().position(|e| matches!(e.kind, ElementKind::Camera)) { Some(i) => i, None => { diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 18bbd5d6..494f55f6 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -1,7 +1,7 @@ //! Drawing, selection, element and symbol commands. use crate::params::*; -use crate::{CommandSpec, EngineError, Result, Session}; +use crate::{CommandSpec, EngineError, Result, Selection, Session}; use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Decomposed, Path, Vec2}; use serde_json::{Value, json}; @@ -10,36 +10,37 @@ 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?, profile?, object?}", true, draw_rect as crate::RunFn), - c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?, profile?, object?}", true, draw_ellipse), - c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, object?}", true, draw_star), - c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line), + c("draw.rect", "Rectangle", "", None, "{x, y, w, h, radius?, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_rect as crate::RunFn), + c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_ellipse), + c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, cap?, join?, style?, dash?, object?}", true, draw_star), + c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (the line style, as stroke.set_style; default: the tool's), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line), c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing), + c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", None, "{on?: bool} (default: toggle) dragged points and selections snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point and raw.move_handle do nothing while it is off)", false, snap_to_objects), c("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?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..]}", true, set_stroke), - c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, set_alpha), - c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, set_blend), - c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, set_filters), - c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, set_loop), + c("edit.delete", "Clear", "Edit", Some("Delete"), "{} (on every layer with selected items)", true, delete_selection), + c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?} (each copy on its original's layer)", true, |s, p| s.each_layer(true, |s| duplicate(s, p))), + c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); the active layer becomes the first one's unless it has some of them", false, select), + c("element.pick", "Select at Point", "", None, "{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer", false, pick), + c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends (the nearest to `from`) then snaps onto a point, line or fill edge of the rest within that distance", true, translate), + c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), + c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), + c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), + c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), + c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))), + c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))), + c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))), c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the selected instance's)}", true, set_symbol_kind), - c("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("element.rename", "Instance Name", "", None, "{name}", true, |s, p| s.each_layer(true, |s| rename(s, p))), + c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, true))), + c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, true))), + c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, false))), + c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))), + c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol), + c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))), c("library.place", "Place Instance", "", None, "{symbol | bitmap, x?, y?}", true, place), ] } @@ -65,6 +66,7 @@ pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option s.style.stroke_width, }; let profile = opt_profile(p, "profile")?.unwrap_or_else(|| s.style.profile()); + let line = opt_stroke_style(p, &s.style.line, width)?.unwrap_or_else(|| s.style.line.clone()); let stroke = if p.get("stroke").is_some_and(Value::is_null) || width <= 0.0 { None } else { @@ -73,7 +75,7 @@ pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option (s.style.use_stroke || !closed).then_some(Stroke::new(s.style.stroke, width)), } } - .map(|st| st.with_profile(profile)); + .map(|st| st.with_profile(profile).with_style(line)); if fill.is_none() && stroke.is_none() { return Err(EngineError::Param("shape would be invisible: give it a fill or a stroke".into())); } @@ -99,7 +101,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, // A gradient or bitmap from the fill swatch is in stage space: it stays where it is on the // stage (Animate's Lock Fill after the Eyedropper). let fill = fill.map(|f| f.transformed(&Affine::translate(-origin.x, -origin.y))); - let merge = !object && crate::merge::can_merge(fill.as_ref(), stroke.as_ref()); + let merge = !object && crate::merge::can_merge(stroke.as_ref()); let id = ElementId(s.doc.alloc_id()); let el = Element { id, @@ -109,8 +111,9 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge }), }; if merge { - s.selection = crate::merge::merge_in(s, vec![el])?; - let ids: Vec = s.selection.iter().map(|e| e.0).collect(); + let merged = crate::merge::merge_in(s, vec![el])?; + s.select_only(merged); + let ids: Vec = s.selection.id_list(); return Ok(json!({"element": ids.first(), "elements": ids, "kind": name, "merged": true})); } let kf = s.editable_keyframe()?; @@ -118,7 +121,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, return Err(EngineError::State("too many elements on this keyframe".into())); } kf.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(json!({"element": id.0, "kind": name})) } @@ -165,6 +168,11 @@ fn draw_line(s: &mut Session, p: &Value) -> Result { add_shape(s, "line", Path::line(a - c, b - c), c, None, stroke, object_param(s, p)?) } +fn snap_to_objects(s: &mut Session, p: &Value) -> Result { + s.style.snap_objects = opt_bool(p, "on")?.unwrap_or(!s.style.snap_objects); + Ok(json!({"snap_to_objects": s.style.snap_objects})) +} + fn object_drawing(s: &mut Session, p: &Value) -> Result { s.style.object_drawing = opt_bool(p, "on")?.unwrap_or(!s.style.object_drawing); Ok(json!({"object_drawing": s.style.object_drawing})) @@ -172,27 +180,63 @@ fn object_drawing(s: &mut Session, p: &Value) -> Result { // ----- selection -------------------------------------------------------------------------- +/// Everything on every visible, unlocked layer at the playhead, as Animate's Select All. fn select_all(s: &mut Session, _: &Value) -> Result { - s.selection = s.visible_elements().iter().map(|e| e.id).collect(); + let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let mut sel = Selection::default(); + for l in layers.into_iter().filter(|l| s.gathers(*l)) { + sel.extend_on(l, s.elements_on(l).iter().map(|e| e.id)); + } + s.selection = sel; Ok(json!({"selected": s.selection.len()})) } +/// Most ids `element.select` takes. +const MAX_SELECT: usize = 100_000; + 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()))?; + if ids.len() > MAX_SELECT { + return Err(EngineError::Param(format!("param 'ids' has more than {MAX_SELECT} ids"))); + } let add = opt_bool(p, "add")?.unwrap_or(false); - let present: Vec = s.visible_elements().iter().map(|e| e.id).collect(); + // Where each element is at the playhead: on `layer`, else the active layer first, then the + // others top to bottom. + let order: Vec = match opt_u64(p, "layer")?.map(LayerId) { + Some(l) if s.doc.timeline(s.scene).layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), + Some(l) => vec![l], + None => std::iter::once(s.layer).chain(s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), + }; + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for l in order { + for e in s.elements_on(l) { + at.entry(e.id).or_insert(l); + } + } + let mut picked: Vec<(LayerId, ElementId)> = Vec::with_capacity(ids.len()); + for id in ids.into_iter().map(ElementId) { + let Some(&l) = at.get(&id) else { + return Err(EngineError::State(format!("element {} is not on the active layer, or any layer, at this frame", id.0))); + }; + if !s.selectable(l) { + let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + return Err(EngineError::State(format!("element {} is on layer '{name}', which is locked or hidden", id.0))); + } + picked.push((l, id)); + } 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); - } + for &(l, id) in &picked { + s.selection.insert(l, id); } - Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>()})) + // As a click does: the active layer is where the artwork is. + if let Some(&(l, _)) = picked.first() + && !picked.iter().any(|(x, _)| *x == s.layer) + { + s.layer = l; + } + Ok(json!({"selected": s.selection.id_list()})) } fn pick(s: &mut Session, p: &Value) -> Result { @@ -200,19 +244,13 @@ fn pick(s: &mut Session, p: &Value) -> Result { 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(); - } + // Shift adds it to (or takes it from) the selection, whichever layers that is on. 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]; + s.selection.toggle(layer, el); + } else if !s.selection.contains(layer, el) { + s.selection = Selection::only(layer, [el]); } + s.layer = layer; Ok(json!({"layer": layer.0, "element": el.0})) } None => { @@ -227,13 +265,39 @@ fn pick(s: &mut Session, p: &Value) -> Result { // ----- 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); + let (mut dx, mut dy) = (f32_req(p, "dx")?, f32_req(p, "dy")?); + let snap = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0)); + let from = match p.get("from").filter(|v| !v.is_null()) { + None => None, + Some(v) => { + let xy = v.as_array().filter(|a| a.len() == 2).and_then(|a| Some(Vec2::new(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32))); + Some(xy.filter(|q| q.is_finite()).ok_or_else(|| EngineError::Param("param 'from' must be [x, y]".into()))?) + } + }; + let n = move_by(s, Vec2::new(dx, dy))?; + // Snapping while dragging (ADR 0041): a little more, onto what is near. + let mut snapped = Value::Null; + if snap > 0.0 + && let Some((extra, at, kind)) = crate::cmds_raw::snap_selection(s, snap, from) + { + move_by(s, extra)?; + (dx, dy) = (dx + extra.x, dy + extra.y); + snapped = json!({"x": at.x, "y": at.y, "to": kind.key()}); } - Ok(json!({"moved": n})) + Ok(json!({"moved": n, "dx": dx, "dy": dy, "snapped": snapped})) +} + +/// Moves the selection by `d` on every layer it is on; how many elements moved. +fn move_by(s: &mut Session, d: Vec2) -> Result { + let v = s.each_layer(true, |s| { + let els = s.selected_elements_mut()?; + let n = els.len(); + for e in els { + e.transform = Affine::translate(d.x, d.y).mul(&e.transform); + } + Ok(json!({"moved": n})) + })?; + Ok(v["moved"].as_u64().unwrap_or(0)) } fn set_transform(s: &mut Session, p: &Value) -> Result { @@ -306,12 +370,14 @@ fn set_stroke(s: &mut Session, p: &Value) -> Result { } let profile = opt_profile(p, "profile")?; let default = s.style.clone(); + // Checked once up front, so a bad style param changes nothing. + opt_stroke_style(p, &default.line, default.stroke_width)?; for sh in shapes_mut(s)? { if remove { sh.stroke = None; continue; } - let mut st = sh.stroke.take().unwrap_or_else(|| Stroke::new(default.stroke, default.stroke_width).with_profile(default.profile())); + let mut st = sh.stroke.take().unwrap_or_else(|| default.new_stroke(default.stroke, default.stroke_width)); if let Some(c) = color { st.color = c; } @@ -321,6 +387,9 @@ fn set_stroke(s: &mut Session, p: &Value) -> Result { if let Some(pr) = &profile { st = st.with_profile(pr.clone()); } + if let Some(line) = opt_stroke_style(p, &st.style, st.width)? { + st = st.with_style(line); + } sh.stroke = (st.width > 0.0).then_some(st); } Ok(json!({"ok": true})) @@ -467,8 +536,8 @@ fn set_symbol_kind(s: &mut Session, p: &Value) -> Result { Some(id) => SymbolId(id), None => { // The symbol of the selected instance. - let sel = s.selection.first().copied().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?; - s.visible_elements() + let (layer, sel) = s.selection.first().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?; + s.elements_on(layer) .iter() .find(|e| e.id == sel) .and_then(|e| match e.kind { @@ -491,8 +560,13 @@ fn rename(s: &mut Session, p: &Value) -> Result { Ok(json!({"name": name})) } -pub(crate) fn delete(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); +/// Clear: the selection goes, on every layer it is on. +pub(crate) fn delete_selection(s: &mut Session, p: &Value) -> Result { + s.each_layer(true, |s| delete(s, p)) +} + +fn delete(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -507,7 +581,7 @@ pub(crate) fn delete(s: &mut Session, _: &Value) -> Result { 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(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -521,12 +595,12 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { out.push(Arc::new(e)); } s.editable_keyframe()?.elements.extend(out); - s.selection = new_ids.clone(); + s.select_only(new_ids.iter().copied()); Ok(json!({"created": new_ids.iter().map(|e| e.0).collect::>()})) } fn arrange(s: &mut Session, front: bool) -> Result { - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -539,7 +613,7 @@ fn arrange(s: &mut Session, front: bool) -> Result { /// 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(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -565,31 +639,22 @@ fn arrange_step(s: &mut Session, forward: bool) -> Result { // ----- symbols ---------------------------------------------------------------------------- +/// Convert to Symbol. The registration point is the centre of the selection's bounds. A +/// selection on several layers becomes one symbol with those layers inside it (named and +/// stacked as they are), and its instance lands on the topmost of them, where its first +/// selected element was; the other layers lose what was selected (ADR 0044). pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { - let sel = s.selection.clone(); - if sel.is_empty() { + let layers = s.selected_layers(); + let Some(&top) = layers.first() else { return Err(EngineError::State("select something to convert".into())); - } + }; let n = s.doc.library.len() + 1; let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}")); 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 first_layer = 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(), @@ -597,20 +662,46 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, }; - 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; + // Children are stored relative to the registration point (the selection centre). + let to_local = Affine::translate(-center.x, -center.y); + let single = layers.len() == 1; + let mut inner: Vec> = Vec::with_capacity(layers.len()); + for l in layers { + let sel = s.selection.on(l); + let source = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let picked = s.with_layer(l, |s| -> Result>> { + let kf = s.editable_keyframe()?; + let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len()); + let (picked, mut rest): (Vec>, Vec>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id)); + if l == top { + rest.insert(first_pos.min(rest.len()), Arc::new(instance.clone())); + } + kf.elements = rest; + Ok(picked) + })?; + 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 id = if inner.is_empty() { first_layer } else { LayerId(s.doc.alloc_id()) }; + let mut layer = Layer::new(id, if single { "Layer 1".to_string() } else { source }); + if let Some(k) = layer.keyframe_mut(0) { + k.elements = children; + } + inner.push(Arc::new(layer)); } - s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); - s.selection = vec![inst_id]; - Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name})) + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: inner } })); + s.layer = top; + s.select_only([inst_id]); + Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0})) } fn break_apart(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -657,7 +748,7 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { return Err(EngineError::State("the selection has no symbol instances or text to break apart".into())); } s.editable_keyframe()?.elements = out; - s.selection = fresh_ids.clone(); + s.select_only(fresh_ids.iter().copied()); Ok(json!({"created": fresh_ids.len()})) } @@ -682,7 +773,7 @@ fn place(s: &mut Session, p: &Value) -> Result { kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(json!({"element": id.0})) } @@ -708,6 +799,6 @@ fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> R }), }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(json!({"element": id.0})) } diff --git a/crates/engine/src/cmds_erase.rs b/crates/engine/src/cmds_erase.rs index bf532ff2..3f3d22f9 100644 --- a/crates/engine/src/cmds_erase.rs +++ b/crates/engine/src/cmds_erase.rs @@ -101,7 +101,7 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: EraseMode::Fills => (fills.clone(), touching.clone()), // Only the lines take part, so the fills stay exactly as they are. EraseMode::Lines => (lines.clone(), lines.clone()), - EraseMode::SelectedFills => (fills.iter().copied().filter(|i| el(i).is_some_and(|e| s.selection.contains(&e.id))).collect(), touching.clone()), + EraseMode::SelectedFills => (fills.iter().copied().filter(|i| el(i).is_some_and(|e| s.selection.contains(s.layer, e.id))).collect(), touching.clone()), EraseMode::Inside => { // The topmost raw fill under the start of the stroke. let at = fills.iter().rev().copied().find(|i| el(i).is_some_and(|e| mergeable(e).is_some_and(|sh| sh.path.contains(start, &e.transform, sh.fill_rule)))); @@ -111,7 +111,7 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: if targets.is_empty() { s.doc = before; return nothing(match mode { - EraseMode::SelectedFills if s.selection.is_empty() => "select the fills to erase first", + EraseMode::SelectedFills if s.selection.on(s.layer).is_empty() => "select the fills to erase first", EraseMode::Inside => "start the stroke on a fill to erase inside it", _ => "nothing raw to erase there", }); @@ -120,8 +120,9 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: // cut the fills they cross and nothing hides them). let rest: Vec = members.iter().copied().filter(|i| !targets.contains(i)).collect(); let (rest_fills, rest_lines): (Vec, Vec) = rest.into_iter().partition(is_fill); + let here = s.layer; let selected = s.selection.clone(); - let shape = |i: &usize| el(i).map(|e| Part::Shape(e, selected.contains(&e.id))); + let shape = |i: &usize| el(i).map(|e| Part::Shape(e, selected.contains(here, e.id))); let parts: Vec = targets.iter().filter_map(shape).chain(std::iter::once(Part::Eraser(eraser))).chain(rest_fills.iter().filter_map(shape)).chain(rest_lines.iter().filter_map(shape)).collect(); let Some((out, picked)) = merge::remerge(s, &parts) else { s.doc = before; @@ -139,8 +140,8 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: let gone: Vec = members.iter().filter_map(el).map(|e| e.id).collect(); merge::replace(s, &members, out, false)?; // What stays selected: the rest of the selection, and what is left of selected shapes. - s.selection.retain(|id| !gone.contains(id)); - s.selection.extend(picked); + s.selection.retain(|l, id| l != here || !gone.contains(&id)); + s.selection.extend_on(here, picked); Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0)})) } @@ -258,7 +259,8 @@ fn faucet(s: &mut Session, p: &Value) -> Result { let (id, line) = (hit.id, matches!(&hit.kind, ElementKind::Shape(sh) if sh.fill.is_none())); let kf = s.editable_keyframe()?; kf.elements.retain(|e| e.id != id); - s.selection.retain(|x| *x != id); + let here = s.layer; + s.selection.remove(here, id); Ok(json!({"deleted": id.0, "kind": if line { "line" } else { "fill" }})) } diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 1799c793..2d59059b 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -168,14 +168,19 @@ fn open(s: &mut Session, p: &Value) -> Result { } else { anicraft_xfl::import_path(&path) }; - let (doc, report) = imported.map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; + let (mut doc, report) = imported.map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; + // Raw artwork arrives one shape per style: each keyframe's becomes one merged drawing, + // as it was in Animate (ADR 0042). + let merged = crate::merge::merge_document(&mut doc); 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); info["kept"] = json!(report.kept); + info["runs"] = json!(report.runs); info["missing_fonts"] = json!(report.missing_fonts); + info["merged_keyframes"] = json!(merged); return Ok(info); } let doc = format::load(&path)?; @@ -347,7 +352,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { s.layer = lid; (lid, ids, made, Some(fid.0)) }; - s.selection = ids.clone(); + s.select_only(ids.iter().copied()); Ok(json!({ "layer": layer_id.0, "folder": folder, diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index 7488f1b8..209bf9f7 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -2,7 +2,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{Element, ElementId, ElementKind, Symbol, SymbolId}; +use anicraft_doc::{Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Symbol, SymbolId}; use anicraft_geom::{Affine, Rect, Vec2}; use serde_json::{Value, json}; use std::collections::HashSet; @@ -12,15 +12,15 @@ 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("edit.copy", "Copy", "Edit", Some("Ctrl+C"), "{} (the selection on every layer, each layer's artwork kept apart)", false, copy), + c("edit.paste", "Paste in Center", "Edit", Some("Ctrl+V"), "{x?, y?} (centre of the pasted artwork; default: offset 10 px). Artwork copied from one layer lands on the active layer; from several, back on those layers when they are all here, else on the active layer and the ones below it, creating missing ones", true, paste), + c("edit.paste_in_place", "Paste in Place", "Edit", Some("Ctrl+Shift+V"), "{} (layers as edit.paste)", true, paste_in_place), + c("modify.transform", "Transform", "", None, "{a, b, c, d, e, f} affine applied in stage space (free transform), to the selection on every layer", true, |s, p| s.each_layer(true, |s| transform(s, p))), 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("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, |s, p| s.each_layer(true, |s| remove_transform(s, p))), 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)), @@ -34,17 +34,34 @@ pub fn specs() -> Vec { // ----- clipboard -------------------------------------------------------------------------------- -/// Copied artwork: elements as they look at the playhead, plus every symbol they need, so a -/// paste into another document is complete. +/// Copied artwork: elements as they look at the playhead, kept apart by the layer they came from, +/// plus every symbol they need, so a paste into another document is complete. #[derive(Clone, Default)] pub struct Clipboard { - pub elements: Vec, + /// One entry per layer the selection was on, top to bottom. + pub layers: Vec, pub symbols: Vec>, } +/// One layer's copied artwork. +#[derive(Clone)] +pub struct ClipLayer { + /// The layer it came from, and its name (for a layer a paste has to create). + pub layer: LayerId, + pub name: String, + pub elements: Vec, +} + impl Clipboard { pub fn is_empty(&self) -> bool { - self.elements.is_empty() + self.layers.iter().all(|l| l.elements.is_empty()) + } + /// Every copied element, layer by layer. + pub fn elements(&self) -> impl Iterator { + self.layers.iter().flat_map(|l| l.elements.iter()) + } + pub fn len(&self) -> usize { + self.layers.iter().map(|l| l.elements.len()).sum() } } @@ -76,26 +93,35 @@ pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec } fn copy(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); - if sel.is_empty() { + let layers = s.selected_layers(); + if layers.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})) + let mut copied = Vec::with_capacity(layers.len()); + for l in layers { + let elements: Vec = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect(); + let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + if !elements.is_empty() { + copied.push(ClipLayer { layer: l, name, elements }); + } + } + let all: Vec = copied.iter().flat_map(|c| c.elements.iter().cloned()).collect(); + let symbols = collect_symbols(s, &all); + let n = all.len(); + let layers = copied.len(); + s.clipboard = Clipboard { layers: copied, symbols }; + Ok(json!({"copied": n, "layers": layers})) } fn cut(s: &mut Session, p: &Value) -> Result { copy(s, p)?; - crate::cmds_draw::delete(s, p)?; - Ok(json!({"cut": s.clipboard.elements.len()})) + crate::cmds_draw::delete_selection(s, p)?; + Ok(json!({"cut": s.clipboard.len()})) } fn clipboard_bounds(s: &Session) -> Rect { - s.clipboard.elements.iter().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e))) + s.clipboard.elements().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e))) } fn clip_element_bounds(s: &Session, e: &Element) -> Rect { @@ -109,27 +135,103 @@ fn clip_element_bounds(s: &Session, e: &Element) -> Rect { e.bounds(&doc) } +/// The layers a paste puts each copied layer's artwork on (ADR 0044). One copied layer goes on +/// the active layer. Several go back on the layers they came from when every one of them is in +/// this scene (same id and name) and can be drawn on; else on the active layer and the drawable +/// layers below it, in order, with missing layers created at the bottom named after the copied +/// ones, as Paste Frames does. +fn paste_targets(s: &mut Session) -> Result> { + let n = s.clipboard.layers.len(); + if n <= 1 { + return Ok(vec![s.layer]); + } + let tl = s.doc.timeline(s.scene); + let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature); + let home: Vec = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect(); + if home.len() == n { + return Ok(home); + } + let at = s.active_layer_index().unwrap_or(0); + let mut out = vec![s.layer]; + out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1)); + let names: Vec = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect(); + for name in names { + if s.doc.timeline(s.scene).layers.len() >= 1000 { + return Err(EngineError::State("too many layers (limit 1000)".into())); + } + let id = LayerId(s.doc.alloc_id()); + let count = s.doc.timeline(s.scene).layers.len(); + let mut layer = Layer::new(id, name); + if let Some(k) = layer.keyframe_mut(0) { + k.duration = s.frame_count().max(1); + } + layer.color = crate::cmds_timeline::layer_color(count + 1); + let tl = s.doc.timeline_mut(s.scene); + tl.layers.push(Arc::new(layer)); + tl.repair_masks(); + out.push(id); + } + Ok(out) +} + 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 targets = paste_targets(s)?; + let copied = s.clipboard.layers.clone(); + let mut sel = crate::Selection::default(); + let mut all = Vec::new(); + let mut merged = false; + for (c, &layer) in copied.iter().zip(&targets) { + let (fresh, m) = s.with_layer(layer, |s| paste_layer(s, &c.elements, offset))?; + merged |= m; + all.extend(fresh.iter().map(|e| e.0)); + sel.extend_on(layer, fresh); + } + s.selection = sel; + if let Some(&first) = targets.first() + && targets.len() > 1 + { + s.layer = first; + } + let mut v = json!({"pasted": all, "merged": merged}); + if targets.len() > 1 { + v["layers"] = json!(targets.iter().map(|l| l.0).collect::>()); + } + Ok(v) +} + +/// Pastes `elements` moved by `offset` into the active layer's keyframe at the playhead; their +/// new ids, and whether raw shapes merged. +fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec, bool)> { let mut fresh = Vec::new(); let mut out = Vec::new(); - for e in s.clipboard.elements.clone() { + let mut raw = Vec::new(); + for e in elements.iter().cloned() { 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)); + // Raw shapes go into the drawing where they land, cutting and joining what they touch + // (ADR 0042); objects go on top. + if crate::merge::mergeable(&e).is_some() { + raw.push(e); + } else { + fresh.push(e.id); + out.push(Arc::new(e)); + } } let kf = s.editable_keyframe()?; - if kf.elements.len() + out.len() > 100_000 { + if kf.elements.len() + out.len() + raw.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::>()})) + let merged = !raw.is_empty(); + if merged { + fresh.extend(crate::merge::merge_in(s, raw)?); + } + Ok((fresh, merged)) } /// Adds the symbols this document lacks (from a clipboard, maybe another document's) and @@ -207,6 +309,7 @@ fn remove_transform(s: &mut Session, _: &Value) -> Result { Ok(json!({"reset": n})) } +/// `m` about the centre of the whole selection's bounds, on every layer it is on. fn about_center(s: &mut Session, m: Affine) -> Result { let b = s.selection_bounds(); if b.is_empty() { @@ -214,8 +317,7 @@ fn about_center(s: &mut Session, m: Affine) -> Result { } 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})) + s.each_layer(true, |s| Ok(json!({"transformed": apply(s, &full)?}))) } // ----- align ------------------------------------------------------------------------------------ @@ -230,7 +332,10 @@ enum Edge { Bottom, } -fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(ElementId, Vec2)> { +/// A selected element: its layer and id. +type Item = (LayerId, ElementId); + +fn moves_for(bounds: &[(Item, Rect)], target: Rect, edge: Edge) -> Vec<(Item, Vec2)> { bounds .iter() .map(|(id, b)| { @@ -247,23 +352,38 @@ fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(Ele .collect() } -fn translate_each(s: &mut Session, moves: &[(ElementId, Vec2)]) -> Result { - let kf = s.editable_keyframe()?; +/// Moves each element by its own amount, on its own layer. +fn translate_each(s: &mut Session, moves: &[(Item, Vec2)]) -> Result { + let mut layers: Vec = Vec::new(); + for ((l, _), _) in moves { + if !layers.contains(l) { + layers.push(*l); + } + } 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; + for layer in layers { + let mine: Vec<(ElementId, Vec2)> = moves.iter().filter(|((l, _), d)| *l == layer && (d.x != 0.0 || d.y != 0.0)).map(|((_, id), d)| (*id, *d)).collect(); + if mine.is_empty() { + continue; // untouched layers stay shared with the undo snapshot } + n += s.with_layer(layer, |s| -> Result { + let kf = s.editable_keyframe()?; + let mut n = 0; + for (id, d) in &mine { + 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) + })?; } 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() +/// Each selected element's bounds, over every layer: alignment works across layers. +fn selected_bounds(s: &Session) -> Vec<(Item, Rect)> { + s.selected_elements().iter().map(|(l, e)| ((*l, e.id), s.element_bounds_on(*l, e.id))).filter(|(_, b)| !b.is_empty()).collect() } fn align(s: &mut Session, p: &Value, edge: Edge) -> Result { @@ -293,7 +413,7 @@ fn distribute(s: &mut Session, horizontal: bool) -> Result { 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 + let moves: Vec<(Item, Vec2)> = bounds .iter() .enumerate() .map(|(i, (id, b))| { diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 3b864a9f..0893d409 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -6,11 +6,16 @@ //! [`begin_edit`] swaps the target for how it looks at the playhead, and after the command //! [`finish_edit`] turns whatever changed in its transform or colour effect into property keys //! and puts the base object back (with any other change, a new fill say, kept). +//! +//! On a motion path, moving the object at a frame pins the path there (ADR 0049): the anchor +//! pinned to that frame moves (an end, at the first or last position key), or a new anchor is +//! added where the object is, pinned to the frame, and moved; after the last position key the +//! path carries on to where the object was put. use crate::cmds_timeline::target; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Property, Props}; +use anicraft_doc::{ColorEffect, Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -21,7 +26,7 @@ pub fn specs() -> Vec { c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|tint, value (px, %, °), frame?, layer?}", true, set_key as crate::RunFn), c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property), frame?, layer?}", true, remove_key), c("motion.set_ease", "Property Ease", "", None, "{easing, property? (default: every property), frame? (inside the segment), layer?}", true, set_ease), - c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path and where the object is", false, info), + c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is", false, info), c("motion.set_path", "Edit Motion Path", "", None, "{d: SVG path data in stage space (its first subpath; ends are the start and end positions), layer?, frame?}", true, set_path), c("motion.clear_path", "Remove Motion Path", "", None, "{layer?, frame?}: back to the straight path the X/Y curves trace", true, clear_path), c("motion.orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}: turn the object as its motion path turns", true, orient), @@ -29,6 +34,8 @@ pub fn specs() -> Vec { c("motion.delete_points", "Delete Motion Path Points", "", None, "{anchors: [index, ..] (as motion.info lists them; the ends stay), layer?, frame?}: the path refits through the rest", true, delete_points), c("motion.convert_point", "Convert Motion Path Point", "", None, "{anchor, smooth: bool, layer?, frame?}: smooth (handles in line) or corner (handles on the anchor)", true, convert_point), c("motion.move_path", "Move Motion Path", "", None, "{dx, dy, layer?, frame?}: the whole path with its object, keeping the timing", true, move_path), + c("motion.pin_point", "Pin Motion Path Point", "", None, "{anchor? (default: a new anchor where the object is), frame? (the frame to pin it to, between the first and last position keys), layer?}: the object passes the anchor exactly on that frame → {anchor, frame, pins}", true, pin_point), + c("motion.unpin_point", "Unpin Motion Path Point", "", None, "{anchor? | frame?, layer?}: the anchor shapes the path only again; the X/Y keys of its frame go → {anchor, frame, pins}", true, unpin_point), ] } @@ -132,19 +139,37 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { } } -/// Most bends [`move_on_path`] makes to land the object where it was put; each takes 15–35% -/// off the miss on typical paths (the path's length changes as it bends, sliding the object). +/// Most bends [`move_on_path`] makes to land the object where it was put off the path; each +/// takes 15–35% off the miss on typical paths (the path's length changes as it bends, sliding the +/// object). const BEND_STEPS: usize = 48; -/// The object on a motion path was moved by `d` at `offset`: at or before the first position -/// key the path's start moves, at or after the last its end, in between the path bends so it -/// passes where the object was put (a few bends, as the path's length changes with each); -/// without position keys the whole path moves. +/// The object on a motion path was moved by `d` at `offset` (ADR 0049): the anchor pinned to +/// that frame moves with it (before the first position key, the start); after the last position +/// key the path carries on to where it was put; in between, a new anchor where the object is gets +/// pinned to the frame and moved. Where the object is off the path (an overshooting ease) the +/// path bends instead (ADR 0030); without position keys the whole path moves. fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u32) { let Some(mut path) = m.path.clone() else { return }; - let f = offset as f32; match m.position_range() { - Some((f0, f1)) if f1 > f0 && offset > f0 && offset < f1 => { + Some((f0, f1)) if f1 > f0 => { + let pinned = m.pinned_anchors(base).into_iter().find(|p| p.frame == offset).map(|p| p.anchor as usize); + if let Some(a) = pinned.or((offset < f0).then_some(0)) { + m.move_anchor(a, d, base, last); + return; + } + if offset > f1 { + let end = anicraft_doc::motion::path_ends(&path).map(|(_, b)| b).unwrap_or_default(); + if !m.extend_to(offset, end + d, base) { + m.move_anchor(path.cmds.len().saturating_sub(1), d, base, last); + } + return; + } + if let Ok(a) = m.pin_here(offset, base) { + m.move_anchor(a, d, base, last); + return; + } + let f = offset as f32; let Some(target) = m.on_path(base).map(|op| op.point(f) + d) else { return }; let mut trial = m.clone(); for _ in 0..BEND_STEPS { @@ -160,10 +185,6 @@ fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u trial.path = Some(path.clone()); } } - Some((f0, f1)) if f1 > f0 => { - let anchor = if offset <= f0 { 0 } else { path.cmds.len().saturating_sub(1) }; - path.move_anchor(anchor, d); - } _ => path = path.transformed(&Affine::translate(d.x, d.y)), } m.set_path(&path, base, last); @@ -182,7 +203,7 @@ fn set_path(s: &mut Session, p: &Value) -> Result { let path = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; if last == 0 && m.position_range().is_none_or(|(a, b)| a == b) { return Err(EngineError::State("a one-frame span has no room to move along a path: make the span longer first".into())); @@ -190,33 +211,61 @@ fn set_path(s: &mut Session, p: &Value) -> Result { if !m.set_path(&path, &base, last) { return Err(EngineError::Param("param 'd' needs a segment of some length, with finite points within ±1000000".into())); } - Ok(path_summary(m)) + Ok(path_summary(m, start, &base)) } -fn path_summary(m: &MotionTween) -> Value { - let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient}) }; +fn path_summary(m: &MotionTween, start: u32, base: &Props) -> Value { + let pins = pins_json(m, start, base); + let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient, "pins": pins}) }; let len = anicraft_geom::walk::CurveWalk::new(path).map_or(0.0, |w| w.length()); let (a, b) = anicraft_doc::motion::path_ends(path).unwrap_or_default(); // Anchor `i` is path command `i` (a motion path is a move and cubics). let anchors: Vec<[f32; 2]> = path.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect(); - json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient}) + json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient, "pins": pins}) +} + +/// The anchors tied to frames (ADR 0049), ends included: `{anchor, frame, end, at}`, frames +/// counted from the timeline's start. +fn pins_json(m: &MotionTween, start: u32, base: &Props) -> Value { + let path = m.path.clone().or_else(|| m.path_from_tracks(base)); + let pins = m.pinned_anchors(base); + let n = pins.len(); + let v: Vec = pins + .iter() + .enumerate() + .map(|(i, q)| { + let at = path.as_ref().and_then(|p| p.point(q.anchor as usize, anicraft_geom::edit::ANCHOR)).map(|v| json!([v.x, v.y])); + json!({"anchor": q.anchor, "frame": start + q.frame, "end": i == 0 || i + 1 == n, "at": at}) + }) + .collect(); + Value::Array(v) } /// Edits the motion path at the target frame with `edit`: the tween's own path, or the straight -/// one its X/Y curves trace (which the edit makes its own, as on the stage). The ends' keys stay -/// unless the edit moved an end, so the timing is kept. Returns what `edit` returned and the -/// path's summary. -fn edit_path(s: &mut Session, p: &Value, edit: impl FnOnce(&mut anicraft_geom::Path) -> Result) -> Result<(T, Value)> { +/// one its X/Y curves trace (which the edit makes its own, as on the stage, its position keys +/// pinned to their anchors). The ends' and pins' keys stay unless the edit moved their anchors, +/// so the timing is kept. Returns what `edit` returned and the path's summary. +fn edit_path(s: &mut Session, p: &Value, edit: impl FnOnce(&mut MotionTween) -> Result) -> Result<(T, Value)> { let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; - let mut path = m.path.clone().or_else(|| m.path_from_tracks(&base)).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?; - let out = edit(&mut path)?; + if m.path.is_none() { + let (path, pins) = m.path_and_pins_from_tracks(&base).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?; + m.path = Some(path); + m.pins = pins; + } + let out = edit(m)?; + let path = m.path.clone().ok_or_else(|| EngineError::State("the motion path went away".into()))?; if !m.set_path(&path, &base, last) { return Err(EngineError::State("that would leave the motion path with no length".into())); } - Ok((out, path_summary(m))) + Ok((out, path_summary(m, start, &base))) +} + +/// The motion path being edited (there is one inside [`edit_path`]). +fn path_mut(m: &mut MotionTween) -> Result<&mut anicraft_geom::Path> { + m.path.as_mut().ok_or_else(|| EngineError::State("no motion path here".into())) } /// An anchor index param, checked against the path. @@ -242,7 +291,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result { if !(0.0..=1000.0).contains(&slop) { return Err(EngineError::Param("param 'slop' must be between 0 and 1000".into())); } - let (anchor, mut v) = edit_path(s, p, |path| { + let (anchor, mut v) = edit_path(s, p, |m| { + let path = path_mut(m)?; if path.cmds.len() > anicraft_doc::motion::MAX_PATH_SEGMENTS { return Err(EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS))); } @@ -268,7 +318,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result { if !(1e-3..=1.0 - 1e-3).contains(&t) { return Err(EngineError::State("there is already an anchor there".into())); } - if !path.split_segment(cmd, t) { + // Pins after it stay on their anchors. + if !m.split_path(cmd, t) { return Err(EngineError::State("cannot add a point there".into())); } // The new anchor ends the first half. @@ -283,8 +334,8 @@ fn delete_points(s: &mut Session, p: &Value) -> Result { if wanted.is_empty() { return Err(EngineError::Param("param 'anchors' lists no anchor".into())); } - let ((deleted, kept_ends), mut v) = edit_path(s, p, |path| { - let n = path.cmds.len(); + let ((deleted, kept_ends, unpinned), mut v) = edit_path(s, p, |m| { + let n = path_mut(m)?.cmds.len(); let mut set = std::collections::BTreeSet::new(); for &i in wanted.iter().take(100_000) { match usize::try_from(i).ok().filter(|i| *i < n) { @@ -296,23 +347,28 @@ fn delete_points(s: &mut Session, p: &Value) -> Result { if set.is_empty() { return Err(EngineError::State("the ends of a motion path can't be deleted: they are where the motion starts and ends. Drag them to move them, or Straighten the path".into())); } - // Last first, so the indices still to go stay where they were. - let mut deleted = 0; + // Last first, so the indices still to go stay where they were. A pinned anchor's pin + // goes with it (and its X/Y keys). + let (mut deleted, mut unpinned) = (0, 0); for i in set.into_iter().rev() { - if path.merge_at(i) { + let pinned = m.live_pins().iter().any(|q| q.anchor as usize == i); + if m.delete_anchor(i) { deleted += 1; + unpinned += usize::from(pinned); } } - Ok((deleted, ends)) + Ok((deleted, ends, unpinned)) })?; v["deleted"] = json!(deleted); v["kept_ends"] = json!(kept_ends); + v["unpinned"] = json!(unpinned); Ok(v) } fn convert_point(s: &mut Session, p: &Value) -> Result { let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required (true: smooth, false: corner)".into()))?; - let (changed, mut v) = edit_path(s, p, |path| { + let (changed, mut v) = edit_path(s, p, |m| { + let path = path_mut(m)?; let a = anchor_index(p, "anchor", path)?; Ok(if smooth { path.make_smooth(a) } else { path.make_corner(a) }) })?; @@ -326,6 +382,7 @@ fn move_path(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("params 'dx' and 'dy' must be finite".into())); } let (kf, _) = motion_span(s, p)?; + let start = kf.start; let i = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; if !m.translate(d) { @@ -337,7 +394,8 @@ fn move_path(s: &mut Session, p: &Value) -> Result { el.transform = Affine::translate(d.x, d.y).mul(&el.transform); *slot = Arc::new(el); } - let mut v = kf.motion.as_ref().map_or(Value::Null, path_summary); + let base = base_of(kf)?; + let mut v = kf.motion.as_ref().map_or(Value::Null, |m| path_summary(m, start, &base)); v["moved"] = json!([d.x, d.y]); Ok(v) } @@ -349,8 +407,10 @@ fn clear_path(s: &mut Session, p: &Value) -> Result { if m.path.take().is_none() { return Err(EngineError::State(format!("the motion tween at frame {} has no motion path to remove", frame + 1))); } - // Orient to path has nothing left to turn with. + // Orient to path has nothing left to turn with, and pins nothing to pin. Their keys stay: + // the straight path runs through them. m.orient = false; + m.pins.clear(); Ok(json!({"cleared": true})) } @@ -358,7 +418,7 @@ fn orient(s: &mut Session, p: &Value) -> Result { let on = opt_bool(p, "orient")?.ok_or_else(|| EngineError::Param("param 'orient' is required (true or false)".into()))?; let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; // The straight path the X/Y curves trace becomes the path to turn along. let mut created = false; @@ -367,11 +427,84 @@ fn orient(s: &mut Session, p: &Value) -> Result { created = m.set_path(&path, &base, last); } m.orient = on; - let mut v = path_summary(m); + let mut v = path_summary(m, start, &base); v["path_created"] = json!(created); Ok(v) } +/// Why a pin can't be made, in words an artist (or an agent) can act on. `start` is the span's +/// first frame (messages count frames from 1, as the timeline does). +fn pin_error(e: PinError, start: u32, frame: u32) -> EngineError { + let shown = |f: u32| start + f + 1; + match e { + PinError::NoPath => EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()), + PinError::NoAnchor => EngineError::Param("no such anchor on this motion path (motion.info lists them, from 0 at the start)".into()), + PinError::End => EngineError::State("the ends of a motion path are always pinned, to the first and last position keys: move the object on those frames to move them".into()), + PinError::Outside(f0, f1) => EngineError::State(format!("frame {} is outside the motion (frames {} to {}): move the object there to carry the path on", shown(frame), shown(f0), shown(f1))), + PinError::Order(q) => EngineError::State(format!("anchor {} is pinned to frame {}: pins keep the path's order, a later frame on a later anchor", q.anchor, shown(q.frame))), + PinError::OffPath => EngineError::State(format!("at frame {} the object is beyond an end of the path (its ease overshoots): pin an anchor of the path instead", shown(frame))), + PinError::Full => EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS)), + } +} + +/// A straight motion's path becomes the tween's own, its position keys pinned to its anchors +/// (nothing moves). +fn own_path(m: &mut MotionTween, base: &Props, last: u32) -> std::result::Result<(), PinError> { + if m.path.is_none() { + let (path, pins) = m.path_and_pins_from_tracks(base).ok_or(PinError::NoPath)?; + m.path = Some(path.clone()); + m.pins = pins; + m.set_path(&path, base, last); + } + Ok(()) +} + +fn pin_point(s: &mut Session, p: &Value) -> Result { + let anchor = opt_u64(p, "anchor")?.map(|a| usize::try_from(a).unwrap_or(usize::MAX)); + let (kf, offset) = motion_span(s, p)?; + let base = base_of(kf)?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?; + let a = match anchor { + Some(a) => m.pin(a, offset, &base).map(|_| a), + None => m.pin_here(offset, &base), + } + .map_err(|e| pin_error(e, start, offset))?; + let mut v = path_summary(m, start, &base); + v["anchor"] = json!(a); + v["frame"] = json!(start + offset); + Ok(v) +} + +fn unpin_point(s: &mut Session, p: &Value) -> Result { + let anchor = opt_u64(p, "anchor")?; + let (kf, offset) = motion_span(s, p)?; + let base = base_of(kf)?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?; + let all = m.pinned_anchors(&base); + let found: Option = match anchor { + Some(a) => all.iter().find(|q| u64::from(q.anchor) == a).copied(), + None => all.iter().find(|q| q.frame == offset).copied(), + }; + let Some(pin) = found else { + return Err(EngineError::State(match anchor { + Some(a) => format!("anchor {a} isn't pinned to a frame"), + None => format!("no anchor is pinned to frame {}", start + offset + 1), + })); + }; + if all.first() == Some(&pin) || all.last() == Some(&pin) { + return Err(pin_error(PinError::End, start, pin.frame)); + } + m.unpin(pin.frame); + let mut v = path_summary(m, start, &base); + v["anchor"] = json!(pin.anchor); + v["frame"] = json!(start + pin.frame); + Ok(v) +} + /// Insert Keyframe (F6) inside a motion tween: every property gets a key at `frame` holding its /// value there; the timeline is not split. Whether `frame` was in a motion tween. pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool { @@ -384,7 +517,13 @@ pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool { let Some(m) = kf.motion.as_mut() else { return false }; let Some(base) = m.target_index(&kf.elements).and_then(|t| kf.elements.get(t)).map(|e| Props::of(e)) else { return true }; let now = m.props_at(&base, offset as f32); + // On a motion path the frame's place is an anchor pinned to it (ADR 0049), where the + // object is: nothing moves on this frame. + let pinned = m.path.is_some() && m.pin_here(offset, &base).is_ok(); for p in Property::ALL { + if pinned && matches!(p, Property::X | Property::Y) { + continue; + } m.set_key(p, offset, now.get(p), base.get(p)); } true @@ -416,6 +555,9 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result { if layer.kind == LayerKind::Folder { return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into())); } + if layer.kind == LayerKind::Armature { + return Err(EngineError::State("an armature layer tweens its poses: add a pose at another frame and Create Classic Tween between them".into())); + } let k = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; if let Some(m) = &k.motion { return Ok(json!({"motion": k.start, "target": m.target.0, "frames": k.duration, "converted": false})); @@ -440,7 +582,7 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result { let name = format!("Tween {}", s.doc.library.len() + 1); s.layer = lid; s.frame = start; - s.selection = ids; + s.selection = crate::Selection::only(lid, ids); let r = crate::cmds_draw::convert_to_symbol(s, &json!({"name": name})); s.frame = frame; if layer != lid { @@ -502,8 +644,19 @@ fn set_key(s: &mut Session, p: &Value) -> Result { let (kf, offset) = motion_span(s, p)?; let base = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); let base = base.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; - let start = kf.start; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + // On a path, the X/Y keys of a pinned frame are its anchor's place: setting one moves the + // anchor (ADR 0049). + let pinned = matches!(prop, Property::X | Property::Y).then(|| m.pinned_anchors(&base).into_iter().find(|q| q.frame == offset)).flatten().filter(|_| m.path.is_some()); + if let Some(pin) = pinned { + let at = m.path.as_ref().and_then(|p| p.point(pin.anchor as usize, anicraft_geom::edit::ANCHOR)).unwrap_or_default(); + let d = if prop == Property::X { Vec2::new(value - at.x, 0.0) } else { Vec2::new(0.0, value - at.y) }; + if d != Vec2::ZERO && !m.move_anchor(pin.anchor as usize, d, &base, last) { + return Err(EngineError::Param(format!("{} must keep the motion path within ±1000000 px", prop.label()))); + } + return Ok(json!({"property": prop.key(), "frame": start + offset, "value": value, "anchor": pin.anchor})); + } m.set_key(prop, offset, value, base.get(prop)); Ok(json!({"property": prop.key(), "frame": start + offset, "value": value})) } @@ -513,11 +666,20 @@ fn remove_key(s: &mut Session, p: &Value) -> Result { let (kf, offset) = motion_span(s, p)?; let start = kf.start; let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; - let removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); + // Removing a pinned frame's X or Y key lets the pin go, with both keys (ADR 0049). + let pin = m.live_pins().into_iter().find(|q| q.frame == offset).filter(|_| only.is_none_or(|o| matches!(o, Property::X | Property::Y))); + let mut removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); + if pin.is_some() { + for k in [Property::X.key(), Property::Y.key()] { + if !removed.contains(&k) { + removed.push(k); + } + } + } if removed.is_empty() { return Err(EngineError::State(format!("there is no property keyframe at frame {}", start + offset + 1))); } - Ok(json!({"removed": removed, "frame": start + offset})) + Ok(json!({"removed": removed, "frame": start + offset, "unpinned": pin.map(|q| q.anchor)})) } fn set_ease(s: &mut Session, p: &Value) -> Result { @@ -558,8 +720,10 @@ fn info(s: &mut Session, p: &Value) -> Result { let values: serde_json::Map = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().to_string(), json!(n.get(*p))))).collect(); // Where the object is (on a motion path the X/Y values are its timing, not its place). let position = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| m.apply(e, (frame - kf.start) as f32).transform.translation()).map(|q| json!([q.x, q.y])); - let path = path_summary(m); + let path = m.path.as_ref().map(|p| p.to_svg()); // The anchors point edits address: the path's own, or the straight path's (ADR 0038). let anchors: Vec<[f32; 2]> = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).map(|p| p.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect()).unwrap_or_default(); - Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path["path"], "anchors": anchors, "orient": m.orient})) + // And those tied to frames, ends included (ADR 0049). + let pins = base.map_or(Value::Array(Vec::new()), |b| pins_json(m, kf.start, &b)); + Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path, "anchors": anchors, "pins": pins, "orient": m.orient})) } diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index a5ac6bbe..d878ed7d 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -30,10 +30,18 @@ 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?, profile?}", true, ink), + c( + "paint.bucket", + "Paint Bucket", + "", + None, + "{x, y, color?, gap? (stage units: how wide an opening still counts as closed), object?: bool} fills the closed area under the point, or recolours the fill there; unless `object` (default: the Object Drawing setting), the fill is raw and merges with the drawing (an area closed by raw lines and fills is filled exactly up to them)", + true, + bucket as crate::RunFn, + ), + c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?, profile?, cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing?} (the tool's line style unless given; see stroke.set_style)", true, ink), c("paint.pick", "Eyedropper", "", None, "{x, y, other?: bool (into the other swatch only: a fill's colour into the stroke, a line's into the fill), slop?} picks the style under the point on any visible layer into the tool settings: a fill's paint (solid, gradient or bitmap, kept where it is on the stage) into the fill swatch, a line's colour, width and profile into the stroke settings", false, pick_style), - c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, apply_style), + c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, |s, p| s.each_layer(false, |s| apply_style(s, p))), ] } @@ -76,16 +84,26 @@ fn bucket(s: &mut Session, p: &Value) -> Result { if !(0.0..=1000.0).contains(&gap) { return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into())); } + let object = crate::cmds_draw::object_param(s, p)?; let items = layer_items(s); - // 1. On a fill: recolour it. + // 1. On a fill: recolour it. A raw fill then joins the fills of its new colour it touches. if let Some((id, true)) = pick(&items, at, 0.0) { let to_local = items.iter().find(|i| i.element == id).and_then(|i| i.transform.inverse()).unwrap_or(Affine::IDENTITY); - element_shape_mut(s, id)?.fill = Some(paint.transformed(&to_local)); + let sh = element_shape_mut(s, id)?; + sh.fill = Some(paint.transformed(&to_local)); + if sh.merge { + crate::cmds_raw::remerge_in_place(s, &[id])?; + return Ok(json!({"recolored": id.0, "merged": true})); + } 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())); + // 2. Find the enclosed area: exactly, when raw lines and fills close it off (ADR 0042), + // else from the rasterized layer. + let exact = if object { None } else { crate::merge::enclosed_area(&s.visible_elements(), at) }; + let was_exact = exact.is_some(); + let path = match exact { + Some(p) => p, + None => enclosed_region(&items, at, gap)?.ok_or_else(|| 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)); @@ -95,8 +113,15 @@ fn bucket(s: &mut Session, p: &Value) -> Result { name: String::new(), transform: Affine::translate(c.x, c.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(paint.transformed(&Affine::translate(-c.x, -c.y))), stroke: None, fill_rule: FillRule::EvenOdd, merge: false }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(paint.transformed(&Affine::translate(-c.x, -c.y))), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }), }; + if !object { + // Raw: behind the drawing, so it takes only what is empty and joins the fills of its + // colour it meets; the lines that bound it stay on top. + let ids = crate::merge::merge_in_order(s, vec![el], crate::merge::Order::Behind)?; + s.selection.clear(); + return Ok(json!({"element": ids.first().map(|e| e.0), "elements": ids.iter().map(|e| e.0).collect::>(), "merged": true, "exact": was_exact})); + } let kf = s.editable_keyframe()?; if kf.elements.len() >= 100_000 { return Err(EngineError::State("too many elements on this keyframe".into())); @@ -289,7 +314,9 @@ fn ink(s: &mut Session, p: &Value) -> Result { Some(pr) => pr, None => s.style.profile(), }; - element_shape_mut(s, id)?.stroke = Some(Stroke::new(color, width).with_profile(profile)); + // The Ink Bottle carries the whole line: caps, joins and dashes too. + let line = opt_stroke_style(p, &s.style.line, width)?.unwrap_or_else(|| s.style.line.clone()); + element_shape_mut(s, id)?.stroke = Some(Stroke::new(color, width).with_profile(profile).with_style(line)); Ok(json!({"element": id.0})) } @@ -360,6 +387,8 @@ fn pick_style(s: &mut Session, p: &Value) -> Result { st.stroke = stroke.color; st.stroke_width = (stroke.width * scale).clamp(0.1, 1000.0); st.use_stroke = true; + // Caps, joins and dashes as drawn (dashes scale with the shape, like the width). + st.line = stroke.style.scaled(scale).sanitized(); let preset = anicraft_doc::ProfilePreset::ALL.into_iter().find(|pr| pr.profile() == stroke.profile); let profile = match preset { Some(pr) => { @@ -371,7 +400,7 @@ fn pick_style(s: &mut Session, p: &Value) -> Result { "custom" } }; - Ok(json!({"picked": "line", "into": "stroke", "color": stroke.color.to_hex(), "width": st.stroke_width, "profile": profile})) + Ok(json!({"picked": "line", "into": "stroke", "color": stroke.color.to_hex(), "width": st.stroke_width, "profile": profile, "cap": st.line.cap.key(), "join": st.line.join.key(), "style": st.line.dash_kind().key()})) } None => Err(EngineError::State("click a fill or a line to pick its colour".into())), } @@ -387,7 +416,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { } let style = s.style.clone(); let paint = style.fill_paint(); - let line = Stroke::new(style.stroke, style.stroke_width).with_profile(style.profile()); + let line = style.new_stroke(style.stroke, style.stroke_width); let mut changed = 0; for e in s.selected_elements_mut()? { let to_local = e.transform.inverse(); diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 3230f7c0..dc4d70c4 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -31,7 +31,7 @@ const MAX_ELEMENTS: usize = 10_000; /// a namespace this list doesn't know is refused until someone decides (a test checks that /// every registered namespace is known). pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { - const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "script"]; + const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames"]; match id { "edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"), "edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" => { @@ -90,7 +90,7 @@ fn document_view(s: &Session) -> Value { "frames": s.frame_count(), "layer": s.layer.0, "layers": layers, - "selection": s.selection.iter().map(|e| e.0).collect::>(), + "selection": s.selection.id_list(), }) } @@ -116,7 +116,7 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result *e = e.union(&r); } let mut out = Vec::new(); - for e in s.visible_elements().iter().filter(|e| !only_selected || s.selection.contains(&e.id)) { + for e in s.visible_elements().iter().filter(|e| !only_selected || s.selection.contains(s.layer, e.id)) { if out.len() >= MAX_ELEMENTS { break; } @@ -124,7 +124,7 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result let mut v = json!({ "id": e.id.0, "name": e.name, - "selected": s.selection.contains(&e.id), + "selected": s.selection.contains(s.layer, e.id), "transform": e.transform.m, "bounds": if b.is_empty() { Value::Null } else { json!([b.min.x, b.min.y, b.max.x - b.min.x, b.max.y - b.min.y]) }, "alpha": e.color.alpha, diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs new file mode 100644 index 00000000..7b122f1b --- /dev/null +++ b/crates/engine/src/cmds_raw.rs @@ -0,0 +1,676 @@ +//! The Selection tool on raw shapes (ADR 0041; issue #42 §2 and §4): bending an edge by dragging +//! it, moving a corner or an end together with every raw shape that shares it, snapping what is +//! dragged to points, lines and fill edges, and a marquee that selects the parts of fills and +//! strokes under it. +//! +//! Positions and moves are in stage space. A layer's merged drawing stores a shared edge or +//! point once in each shape that has it, so every edit here changes all the copies alike and +//! then merges the shapes again (ADR 0031), unless asked not to while a drag is still going. + +use crate::cmds_draw::MAX_EXTENT; +use crate::merge::{self, Part, mergeable, reach}; +use crate::params::*; +use crate::{CommandSpec, CutOrigin, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId}; +use anicraft_geom::planar::SNAP; +use anicraft_geom::raw::{self as rawgeom, Cubic}; +use anicraft_geom::walk::cubic_point; +use anicraft_geom::{Path, PathCmd, Rect, Vec2}; +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( + "path.bend_segment", + "Bend Segment", + "", + None, + "{x, y, dx, dy, id?, cmd?, t?, slop?, merge?: bool} the segment at (x, y) (of shape `id`, else the one there) bends so that point moves by (dx, dy), its ends staying; a raw shape's copies of the edge bend with it and merge again (unless merge is false)", + true, + bend_segment as crate::RunFn, + ), + c( + "raw.move_point", + "Move Point", + "", + None, + "{x, y, to_x, to_y, with?: [[x, y], ..], points?: [[id, cmd], ..], snap?, slop?, merge?: bool} moves the corner or end at (x, y), with every raw shape that shares it, to (to_x, to_y), snapped within `snap` to points, lines and fill edges (while Snap to Objects is on); the anchors at `with` move by as much; returns the points to pass on while a drag goes on", + true, + move_point, + ), + c( + "raw.select_rect", + "Select Parts", + "", + None, + "{x0, y0, x1, y1, add?: bool} the marquee, on every visible, unlocked layer: the parts of raw fills and strokes under the rectangle (cut at its edges, per layer) and the objects wholly inside it", + true, + select_rect, + ), + c("raw.merge", "Merge Shapes", "", None, "{ids?: [..]} the raw shapes (default: the selection) merge again with the raw shapes they touch, in place", true, merge_cmd), + c("raw.hit", "Selection Tool Target", "", None, "{x, y, slop?, point_slop?} what a Selection-tool drag from (x, y) takes: a point, a segment to bend, a fill, or an object", false, hit), + ] +} + +/// Most points one move takes along. +const MAX_POINTS: usize = 10_000; +/// Most anchors and segments looked at when snapping. +const MAX_TARGETS: usize = 50_000; + +// ----- what the Selection tool takes ----------------------------------------------------------- + +/// What a Selection-tool drag starting at a point takes (Animate's corner and curve cursors). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Grab { + /// A corner or end that raw shapes share: the drag moves it. + Point { at: Vec2 }, + /// A raw stroke segment or fill edge, at parameter `t` of command `cmd`: the drag bends it. + Segment { id: ElementId, cmd: usize, t: f32, at: Vec2 }, + /// The inside of an unselected raw fill: the drag selects and moves it. + Fill { id: ElementId }, + /// Anything else (an object, or something selected): the drag moves the selection. + Object { id: ElementId }, +} + +impl Grab { + pub fn key(&self) -> &'static str { + match self { + Grab::Point { .. } => "point", + Grab::Segment { .. } => "segment", + Grab::Fill { .. } => "fill", + Grab::Object { .. } => "object", + } + } +} + +/// A raw shape's anchors in stage space. +fn stage_anchors(e: &Element) -> Vec<(usize, Vec2)> { + match mergeable(e) { + Some(sh) => sh.path.editable_anchors().into_iter().map(|(i, p)| (i, e.transform.apply(p))).collect(), + None => Vec::new(), + } +} + +impl Session { + /// What a Selection-tool drag from `p` takes: a shared point within `point_slop`, a segment + /// within `slop`, the inside of a fill, or the object there. Raw shapes that are selected + /// count as objects (a drag moves the selection). `None` over empty space. + pub fn raw_grab(&self, p: Vec2, slop: f32, point_slop: f32) -> Option<(LayerId, Grab)> { + let (layer, id) = self.hit_test(p, slop)?; + let object = Some((layer, Grab::Object { id })); + if self.selection.contains(layer, id) { + return object; + } + let els = self.elements_on(layer); + let el = els.iter().find(|e| e.id == id)?; + let Some(sh) = mergeable(el) else { return object }; + // A corner or end there, of any raw shape on the layer. + let mut best: Option<(f32, Vec2)> = None; + for e in els.iter().filter(|e| mergeable(e).is_some_and(|x| reach(x, &e.transform).inflate(point_slop).contains(p))) { + for (_, q) in stage_anchors(e) { + let d = q.distance(p); + if d <= point_slop && best.is_none_or(|b| d < b.0) { + best = Some((d, q)); + } + } + } + if let Some((_, at)) = best { + return Some((layer, Grab::Point { at })); + } + // The edge of a fill bends; its inside moves. + if sh.fill.is_some() && sh.path.distance_to_edge(p, &el.transform) > slop { + return Some((layer, Grab::Fill { id })); + } + let (cmd, t, _) = sh.path.nearest_segment(p, &el.transform)?; + let at = sh.path.segment_point(cmd, t).map(|q| el.transform.apply(q))?; + Some((layer, Grab::Segment { id, cmd, t, at })) + } +} + +fn hit(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(2.0).clamp(0.0, 100.0); + let point_slop = opt_f32(p, "point_slop")?.unwrap_or(slop * 1.5).clamp(0.0, 100.0); + Ok(match s.raw_grab(at, slop, point_slop) { + None => json!({"kind": null}), + Some((layer, g)) => { + let mut v = json!({"kind": g.key(), "layer": layer.0}); + match g { + Grab::Point { at } => { + v["x"] = json!(at.x); + v["y"] = json!(at.y); + } + Grab::Segment { id, cmd, t, at } => { + v["id"] = json!(id.0); + v["cmd"] = json!(cmd); + v["t"] = json!(t); + v["x"] = json!(at.x); + v["y"] = json!(at.y); + } + Grab::Fill { id } | Grab::Object { id } => v["id"] = json!(id.0), + } + v + } + }) +} + +/// Makes the layer of what is at `at` (within `slop`) the active one, as a click does. +fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) { + if let Some((layer, _)) = s.hit_test(at, slop) + && layer != s.layer + { + s.layer = layer; + s.selection.clear(); + } +} + +pub(crate) fn check_extent(path: &Path) -> Result<()> { + let b = path.bounds(); + if b.is_empty() { + return Ok(()); + } + if !(b.min.is_finite() && b.max.is_finite()) || b.width() > MAX_EXTENT || b.height() > MAX_EXTENT || b.min.x.abs().max(b.min.y.abs()).max(b.max.x.abs()).max(b.max.y.abs()) > MAX_EXTENT { + return Err(EngineError::Param("that would make the shape too large".into())); + } + Ok(()) +} + +// ----- bending ---------------------------------------------------------------------------------- + +fn bend_segment(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); + let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0); + let merge_after = opt_bool(p, "merge")?.unwrap_or(true); + // The shape: `id`, else the one under the point (its layer becomes the active one). + let id = match opt_u64(p, "id")? { + Some(i) => ElementId(i), + None => { + activate_layer_at(s, at, slop); + s.hit_test(at, slop).map(|(_, e)| e).ok_or_else(|| EngineError::State("no shape there".into()))? + } + }; + let els = s.visible_elements(); + let el = els.iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?; + let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("only shapes have segments to bend".into())) }; + let m = el.transform; + let mut path = (*sh.path).clone(); + path.close_explicitly(); + let (cmd, t) = match opt_u64(p, "cmd")? { + Some(c) => (usize::try_from(c).unwrap_or(usize::MAX), opt_f32(p, "t")?.ok_or_else(|| EngineError::Param("param 't' is required with 'cmd'".into()))?.clamp(0.0, 1.0)), + None => { + let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the shape has no segments".into()))?; + if dist > slop { + return Err(EngineError::State("no segment there".into())); + } + (cmd, t) + } + }; + let old = rawgeom::segment_cubic(&path, cmd).map(|c| rawgeom::transform(&c, &m)).ok_or_else(|| EngineError::Param(format!("no segment {cmd} on this shape")))?; + let new = rawgeom::bend(&old, t, d).ok_or_else(|| EngineError::Param("cannot bend that segment".into()))?; + let raw = mergeable(el).is_some(); + let changed = edit_edge(s, id, cmd, &old, &new, raw)?; + let point = cubic_point(&new, t.clamp(0.02, 0.98)); + if raw && merge_after { + remerge_in_place(s, &changed)?; + } + Ok(json!({"id": id.0, "cmd": cmd, "t": t, "x": point.x, "y": point.y, "changed": changed.iter().map(|e| e.0).collect::>(), "merged": raw && merge_after})) +} + +/// Replaces segment `cmd` of shape `id` (stage space: `old`) with `new` (same ends). When `raw`, +/// every raw shape's copy of the edge changes alike (a fill and its outline, two fills that +/// meet there); an object only changes itself. Returns the shapes that changed. +pub(crate) fn edit_edge(s: &mut Session, id: ElementId, cmd: usize, old: &Cubic, new: &Cubic, raw: bool) -> Result> { + let area = new.iter().chain(old).fold(Rect::EMPTY, |mut r, q| { + r.include(*q); + r + }); + let kf = s.editable_keyframe()?; + let mut changed = Vec::new(); + for e in kf.elements.iter_mut() { + let target = e.id == id; + if !target && !(raw && mergeable(e).is_some_and(|x| !reach(x, &e.transform).intersect(&area).is_empty())) { + continue; + } + let (Some(inv), ElementKind::Shape(x)) = (e.transform.inverse(), &e.kind) else { continue }; + let (ol, nl) = (rawgeom::transform(old, &inv), rawgeom::transform(new, &inv)); + let mut edited = (*x.path).clone(); + let n = if target { + edited.close_explicitly(); + let end = edited.point(cmd, anicraft_geom::edit::ANCHOR); + match (edited.cmds.get_mut(cmd), end) { + (Some(c), Some(end)) => { + *c = PathCmd::CubicTo(nl[1], nl[2], end); + 1 + } + _ => 0, + } + } else { + rawgeom::follow(&mut edited, &ol, &nl, SNAP / e.transform.mean_scale().max(1e-6)) + }; + if n == 0 { + continue; + } + check_extent(&edited)?; + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(edited); + } + changed.push(e.id); + } + Ok(changed) +} + +// ----- moving shared points --------------------------------------------------------------------- + +fn points_param(p: &Value) -> Result>> { + let Some(v) = p.get("points").filter(|v| !v.is_null()) else { return Ok(None) }; + let bad = || EngineError::Param("param 'points' must be a list of [id, cmd] pairs".into()); + let list = v.as_array().ok_or_else(bad)?; + if list.len() > MAX_POINTS { + return Err(EngineError::Param(format!("param 'points' has more than {MAX_POINTS} points"))); + } + let mut out = Vec::with_capacity(list.len()); + for pair in list { + let pair = pair.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?; + let id = pair.first().and_then(Value::as_u64).ok_or_else(bad)?; + let cmd = pair.get(1).and_then(Value::as_u64).ok_or_else(bad)?; + out.push((ElementId(id), usize::try_from(cmd).unwrap_or(usize::MAX))); + } + if out.is_empty() { + return Err(EngineError::Param("param 'points' is empty".into())); + } + Ok(Some(out)) +} + +/// A list of `[x, y]` stage positions (empty when absent). +pub(crate) fn positions_param(p: &Value, key: &str) -> Result> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + let bad = || EngineError::Param(format!("param '{key}' must be a list of [x, y] pairs")); + let list = v.as_array().ok_or_else(bad)?; + if list.len() > MAX_POINTS { + return Err(EngineError::Param(format!("param '{key}' has more than {MAX_POINTS} points"))); + } + list.iter() + .map(|xy| { + let xy = xy.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() +} + +/// Every raw shape's anchor at `at` (within [`SNAP`]) on the editable keyframe; shapes whose edge +/// passes there get an anchor there first. +fn shared_points(s: &mut Session, at: Vec2) -> Result> { + let kf = s.editable_keyframe()?; + let mut out = Vec::new(); + for e in kf.elements.iter_mut() { + let Some(sh) = mergeable(e) else { continue }; + if !reach(sh, &e.transform).contains(at) { + continue; + } + let Some(inv) = e.transform.inverse() else { continue }; + let mut path = (*sh.path).clone(); + let len = path.cmds.len(); + let cmds = rawgeom::anchors_at(&mut path, inv.apply(at), SNAP / e.transform.mean_scale().max(1e-6)); + if path.cmds.len() != len + && let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind + { + x.path = Arc::new(path); + } + out.extend(cmds.into_iter().map(|c| (e.id, c))); + if out.len() > MAX_POINTS { + return Err(EngineError::State("too many shapes meet there".into())); + } + } + Ok(out) +} + +fn move_point(s: &mut Session, p: &Value) -> Result { + let from = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let to = Vec2::new(f32_req(p, "to_x")?, f32_req(p, "to_y")?); + let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0)); + let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0); + let merge_after = opt_bool(p, "merge")?.unwrap_or(true); + let points = match points_param(p)? { + Some(points) => points, + None => { + activate_layer_at(s, from, slop); + // The nearest corner or end of a raw shape, then everything that shares it. + let els = s.visible_elements(); + let at = els.iter().flat_map(|e| stage_anchors(e)).map(|(_, q)| q).filter(|q| q.distance(from) <= slop).min_by(|a, b| a.distance(from).total_cmp(&b.distance(from))); + let at = at.ok_or_else(|| EngineError::State("no corner or end of a raw shape there".into()))?; + let mut points = shared_points(s, at)?; + // Other selected anchors (the Subselection tool) move by as much. + for w in positions_param(p, "with")? { + for pt in shared_points(s, w)? { + if !points.contains(&pt) { + points.push(pt); + } + } + if points.len() > MAX_POINTS { + return Err(EngineError::State("too many points to move at once".into())); + } + } + points + } + }; + let els = s.visible_elements(); + let find = |id: ElementId| els.iter().find(|e| e.id == id); + let &(id0, cmd0) = points.first().ok_or_else(|| EngineError::State("no point there".into()))?; + let cur = find(id0).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => sh.path.point(cmd0, anicraft_geom::edit::ANCHOR).map(|q| e.transform.apply(q)), + _ => None, + }); + let cur = cur.ok_or_else(|| EngineError::Param(format!("no point ({}, {cmd0}) on the active layer", id0.0)))?; + let snapped = if radius > 0.0 { snap_point(&els, to, radius, &points) } else { None }; + let target = snapped.map_or(to, |(q, _)| q); + let d = target - cur; + let kf = s.editable_keyframe()?; + let mut moved: BTreeSet = BTreeSet::new(); + for e in kf.elements.iter_mut() { + let cmds: Vec = points.iter().filter(|(id, _)| *id == e.id).map(|(_, c)| *c).collect(); + if cmds.is_empty() { + continue; + } + let (Some(inv), ElementKind::Shape(sh)) = (e.transform.inverse(), &e.kind) else { continue }; + let local = inv.apply_vector(d); + let mut path = (*sh.path).clone(); + for cmd in cmds { + if !path.move_anchor(cmd, local) && local.length() > 0.0 { + return Err(EngineError::Param(format!("no point ({}, {cmd}) to move", e.id.0))); + } + } + check_extent(&path)?; + if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind { + sh.path = Arc::new(path); + } + moved.insert(e.id); + } + if points.iter().any(|(id, _)| !moved.contains(id)) { + return Err(EngineError::Param("a point to move is not on the active layer at this frame".into())); + } + let ids: Vec = moved.into_iter().collect(); + if merge_after { + remerge_in_place(s, &ids)?; + } + Ok(json!({ + "x": target.x, "y": target.y, + "snapped": snapped.map(|(q, kind)| json!({"x": q.x, "y": q.y, "to": kind.key()})), + "points": if merge_after { json!([]) } else { json!(points.iter().map(|(id, c)| [id.0, *c as u64]).collect::>()) }, + "moved": ids.len(), + "merged": merge_after, + })) +} + +// ----- snapping --------------------------------------------------------------------------------- + +/// What a dragged point snapped to. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum SnapTo { + /// An anchor (corner or end). + Point, + /// A stroke or a fill's edge. + Line, +} + +impl SnapTo { + pub fn key(&self) -> &'static str { + match self { + SnapTo::Point => "point", + SnapTo::Line => "line", + } + } +} + +/// Anchors and segments to snap to, in stage space. +#[derive(Default)] +struct Targets { + points: Vec, + segs: Vec, +} + +/// The shapes' anchors and segments, leaving out the anchors `skip_point(id, cmd)` and the +/// segments `skip_seg(id, cmd)` says move along. +fn targets(els: &[Arc], skip_el: impl Fn(ElementId) -> bool, skip_point: impl Fn(ElementId, usize) -> bool, skip_seg: impl Fn(ElementId, usize) -> bool) -> Targets { + let mut t = Targets::default(); + for e in els.iter().filter(|e| !skip_el(e.id)) { + let ElementKind::Shape(sh) = &e.kind else { continue }; + if t.points.len() + t.segs.len() > MAX_TARGETS { + break; + } + let mut path = (*sh.path).clone(); + path.close_explicitly(); + for (i, q) in path.editable_anchors() { + if !skip_point(e.id, i) { + t.points.push(e.transform.apply(q)); + } + } + for k in 0..path.cmds.len().min(MAX_TARGETS) { + if !skip_seg(e.id, k) + && let Some(c) = rawgeom::segment_cubic(&path, k) + { + t.segs.push(rawgeom::transform(&c, &e.transform)); + } + } + } + t +} + +/// The nearest anchor within `radius` of `p`, else the nearest point on a segment. +fn snap_to(t: &Targets, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo, f32)> { + let point = t.points.iter().map(|q| (*q, q.distance(p))).filter(|(_, d)| *d <= radius).min_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((q, d)) = point { + return Some((q, SnapTo::Point, d)); + } + let near = |c: &Cubic| { + let (lo, hi) = c.iter().fold((Vec2::new(f32::INFINITY, f32::INFINITY), Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY)), |(lo, hi), q| (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y)))); + p.x >= lo.x - radius && p.x <= hi.x + radius && p.y >= lo.y - radius && p.y <= hi.y + radius + }; + t.segs + .iter() + .filter(|c| near(c)) + .map(|c| { + let (u, d) = rawgeom::nearest(c, p); + (cubic_point(c, u), d) + }) + .filter(|(_, d)| *d <= radius) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(q, d)| (q, SnapTo::Line, d)) +} + +/// Where a point being moved (`moving`: the anchors that go with it) snaps near `to`. +fn snap_point(els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, usize)]) -> Option<(Vec2, SnapTo)> { + // The segments leaving the moving anchors move too. + let mut segs: BTreeSet<(ElementId, usize)> = BTreeSet::new(); + for e in els { + let ElementKind::Shape(sh) = &e.kind else { continue }; + for (_, cmd) in moving.iter().filter(|(id, _)| *id == e.id) { + let (i, o) = sh.path.anchor_segments(*cmd); + segs.extend(i.into_iter().chain(o).map(|k| (e.id, k))); + } + } + let t = targets(els, |_| false, |id, c| moving.contains(&(id, c)), |id, k| segs.contains(&(id, k))); + snap_to(&t, to, radius).map(|(q, k, _)| (q, k)) +} + +/// After the selection moved: the extra move that snaps one of its anchors (the nearest to +/// `from` when given, else whichever comes closest) onto an anchor or line of the shapes that +/// did not move, within `radius`. +pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Option<(Vec2, Vec2, SnapTo)> { + let mut own: Vec = Vec::new(); + for (_, e) in s.selected_elements() { + if let ElementKind::Shape(sh) = &e.kind { + own.extend(sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q))); + } + if own.len() > 4 * MAX_POINTS { + break; + } + } + let candidates: Vec = match from { + Some(f) => own.iter().copied().min_by(|a, b| a.distance(f).total_cmp(&b.distance(f))).into_iter().collect(), + None => own.into_iter().take(512).collect(), + }; + if candidates.is_empty() { + return None; + } + // What stays put on the layers the selection is on (ADR 0044). + let rest: Vec> = s.selected_layers().into_iter().flat_map(|l| s.elements_on(l).into_iter().filter(move |e| !s.selection.contains(l, e.id))).collect(); + let t = targets(&rest, |_| false, |_, _| false, |_, _| false); + candidates + .into_iter() + .filter_map(|c| snap_to(&t, c, radius).map(|(q, k, d)| (c, q, k, d))) + .min_by(|a, b| a.3.total_cmp(&b.3)) + .map(|(c, q, k, _)| (q - c, q, k)) +} + +// ----- the marquee ------------------------------------------------------------------------------ + +fn contains(outer: &Rect, inner: &Rect) -> bool { + inner.min.x >= outer.min.x && inner.min.y >= outer.min.y && inner.max.x <= outer.max.x && inner.max.y <= outer.max.y +} + +/// Whether the playhead is on a keyframe whose artwork can be cut here (not inside a tween, where +/// an edit would add a keyframe). +fn on_editable_key(s: &Session) -> bool { + s.active_layer().and_then(|l| l.keyframe_at(s.frame)).is_some_and(|k| k.motion.is_none() && (k.tween.is_none() || k.start == s.frame)) +} + +/// The marquee (ADR 0041, 0044): on every visible, unlocked layer, the parts of raw shapes under +/// the rectangle (cut at its edges) and the objects wholly inside it. +fn select_rect(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")?); + let add = opt_bool(p, "add")?.unwrap_or(false); + let r = Rect::from_points(a, b); + if !add { + s.selection.clear(); + } + if r.width() <= 0.0 || r.height() <= 0.0 { + return Ok(json!({"selected": s.selection.id_list(), "cut": 0})); + } + // What each layer has under the marquee, from one display list: wholly inside, or (raw + // shapes) partly. + let mut found: Vec<(LayerId, Vec, Vec)> = Vec::new(); + let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); + for l in layers { + let (mut picked, mut partial) = (Vec::new(), Vec::new()); + for e in s.elements_on(l) { + let bounds = s.element_bounds_on(l, e.id); + if bounds.is_empty() || bounds.intersect(&r).is_empty() { + continue; + } + if contains(&r, &bounds) { + picked.push(e.id); + } else if mergeable(&e).is_some() { + partial.push(e.id); + } + } + if !picked.is_empty() || !partial.is_empty() { + found.push((l, picked, partial)); + } + } + let mut cut = 0; + let (mut origin, mut inside): (CutOrigin, Vec) = (Vec::new(), Vec::new()); + let mut hit: Vec = Vec::new(); + for (l, picked, partial) in found { + let (n, o, i) = s.with_layer(l, |s| marquee_layer(s, &r, picked, &partial))?; + cut += n; + origin.extend(o); + inside.extend(i); + hit.push(l); + } + if !inside.is_empty() { + s.pending_cut = Some((origin, inside)); + } + // The active layer stays when the marquee took something there, else the topmost that it + // did becomes active, as a click would make it. + if !hit.contains(&s.layer) + && let Some(&top) = hit.first() + { + s.layer = top; + } + Ok(json!({"selected": s.selection.id_list(), "cut": cut})) +} + +/// The marquee on the active layer: raw shapes partly under `r` are cut at its edges and the +/// parts inside are selected, the rest stay as they are; `picked` (wholly inside) are selected. +/// How many pieces it cut, each piece with the shape it came from, and the pieces inside. +fn marquee_layer(s: &mut Session, r: &Rect, mut picked: Vec, partial: &[ElementId]) -> Result<(usize, CutOrigin, Vec)> { + let here = s.layer; + let mut cut = 0; + let (mut origin, mut inside_all) = (Vec::new(), Vec::new()); + if !partial.is_empty() && on_editable_key(s) { + let kf = s.editable_keyframe()?; + let existing = kf.elements.clone(); + let idx: Vec = existing.iter().enumerate().filter(|(_, e)| partial.contains(&e.id)).map(|(i, _)| i).collect(); + // Parts already selected (an earlier marquee, with Shift) stay selected, cut or not. + let parts: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(here, e.id))).collect(); + let cutter = Path::rect(r.min.x, r.min.y, r.width(), r.height()); + match merge::remerge_with(s, &parts, Some(&cutter)) { + Some(rm) if !rm.inside.is_empty() => { + origin = rm.from.iter().filter_map(|&(piece, part)| idx.get(part).and_then(|&i| existing.get(i)).map(|e| (piece, e.id))).collect(); + cut = rm.inside.len(); + let gone: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| e.id).collect(); + s.selection.retain(|l, id| l != here || !gone.contains(&id)); + let mut inside = rm.inside; + inside.extend(rm.picked.iter().filter(|id| !inside.contains(id)).copied().collect::>()); + picked.extend(inside.iter().copied()); + merge::replace(s, &idx, rm.out, false)?; + inside_all = inside; + } + // Only their bounds reached in: nothing of them is under the marquee. + Some(_) => {} + // Too much to cut at once: they are selected whole. + None => picked.extend(partial.iter().copied()), + } + } else { + picked.extend(partial.iter().copied()); + } + s.selection.extend_on(here, picked); + Ok((cut, origin, inside_all)) +} + +// ----- merging again ---------------------------------------------------------------------------- + +fn merge_cmd(s: &mut Session, p: &Value) -> Result { + match opt_u64_list(p, "ids")? { + Some(v) => remerge_in_place(s, &v.into_iter().map(ElementId).collect::>())?, + // The selection's shapes, on each layer they are on. + None => { + s.each_layer(true, |s| { + let ids = s.selection.on(s.layer); + remerge_in_place(s, &ids)?; + Ok(json!({})) + })?; + } + } + Ok(json!({"selected": s.selection.id_list()})) +} + +/// Merges the raw shapes `ids` again with the raw shapes they touch, keeping their stacking (an +/// edit changed them in place). Selected shapes' pieces stay selected. +pub(crate) fn remerge_in_place(s: &mut Session, ids: &[ElementId]) -> Result<()> { + if ids.is_empty() { + return Ok(()); + } + let kf = s.editable_keyframe()?; + let existing = kf.elements.clone(); + let area = existing.iter().filter(|e| ids.contains(&e.id)).filter_map(|e| mergeable(e).map(|sh| reach(sh, &e.transform))).fold(Rect::EMPTY, |r, b| r.union(&b)); + if area.is_empty() { + return Ok(()); + } + let touching: Vec = existing.iter().enumerate().filter(|(_, e)| mergeable(e).is_some_and(|sh| !reach(sh, &e.transform).intersect(&area).is_empty())).map(|(i, _)| i).collect(); + let here = s.layer; + let parts: Vec = touching.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(here, e.id))).collect(); + // Too much to merge at once: the shapes stay as edited. + let Some((out, picked)) = merge::remerge(s, &parts) else { return Ok(()) }; + let gone: Vec = touching.iter().filter_map(|&i| existing.get(i)).map(|e| e.id).collect(); + merge::replace(s, &touching, out, false)?; + s.selection.retain(|l, id| l != here || !gone.contains(&id)); + s.selection.extend_on(here, picked); + Ok(()) +} diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs new file mode 100644 index 00000000..7187da73 --- /dev/null +++ b/crates/engine/src/cmds_rawsub.rs @@ -0,0 +1,435 @@ +//! The Subselection tool on raw shapes (ADR 0042; issue #42 §3). +//! +//! Clicking a raw stroke or fill shows the anchors of every raw shape **connected** to it: the +//! strokes and fills that meet it at a point or along an edge, and the ones those meet, and so +//! on. A layer's merged drawing stores a shared corner once in each shape that has it (ADR 0031), +//! so the anchors are listed once per position. Moving one moves every shape that shares it +//! (`raw.move_point`); dragging a handle changes the curve in every shape that has that edge +//! (`raw.move_handle`). +//! +//! Which anchors are selected is view state, kept by the editor (as for drawing objects): the +//! commands here report anchors and handles by stage position, and take positions back. + +use crate::cmds_raw::{check_extent, edit_edge, remerge_in_place}; +use crate::merge::mergeable; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind}; +use anicraft_geom::planar::SNAP; +use anicraft_geom::raw::{self as rawgeom, Cubic}; +use anicraft_geom::{Path, PathCmd, Rect, Vec2}; +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( + "raw.subselect", + "Subselect", + "", + None, + "{x, y, add?: bool, slop?} the Subselection tool's click: the raw stroke or fill at (x, y) and every raw shape connected to it are selected, to show their anchors (an object there is selected alone); returns the anchors and, on an edge, its ends", + false, + subselect as crate::RunFn, + ), + c( + "raw.subselect_rect", + "Subselect Rectangle", + "", + None, + "{x0, y0, x1, y1, add?: bool} the Subselection tool's marquee, on the active layer only: the shapes it touches are selected whole (raw ones with every raw shape connected to them); returns the raw anchors inside it", + false, + subselect_rect, + ), + c("raw.points", "Raw Points", "", None, "{ids?: [..]} the anchors of raw shapes (default: the selection), once per position, and the handles of their curved segments", false, points_cmd), + c( + "raw.move_handle", + "Move Handle", + "", + None, + "{id, cmd, slot: 1|2, dx, dy, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false)", + true, + move_handle, + ), + ] +} + +/// Most raw shapes one connected set takes in (keeps a click's cost bounded). +const MAX_SHAPES: usize = 20_000; +/// Most anchors listed. +const MAX_ANCHORS: usize = 50_000; +/// Raw shapes are connected where a point of one lies this near the other. +const TOUCH: f32 = 2.0 * SNAP; +/// Flattening tolerance for the connection test. +const FLAT: f32 = 0.05; + +// ----- connected raw shapes ---------------------------------------------------------------------- + +/// A raw shape's stage-space geometry for the connection test. +struct Geo { + id: ElementId, + bounds: Rect, + anchors: Vec, + lines: Vec<(Vec2, Vec2)>, +} + +fn geo(e: &Element) -> Option { + let sh = mergeable(e)?; + let m = e.transform; + let anchors = sh.path.editable_anchors().into_iter().map(|(_, p)| m.apply(p)).collect(); + let mut lines = Vec::new(); + for pl in sh.path.flatten(&m, FLAT) { + lines.extend(pl.points.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?)))); + if pl.closed + && let (Some(a), Some(b)) = (pl.points.last(), pl.points.first()) + { + lines.push((*a, *b)); + } + } + Some(Geo { id: e.id, bounds: sh.path.bounds().transformed(&m).inflate(TOUCH), anchors, lines }) +} + +/// Whether a point of `a` lies on `b`, within [`TOUCH`]. +fn lands_on(a: &Geo, b: &Geo) -> bool { + a.anchors.iter().filter(|p| b.bounds.contains(**p)).any(|p| b.lines.iter().any(|(u, v)| anicraft_geom::segment_distance(*p, *u, *v) <= TOUCH)) +} + +fn touch(a: &Geo, b: &Geo) -> bool { + !a.bounds.intersect(&b.bounds).is_empty() && (lands_on(a, b) || lands_on(b, a)) +} + +/// A grid over the shapes' bounds, so each shape is only tested against its neighbours. +struct Grid { + cell: f32, + cells: HashMap<(i64, i64), Vec>, + /// Shapes too large for the grid: tested against everything. + big: Vec, +} + +/// Most cells one shape is put in before it counts as big. +const MAX_CELLS: i64 = 256; + +impl Grid { + fn new(geos: &[Geo]) -> Grid { + let sum: f32 = geos.iter().map(|g| g.bounds.width().max(g.bounds.height())).sum(); + let cell = (sum / geos.len().max(1) as f32).clamp(1.0, 1.0e6); + let mut grid = Grid { cell, cells: HashMap::new(), big: Vec::new() }; + for (i, g) in geos.iter().enumerate() { + match grid.span(&g.bounds) { + Some(cells) => { + for k in cells { + grid.cells.entry(k).or_default().push(i); + } + } + None => grid.big.push(i), + } + } + grid + } + + /// The cells `r` covers, unless that is too many. + fn span(&self, r: &Rect) -> Option> { + let k = |v: f32| (v / self.cell).floor() as i64; + let (x0, y0, x1, y1) = (k(r.min.x), k(r.min.y), k(r.max.x), k(r.max.y)); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_CELLS { + return None; + } + Some((x0..=x1).flat_map(|x| (y0..=y1).map(move |y| (x, y))).collect()) + } + + /// The shapes that may touch `r` (every shape when `r` is too large). + fn near(&self, r: &Rect, n: usize) -> Vec { + let mut out: Vec = match self.span(r) { + Some(cells) => cells.iter().filter_map(|k| self.cells.get(k)).flatten().copied().chain(self.big.iter().copied()).collect(), + None => (0..n).collect(), + }; + out.sort_unstable(); + out.dedup(); + out + } +} + +/// The raw shapes among `els` connected to the `seeds` (themselves included): sharing a point +/// or an edge, directly or through others. Objects among the seeds are left out. +pub fn connected(els: &[Arc], seeds: &[ElementId]) -> Vec { + let geos: Vec = els.iter().filter_map(|e| geo(e)).take(MAX_SHAPES).collect(); + let grid = Grid::new(&geos); + let mut seen = vec![false; geos.len()]; + let mut todo: Vec = geos.iter().enumerate().filter(|(_, g)| seeds.contains(&g.id)).map(|(i, _)| i).collect(); + for &i in &todo { + if let Some(s) = seen.get_mut(i) { + *s = true; + } + } + let mut out = Vec::new(); + while let Some(i) = todo.pop() { + let Some(g) = geos.get(i) else { continue }; + out.push(g.id); + for j in grid.near(&g.bounds, geos.len()) { + if seen.get(j).copied().unwrap_or(true) { + continue; + } + if geos.get(j).is_some_and(|h| touch(g, h)) { + if let Some(s) = seen.get_mut(j) { + *s = true; + } + todo.push(j); + } + } + } + // In stacking order, as the layer has them. + els.iter().map(|e| e.id).filter(|id| out.contains(id)).collect() +} + +// ----- anchors and handles ----------------------------------------------------------------------- + +/// A handle of a curved segment, as the Subselection tool shows it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Handle { + /// Where the handle is, and the anchor its direction line starts from (stage space). + pub at: Vec2, + pub anchor: Vec2, + /// The shape, segment and control point (1: the segment's first, 2: its second) that + /// `raw.move_handle` takes. + pub id: ElementId, + pub cmd: usize, + pub slot: u8, +} + +/// The anchors and handles of a set of raw shapes. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawPoints { + /// Every anchor once (shapes share corners), in stage space. + pub anchors: Vec, + /// The handles of curved segments, once per position. + pub handles: Vec, +} + +/// Positions seen so far, within [`SNAP`] of each other counting as one. +#[derive(Default)] +struct Seen(HashMap<(i64, i64), Vec>); + +impl Seen { + fn key(p: Vec2) -> (i64, i64) { + ((p.x / SNAP).floor() as i64, (p.y / SNAP).floor() as i64) + } + /// Whether `p` is new (and remembers it). + fn insert(&mut self, p: Vec2) -> bool { + let (kx, ky) = Seen::key(p); + let near = (-1..=1).any(|dx| (-1..=1).any(|dy| self.0.get(&(kx + dx, ky + dy)).is_some_and(|v| v.iter().any(|q| q.distance(p) <= SNAP)))); + if !near { + self.0.entry((kx, ky)).or_default().push(p); + } + !near + } +} + +/// The path as the raw commands address it (a closed subpath's last side written out). +fn explicit(path: &Path) -> Path { + let mut p = path.clone(); + p.close_explicitly(); + p +} + +impl Session { + /// The raw shapes on the active layer connected to `ids` (themselves included). + pub fn raw_connected(&self, ids: &[ElementId]) -> Vec { + connected(&self.visible_elements(), ids) + } + + /// The anchors (once per position) and curve handles of the raw shapes `ids` on the active + /// layer. + pub fn raw_points(&self, ids: &[ElementId]) -> RawPoints { + let mut out = RawPoints::default(); + let (mut anchors, mut handles) = (Seen::default(), HashMap::<((i64, i64), (i64, i64)), Vec<(Vec2, Vec2)>>::new()); + for e in self.visible_elements().iter().filter(|e| ids.contains(&e.id)) { + let Some(sh) = mergeable(e) else { continue }; + let m = e.transform; + let path = explicit(&sh.path); + for (_, q) in path.editable_anchors() { + let q = m.apply(q); + if out.anchors.len() < MAX_ANCHORS && anchors.insert(q) { + out.anchors.push(q); + } + } + for k in 0..path.cmds.len().min(MAX_ANCHORS) { + if !matches!(path.cmds.get(k), Some(PathCmd::CubicTo(..) | PathCmd::QuadTo(..))) { + continue; + } + let Some(c) = rawgeom::segment_cubic(&path, k).map(|c| rawgeom::transform(&c, &m)) else { continue }; + for (slot, at, anchor) in [(1u8, c[1], c[0]), (2u8, c[2], c[3])] { + // A handle on its anchor has no direction to show. + if at.distance(anchor) <= SNAP || out.handles.len() >= MAX_ANCHORS { + continue; + } + // One edge shared by two shapes has its handles in both: show them once. + let key = (Seen::key(anchor), Seen::key(at)); + let list = handles.entry(key).or_default(); + if list.iter().any(|(a, h)| a.distance(anchor) <= SNAP && h.distance(at) <= SNAP) { + continue; + } + list.push((anchor, at)); + out.handles.push(Handle { at, anchor, id: e.id, cmd: k, slot }); + } + } + } + out + } +} + +fn points_json(pts: &RawPoints) -> Value { + json!({ + "anchors": pts.anchors.iter().map(|p| [p.x, p.y]).collect::>(), + "handles": pts.handles.iter().map(|h| json!({"x": h.at.x, "y": h.at.y, "ax": h.anchor.x, "ay": h.anchor.y, "id": h.id.0, "cmd": h.cmd, "slot": h.slot})).collect::>(), + }) +} + +fn points_cmd(s: &mut Session, p: &Value) -> Result { + let ids: Vec = match opt_u64_list(p, "ids")? { + Some(v) => v.into_iter().map(ElementId).collect(), + None => s.selection.on(s.layer), + }; + Ok(points_json(&s.raw_points(&ids))) +} + +// ----- clicking and the marquee ------------------------------------------------------------------ + +fn subselect(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let add = opt_bool(p, "add")?.unwrap_or(false); + let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0); + let Some((layer, hit)) = s.hit_test(at, slop) else { + if !add { + s.selection.clear(); + } + return Ok(json!({"selected": s.selection.id_list(), "raw": false, "ends": []})); + }; + if layer != s.layer { + s.layer = layer; + s.selection.clear(); + } + let els = s.visible_elements(); + let el = els.iter().find(|e| e.id == hit); + let raw = el.is_some_and(|e| mergeable(e).is_some()); + let picked = if raw { connected(&els, &[hit]) } else { vec![hit] }; + // On an edge (not inside a fill): its ends, whose handles show. + let mut ends = Vec::new(); + if let Some(e) = el.filter(|_| raw) + && let Some(sh) = mergeable(e) + { + let path = explicit(&sh.path); + if let Some((cmd, _, d)) = path.nearest_segment(at, &e.transform) + && d <= slop + sh.stroke.as_ref().map_or(0.0, |st| st.width * 0.5 * e.transform.mean_scale()) + && let Some(c) = rawgeom::segment_cubic(&path, cmd) + { + ends = vec![e.transform.apply(c[0]), e.transform.apply(c[3])]; + } + } + if !add { + s.selection.clear(); + } + s.selection.extend_on(s.layer, picked); + let mut v = if raw { points_json(&s.raw_points(&s.selection.on(s.layer))) } else { json!({}) }; + v["selected"] = json!(s.selection.id_list()); + v["raw"] = json!(raw); + v["ends"] = json!(ends.iter().map(|q| [q.x, q.y]).collect::>()); + Ok(v) +} + +/// Whether the shape `e` (stage space) has a part in `r`: a point, a line through it, or a fill +/// around it. Anything else counts by its bounds. +fn touches_rect(e: &Element, r: &Rect, bounds: &Rect) -> bool { + if bounds.intersect(r).is_empty() { + return false; + } + let ElementKind::Shape(sh) = &e.kind else { return true }; + let m = e.transform; + let crosses = |a: Vec2, b: Vec2| { + if r.contains(a) || r.contains(b) { + return true; + } + let (p, q, u, v) = (r.min, Vec2::new(r.max.x, r.min.y), r.max, Vec2::new(r.min.x, r.max.y)); + [(p, q), (q, u), (u, v), (v, p)].into_iter().any(|(c, d)| segments_cross(a, b, c, d)) + }; + for pl in sh.path.flatten(&m, 0.25) { + if pl.points.windows(2).any(|w| matches!(w, [a, b] if crosses(*a, *b))) || pl.points.first().is_some_and(|p| r.contains(*p)) { + return true; + } + if pl.closed && matches!((pl.points.last(), pl.points.first()), (Some(a), Some(b)) if crosses(*a, *b)) { + return true; + } + } + sh.fill.is_some() && sh.path.contains(r.center(), &m, sh.fill_rule) +} + +fn segments_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool { + let side = |p: Vec2, q: Vec2, x: Vec2| (q - p).cross(x - p); + let (d1, d2, d3, d4) = (side(c, d, a), side(c, d, b), side(a, b, c), side(a, b, d)); + (d1 * d2 <= 0.0) && (d3 * d4 <= 0.0) +} + +fn subselect_rect(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")?); + let add = opt_bool(p, "add")?.unwrap_or(false); + let r = Rect::from_points(a, b); + if !add { + s.selection.clear(); + } + let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer); + let empty = json!({"selected": s.selection.id_list(), "anchors": []}); + if !usable || !(r.width() > 0.0 || r.height() > 0.0) { + return Ok(empty); + } + let els = s.visible_elements(); + let (mut seeds, mut objects) = (Vec::new(), Vec::new()); + for e in &els { + if !touches_rect(e, &r, &s.element_bounds(e.id)) { + continue; + } + if mergeable(e).is_some() { seeds.push(e.id) } else { objects.push(e.id) } + } + let raw = connected(&els, &seeds); + // Subselection's marquee stays on the active layer, as in Animate (ADR 0042, 0044). + s.selection.extend_on(s.layer, raw.iter().chain(&objects).copied()); + let inside: Vec<[f32; 2]> = s.raw_points(&raw).anchors.into_iter().filter(|q| r.contains(*q)).map(|q| [q.x, q.y]).collect(); + Ok(json!({"selected": s.selection.id_list(), "anchors": inside})) +} + +// ----- handles ----------------------------------------------------------------------------------- + +fn move_handle(s: &mut Session, p: &Value) -> Result { + let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); + let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?; + let cmd = usize::try_from(cmd).unwrap_or(usize::MAX); + let slot = opt_u64(p, "slot")?.filter(|k| matches!(k, 1 | 2)).ok_or_else(|| EngineError::Param("param 'slot' must be 1 or 2".into()))? as usize; + let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); + let merge_after = opt_bool(p, "merge")?.unwrap_or(true); + let els = s.visible_elements(); + let el = els.iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?; + let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("only shapes have handles".into())) }; + let path = explicit(&sh.path); + if !matches!(path.cmds.get(cmd), Some(PathCmd::CubicTo(..) | PathCmd::QuadTo(..))) { + return Err(EngineError::Param(format!("segment {cmd} of this shape is not a curve (it has no handles)"))); + } + let old: Cubic = rawgeom::segment_cubic(&path, cmd).map(|c| rawgeom::transform(&c, &el.transform)).ok_or_else(|| EngineError::Param(format!("no segment {cmd} on this shape")))?; + let mut new = old; + if let Some(h) = new.get_mut(slot) { + *h = *h + d; + } + if !new.iter().all(|q| q.is_finite()) { + return Err(EngineError::Param("the move is too large".into())); + } + let mut bounds = Path::new(); + bounds.move_to(new[0]).cubic_to(new[1], new[2], new[3]); + check_extent(&bounds)?; + let raw = mergeable(el).is_some(); + let changed = edit_edge(s, id, cmd, &old, &new, raw)?; + if raw && merge_after { + remerge_in_place(s, &changed)?; + } + let at = new.get(slot).copied().unwrap_or(new[0]); + Ok(json!({"x": at.x, "y": at.y, "changed": changed.iter().map(|e| e.0).collect::>(), "merged": raw && merge_after})) +} diff --git a/crates/engine/src/cmds_script.rs b/crates/engine/src/cmds_script.rs index 7a27acab..8ab992b3 100644 --- a/crates/engine/src/cmds_script.rs +++ b/crates/engine/src/cmds_script.rs @@ -1,16 +1,19 @@ -//! Kept scripts (ADR 0013 tier 1): frame scripts written in another language (ActionScript, as +//! Kept scripts (ADR 0013): frame scripts written in another language (ActionScript, as //! Animate documents bring them), symbol linkage classes and the document class, kept verbatim -//! with the document. Nothing runs them yet: Test Movie, rendering and every export skip them. +//! with the document. Scripts in the ActionScript 3.0 subset run in Test Movie and the HTML +//! canvas export (tier 2); the rest are kept and not run, with the problems that say why. +//! Rendering and the other exports never run scripts. //! -//! `script.set / clear / list` edit and list a keyframe's kept script; `script.set_class` -//! sets a symbol's linkage class or the document class. A keyframe holds actions, a plug-in +//! `script.set / clear / list` edit and list a keyframe's kept script; `script.check` says +//! whether a text would run; `script.set_class` sets a symbol's linkage class or the document +//! class. A keyframe holds actions, a plug-in //! frame script *or* a kept script (one `Keyframe.script`), so setting one replaces the other, //! as one undo step. use crate::cmds_actions::{Scope, keyframe_in}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::actions::{self, FrameScript, Language, SourceScript}; +use anicraft_doc::actions::{self, CompileResult, FrameScript, Language, SourceScript}; use anicraft_doc::{Linkage, SymbolId}; use serde_json::{Value, json}; use std::sync::Arc; @@ -18,9 +21,10 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("script.set", "Set Frame Script", "", None, "{text?: the script, verbatim (\"\" clears; at most 1 MiB), language?: actionscript3|actionscript1or2|other (default: the script's, else actionscript3), symbol?: id, layer?, frame?} keeps a script on the keyframe at the frame (it replaces actions there); it is kept with the document and doesn't run", true, set as crate::RunFn), + c("script.set", "Set Frame Script", "", None, "{text?: the script, verbatim (\"\" clears; at most 1 MiB), language?: actionscript3|actionscript1or2|other (default: the script's, else actionscript3), symbol?: id, layer?, frame?} keeps a script on the keyframe at the frame (it replaces actions there); ActionScript 3.0 in the subset runs in Test Movie and the HTML export, the rest is kept and not run (`runs`, `problems` say which)", true, set as crate::RunFn), c("script.clear", "Clear Frame Script", "", None, "{symbol?, layer?, frame?} removes the keyframe's kept script (actions are left alone: actions.clear)", true, clear), - c("script.list", "List Frame Scripts", "", None, "{text?: bool (default true)} every kept script in every scene and symbol, with its text, plus symbol linkage classes and the document class", false, list), + c("script.list", "List Frame Scripts", "", None, "{text?: bool (default true)} every kept script in every scene and symbol, with its text, whether it runs and its problems, plus symbol linkage classes and the document class", false, list), + c("script.check", "Check Frame Script", "", None, "{text: the script, language?: actionscript3|actionscript1or2|other (default actionscript3)} whether it would run (the ActionScript 3.0 subset, ADR 0013), its problems with line and column, what is ignored, and the steps it runs; changes nothing", false, check), c("script.set_class", "Set Script Class", "", None, "{symbol?: id (default: the document), class: dotted class name (\"\" clears), base?: the class it extends} sets a symbol's linkage class, or the document class; kept as text, not run", true, set_class), ] } @@ -42,6 +46,30 @@ fn what(script: &Option) -> Value { } } +/// Whether a script runs, its problems and notes (each `{line, column, message}`; line 0 is +/// the whole script). +fn status(c: &CompileResult) -> Value { + match c { + Ok(c) => json!({"runs": true, "problems": [], "notes": c.notes}), + Err(p) => json!({"runs": false, "problems": p, "notes": []}), + } +} + +fn check(_: &mut Session, p: &Value) -> Result { + let text = str_req(p, "text")?; + if text.len() > actions::MAX_SOURCE_BYTES { + return Err(EngineError::Param(format!("a script is at most {} KiB", actions::MAX_SOURCE_BYTES / 1024))); + } + let script = SourceScript::new(language(p)?.unwrap_or_default(), text); + let c = script.compiled(); + let mut v = status(c); + if let Ok(c) = c { + v["steps"] = json!(c.ops); + v["describe"] = json!(c.ops.iter().map(|o| o.describe()).collect::>()); + } + Ok(v) +} + fn set(s: &mut Session, p: &Value) -> Result { let lang = language(p)?; let text = match p.get("text") { @@ -74,7 +102,10 @@ fn set(s: &mut Session, p: &Value) -> Result { } let script = SourceScript::new(lang.or(old.map(|o| o.language)).unwrap_or_default(), text); script.check().map_err(EngineError::Param)?; - let out = json!({"layer": lid.0, "keyframe": k.start, "language": script.language.key(), "lines": script.lines(), "bytes": script.text.len(), "replaced": if before == json!("script") { Value::Null } else { before }}); + let mut out = json!({"layer": lid.0, "keyframe": k.start, "language": script.language.key(), "lines": script.lines(), "bytes": script.text.len(), "replaced": if before == json!("script") { Value::Null } else { before }}); + if let (Some(o), Value::Object(st)) = (out.as_object_mut(), status(script.compiled())) { + o.extend(st); + } k.script = Some(FrameScript::Source(Arc::new(script))); Ok(out) } @@ -97,6 +128,9 @@ fn list(s: &mut Session, p: &Value) -> Result { for k in &l.keyframes { let Some(src) = k.script.as_ref().and_then(FrameScript::source) else { continue }; let mut v = json!({"timeline": name, "layer": l.id.0, "layer_name": l.name, "frame": k.start, "label": k.label, "language": src.language.key(), "lines": src.lines(), "bytes": src.text.len()}); + if let (Some(o), Value::Object(st)) = (v.as_object_mut(), status(src.compiled())) { + o.extend(st); + } if with_text { v["text"] = json!(src.text); } diff --git a/crates/engine/src/cmds_stroke.rs b/crates/engine/src/cmds_stroke.rs new file mode 100644 index 00000000..f5d505e1 --- /dev/null +++ b/crates/engine/src/cmds_stroke.rs @@ -0,0 +1,175 @@ +//! Stroke styles (ADR 0046): caps, joins, the miter limit, and dashed and dotted lines. +//! +//! The same style params work on `element.set_stroke`, the drawing commands and `paint.ink` +//! (see [`crate::params::opt_stroke_style`]); `stroke.set_style` is the one Properties uses. +//! Dash lengths and dot spacing are in the shape's own units, like the stroke width. + +use crate::cmds_width::{id_param, shape_mut, visible_shape}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Dash, ElementId, StrokeStyle}; +use serde_json::{Value, json}; + +pub fn specs() -> Vec { + vec![CommandSpec { + id: "stroke.set_style", + label: "Stroke Style", + menu: "", + shortcut: None, + params: "{cap?: none|round|square, join?: miter|round|bevel, miter? (limit, 1..=100; a corner whose point is longer than this many widths is bevelled), style?: solid|dashed|dotted, dash? ([on, off, ..] lengths in the shape's units; implies dashed), dash_offset?, dot_spacing? (between dots, edge to edge; implies dotted), id? (default: the selected shapes)}", + mutates: true, + run: |s, p| s.each_layer(false, |s| set_style(s, p)), + }] +} + +/// What a style is, as commands report it. +pub(crate) fn describe(st: &StrokeStyle) -> Value { + let mut v = json!({"cap": st.cap.key(), "join": st.join.key(), "miter": st.miter_limit, "style": st.dash_kind().key()}); + match &st.dash { + Some(Dash::Dashed { lengths, offset }) => { + v["dash"] = json!(lengths.to_vec()); + v["dash_offset"] = json!(offset); + } + Some(Dash::Dotted { spacing }) => v["dot_spacing"] = json!(spacing), + None => {} + } + v +} + +fn set_style(s: &mut Session, p: &Value) -> Result { + let ids: Vec = match id_param(p)? { + Some(id) => vec![id], + None => s.selection.on(s.layer), + }; + if ids.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + let stroked: Vec = ids.into_iter().filter(|id| visible_shape(s, *id).is_ok()).collect(); + if stroked.is_empty() { + return Err(EngineError::State("the selection has no stroked shapes".into())); + } + let mut last = None; + for id in &stroked { + if let Some(st) = shape_mut(s, *id)?.stroke.as_mut() { + // Each stroke keeps what the params leave out (and sizes a new pattern by its width). + let style = opt_stroke_style(p, &st.style, st.width)?.ok_or_else(|| EngineError::Param(format!("give a style to set ({STROKE_STYLE_PARAMS})")))?; + st.style = style; + last = Some(st.style.clone()); + } + } + let mut out = last.as_ref().map_or_else(|| json!({}), describe); + out["changed"] = json!(stroked.len()); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_doc::{Cap, ElementKind, Join, Stroke}; + + fn line(s: &mut Session) -> u64 { + let v = s.execute("draw.line", &json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke_width": 4})).unwrap(); + v["element"].as_u64().unwrap() + } + + fn stroke(s: &Session, id: u64) -> Option { + s.visible_elements().into_iter().find(|e| e.id.0 == id).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => sh.stroke.clone(), + _ => None, + }) + } + + #[test] + fn styles_apply_to_the_selection_undo_and_round_trip() { + let mut s = Session::default(); + let id = line(&mut s); + assert!(stroke(&s, id).unwrap().style.is_default(), "new strokes are round and solid"); + let v = s.execute("stroke.set_style", &json!({"cap": "none", "join": "miter", "miter": 6})).unwrap(); + assert_eq!((v["cap"].as_str(), v["join"].as_str(), v["miter"].as_f64(), v["changed"].as_u64()), (Some("butt"), Some("miter"), Some(6.0), Some(1))); + // Dashed with no lengths: sized by the stroke (4 wide: 12 on, 8 off). + let v = s.execute("stroke.set_style", &json!({"style": "dashed"})).unwrap(); + assert_eq!(v["dash"], json!([12.0, 8.0])); + let st = stroke(&s, id).unwrap().style; + assert_eq!((st.cap, st.join, st.miter_limit), (Cap::Butt, Join::Miter, 6.0), "what the params leave out stays"); + // A pattern of its own, then dots; each is one undo step. + s.execute("stroke.set_style", &json!({"dash": [5, 2, 1, 2], "dash_offset": 3})).unwrap(); + assert_eq!(stroke(&s, id).unwrap().style.dash, Dash::Dashed { lengths: vec![5.0, 2.0, 1.0, 2.0].into(), offset: 3.0 }.sanitized()); + let v = s.execute("stroke.set_style", &json!({"dot_spacing": 3, "id": id})).unwrap(); + assert_eq!((v["style"].as_str(), v["dot_spacing"].as_f64()), (Some("dotted"), Some(3.0))); + s.undo().unwrap(); + assert_eq!(stroke(&s, id).unwrap().style.dash_kind(), anicraft_doc::DashKind::Dashed); + // The .anicraft file keeps it. + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(text.contains("\"butt\"") && text.contains("\"lengths\""), "styled strokes are written"); + assert_eq!(crate::format::from_json(&text).unwrap(), s.doc); + // Back to solid. + s.execute("stroke.set_style", &json!({"style": "solid", "cap": "round", "join": "round", "miter": 3})).unwrap(); + assert!(stroke(&s, id).unwrap().style.is_default()); + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(!text.contains("\"style\""), "a default style is written as nothing, as before styles"); + } + + #[test] + fn bad_style_params_are_refused_and_change_nothing() { + let mut s = Session::default(); + let id = line(&mut s); + for bad in [ + json!({}), + json!({"cap": "pointy"}), + json!({"join": 3}), + json!({"miter": 0.5}), + json!({"miter": 1e9}), + json!({"style": "ragged"}), + json!({"dash": []}), + json!({"dash": [5, 0]}), + json!({"dash": [-1, 2]}), + json!({"dash": [1e30, 2]}), + json!({"dash": (0..40).collect::>()}), + json!({"dash": "5 2"}), + json!({"dash_offset": 1e30}), + json!({"dot_spacing": -2}), + ] { + assert!(s.execute("stroke.set_style", &bad).is_err(), "{bad}"); + assert!(s.execute("element.set_stroke", &bad).is_err() || bad == json!({}), "{bad}"); + } + assert!(stroke(&s, id).unwrap().style.is_default()); + s.execute("edit.deselect", &json!({})).unwrap(); + assert!(s.execute("stroke.set_style", &json!({"cap": "square"})).is_err(), "nothing selected"); + } + + #[test] + fn drawing_set_stroke_and_the_ink_bottle_carry_the_style() { + let mut s = Session::default(); + // Drawing commands take the tool's line style, or params. + s.style.line = StrokeStyle { cap: Cap::Square, ..StrokeStyle::default() }; + let id = line(&mut s); + assert_eq!(stroke(&s, id).unwrap().style.cap, Cap::Square); + let v = s.execute("draw.rect", &json!({"x": 400, "y": 400, "w": 50, "h": 40, "stroke": "#000000", "join": "bevel", "dash": [4, 2]})).unwrap(); + let rect = v["element"].as_u64().unwrap(); + let st = stroke(&s, rect).unwrap().style; + assert_eq!((st.cap, st.join, st.dash_kind()), (Cap::Square, Join::Bevel, anicraft_doc::DashKind::Dashed)); + // element.set_stroke takes the same params. + s.execute("element.set_stroke", &json!({"width": 6, "style": "dotted"})).unwrap(); + assert_eq!(stroke(&s, rect).unwrap().style.dash, Dash::dotted(6.0), "dots one width apart"); + // The Ink Bottle gives the tool's whole line. + s.style.line = StrokeStyle { join: Join::Miter, dash: Dash::dashed(7.0, 3.0), ..StrokeStyle::default() }; + s.execute("paint.ink", &json!({"x": 200, "y": 100})).unwrap(); + let st = stroke(&s, id).unwrap().style; + assert_eq!((st.join, st.dash), (Join::Miter, Dash::dashed(7.0, 3.0))); + s.execute("paint.ink", &json!({"x": 200, "y": 100, "cap": "none", "style": "solid"})).unwrap(); + let st = stroke(&s, id).unwrap().style; + assert_eq!((st.cap, st.dash), (Cap::Butt, None)); + } + + #[test] + fn the_eyedropper_picks_the_style_and_scales_its_dashes() { + let mut s = Session::default(); + let id = line(&mut s); + s.execute("stroke.set_style", &json!({"cap": "square", "dash": [6, 2]})).unwrap(); + s.execute("element.set_transform", &json!({"sx": 2, "sy": 2})).unwrap(); + let v = s.execute("paint.pick", &json!({"x": 200, "y": 100})).unwrap(); + assert_eq!((v["cap"].as_str(), v["style"].as_str()), (Some("square"), Some("dashed")), "{v}"); + assert_eq!(s.style.line.dash, Dash::dashed(12.0, 4.0), "as drawn: twice as long"); + assert!(stroke(&s, id).is_some()); + } +} diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index ededa328..e2b4dacc 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ c("text.create", "New Text", "", None, "{text, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), - c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, edit), + c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))), c("text.fonts", "Fonts", "", None, "{}", false, fonts), ] } @@ -153,7 +153,7 @@ fn create(s: &mut Session, p: &Value) -> Result { s.text_style = TextStyle { font: block.font.clone(), ..style }; let el = Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(out) } diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index e601f92d..c452ac97 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -2,7 +2,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session}; -use anicraft_doc::{Keyframe, Layer, LayerId, LayerKind, Tween, TweenKind, evaluate_layer_elements}; +use anicraft_doc::{ElementId, Keyframe, Layer, LayerId, LayerKind, Tween, TweenKind, evaluate_layer_elements}; use serde_json::{Value, json}; use std::sync::Arc; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { 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.select", "Select Layer", "", None, "{layer: id} or {index}, select?: bool (also select all of its artwork at the playhead, as a click on the layer's name does; nothing on a locked or hidden layer)", 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), @@ -135,6 +135,9 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Camera) { return Err(EngineError::State("the camera layer holds the camera; it can't become another kind of layer (Remove Camera takes it away)".into())); } + if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Armature) { + return Err(EngineError::State("an armature layer holds its armature; it can't become another kind of layer (removing its bones frees the instances)".into())); + } // Whatever the type, the layer stays in the folder it is in. let folder = tl.folder_of(i); let (kind, parent) = match ty { @@ -169,6 +172,7 @@ fn layer_type_json(s: &Session, id: LayerId) -> Value { LayerKind::Guide => "guide", LayerKind::Folder => "folder", LayerKind::Camera => "camera", + LayerKind::Armature => "armature", LayerKind::Normal if masked_by.is_some() => "masked", LayerKind::Normal if guided_by.is_some() => "guided", LayerKind::Normal => "normal", @@ -326,11 +330,14 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R k.elements.clear(); k.tween = None; k.motion = None; + k.pose = anicraft_doc::Pose::default(); } } return Ok(()); } let elements = if copy { evaluate_layer_elements(layer, frame).map(|(_, e)| e.into_owned()) } else { None }; + // On an armature layer a copy keeps the pose the frame shows (tweened between keys). + let pose = if copy { anicraft_doc::armature::pose_at(layer, frame) } else { None }; // Past the end of a motion tween, a copy starts from how its object looks at the end. let last_state = match layer.keyframes.iter().rposition(|k| k.start < frame) { Some(i) if copy && layer.keyframe_index_at(frame).is_none() => { @@ -357,6 +364,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R nk.elements = elements.unwrap_or_default(); nk.tween = tween; nk.motion = motion; + nk.pose = pose.unwrap_or_default(); layer.keyframes.insert(i + 1, Arc::new(nk)); } None => { @@ -368,6 +376,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R if let Some(k) = layer.keyframe_mut(i) { if copy { nk.elements = last_state.unwrap_or_else(|| k.elements.clone()); + nk.pose = k.pose.clone(); } k.duration = frame - k.start; } @@ -645,6 +654,12 @@ fn new_folder(s: &mut Session, p: &Value) -> Result { add_layer(s, p, LayerKind::Folder) } +/// The colour the `n`th layer gets (its outline and timeline bar). +pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba { + const PALETTE: [u32; 7] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; + anicraft_doc::Rgba::hex(PALETTE.get(n % PALETTE.len()).copied().unwrap_or(0x4fa3ff)) +} + fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { let tl = s.doc.timeline(s.scene); if tl.layers.len() >= 1000 { @@ -672,8 +687,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { // Match the timeline length so the new layer spans the existing frames. k.duration = s.frame_count().max(1); } - let palette = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; - layer.color = anicraft_doc::Rgba::hex(palette[n % palette.len()]); + layer.color = layer_color(n); let tl = s.doc.timeline_mut(s.scene); tl.layers.insert(at, Arc::new(layer)); tl.repair_masks(); @@ -740,6 +754,14 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { if s.doc.timeline(s.scene).layer(id).is_none() { return Err(EngineError::State(format!("no layer with id {}", id.0))); } + // A click on a layer's name in Animate: the layer becomes active with all of its artwork at + // the playhead selected (ADR 0044). + if opt_bool(p, "select")? == Some(true) { + s.layer = id; + let ids: Vec = if s.selectable(id) { s.elements_on(id).iter().map(|e| e.id).collect() } else { Vec::new() }; + s.selection = crate::Selection::only(id, ids); + return Ok(json!({"layer": id.0, "selected": s.selection.id_list()})); + } if s.layer != id { s.layer = id; s.selection.clear(); diff --git a/crates/engine/src/cmds_width.rs b/crates/engine/src/cmds_width.rs index 9fbf287a..38fd6d28 100644 --- a/crates/engine/src/cmds_width.rs +++ b/crates/engine/src/cmds_width.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { None, "{profile: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], id? (default: the selected shapes)}", true, - set_profile as crate::RunFn, + (|s, p| s.each_layer(false, |s| set_profile(s, p))) as crate::RunFn, ), c( "stroke.set_width_point", @@ -41,12 +41,12 @@ pub fn specs() -> Vec { /// Flattening tolerance for finding places on a stroke, in stage units. const FIND_TOL: f32 = 0.2; -fn id_param(p: &Value) -> Result> { +pub(crate) fn id_param(p: &Value) -> Result> { Ok(opt_u64(p, "id")?.map(ElementId)) } /// The shape element `id` as it shows at the playhead on the active layer. -fn visible_shape(s: &Session, id: ElementId) -> Result> { +pub(crate) fn visible_shape(s: &Session, id: ElementId) -> Result> { let el = s.visible_elements().into_iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?; match &el.kind { ElementKind::Shape(sh) if sh.stroke.is_some() => Ok(el), @@ -56,7 +56,7 @@ fn visible_shape(s: &Session, id: ElementId) -> Result> } /// The editable copy of shape `id` (copy-on-write; keys a tween's frame like any edit). -fn shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> { +pub(crate) fn shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> { visible_shape(s, id)?; let kf = s.editable_keyframe()?; let el = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?; @@ -90,7 +90,7 @@ fn set_profile(s: &mut Session, p: &Value) -> Result { let profile = opt_profile(p, "profile")?.ok_or_else(|| EngineError::Param("param 'profile' is required".into()))?; let ids: Vec = match id_param(p)? { Some(id) => vec![id], - None => s.selection.clone(), + None => s.selection.on(s.layer), }; if ids.is_empty() { return Err(EngineError::State("nothing is selected".into())); diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 53a2cba6..138d0fa0 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -156,6 +156,27 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { }) } "camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?), + "bone.remove" => { + // The bone's moves in every pose go with it (ADR 0043); one pose loses nothing. + let id = anicraft_doc::BoneId(p.get("bone").and_then(Value::as_u64)?); + let l = s.doc.timeline(s.scene).layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; + let arm = l.armature.as_deref()?; + let n = crate::cmds_bone::poses(l); + let below = arm.subtree(id).len().saturating_sub(1); + let name = arm.bone(id).map(|b| if b.name.is_empty() { "The bone".to_string() } else { format!("“{}”", b.name) })?; + (n > 1).then(|| Confirmation { + title: "Remove bone?".into(), + message: format!( + "{name}{} {} posed over {}; removing takes {} out of every pose. The instances stay where they are now, on a layer of their own. You can undo this.", + if below > 0 { format!(" and the {} below it", plural(below, "bone")) } else { String::new() }, + if below > 0 { "are" } else { "is" }, + plural(n, "keyframe"), + if below > 0 { "them" } else { "it" }, + ), + action: "Remove Bone".into(), + irreversible: false, + }) + } "layer.delete" => { let l = target_layer(s, p)?; if l.kind == anicraft_doc::LayerKind::Camera { diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index fb2add3b..25294358 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -5,7 +5,7 @@ //! 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 anicraft_doc::{Document, Element, ElementKind, Keyframe, Layer, LayerId, Symbol}; use std::collections::{HashSet, VecDeque}; use std::mem::size_of; use std::sync::Arc; @@ -30,7 +30,7 @@ pub struct Snapshot { pub scene: usize, pub frame: u32, pub layer: LayerId, - pub selection: Vec, + pub selection: crate::Selection, /// Estimated bytes this snapshot keeps alive that the neighbouring state does not share. pub bytes: usize, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f2e55bf7..e95da941 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -6,6 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod cmds_actions; +mod cmds_bone; pub mod cmds_brush; mod cmds_camera; mod cmds_draw; @@ -17,6 +18,8 @@ mod cmds_motion; mod cmds_hints; mod cmds_paint; mod cmds_path; +pub mod cmds_raw; +pub mod cmds_rawsub; mod cmds_recovery; mod cmds_script; pub mod cmds_plugin; @@ -25,12 +28,15 @@ pub mod cmds_sound; pub mod cmds_text; mod cmds_timeline; mod cmds_width; +mod cmds_stroke; pub mod confirm; pub mod format; pub mod history; mod merge; +pub mod onion; pub mod recovery; pub mod render_service; +pub mod selection; pub mod params; pub mod player; pub mod vfs; @@ -101,19 +107,24 @@ pub fn commands() -> Vec { v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); v.extend(cmds_camera::specs()); + v.extend(cmds_bone::specs()); v.extend(cmds_motion::specs()); v.extend(cmds_hints::specs()); v.extend(cmds_scene::specs()); v.extend(cmds_frames::specs()); + v.extend(onion::specs()); v.extend(cmds_draw::specs()); v.extend(merge::specs()); v.extend(cmds_modify::specs()); v.extend(cmds_path::specs()); + v.extend(cmds_raw::specs()); + v.extend(cmds_rawsub::specs()); v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); v.extend(cmds_text::specs()); v.extend(cmds_width::specs()); + v.extend(cmds_stroke::specs()); v.extend(cmds_plugin::specs()); v.extend(cmds_sound::specs()); v.extend(cmds_actions::specs()); @@ -134,10 +145,32 @@ pub fn find_command(id: &str) -> Option { } pub use history::{Snapshot, StateId}; +pub use selection::Selection; /// Last addressable frame (0-based); about 70 minutes at 24 fps. pub const MAX_FRAME: u32 = 100_000; +/// The index of the topmost item of `dl` under `p` (stage space) that `ok` accepts (given its +/// index). A bounding-box test rejects almost every item before any curve is flattened; +/// masked-away parts cannot be picked. +pub(crate) fn pick_index(dl: &DisplayList, p: Vec2, slop: f32, ok: impl Fn(usize, &anicraft_doc::DisplayItem) -> bool) -> Option { + for (i, item) in dl.items.iter().enumerate().rev() { + let hw = item.stroke.as_ref().map_or(0.0, |s| s.reach() * item.transform.mean_scale()); + let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop); + if !bounds.contains(p) || !ok(i, item) { + continue; + } + 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(i); + } + } + None +} + /// Drawing defaults used by the drawing commands when params omit colours. #[derive(Clone, Debug)] pub struct ToolStyle { @@ -153,15 +186,20 @@ pub struct ToolStyle { pub stroke_profile: anicraft_doc::ProfilePreset, /// A picked width profile that is none of the presets (it wins over `stroke_profile`). pub custom_profile: Option, + /// The caps, joins and dashes new strokes get (ADR 0046). + pub line: anicraft_doc::StrokeStyle, /// Object Drawing: new shapes are drawing objects. Off, they merge with the raw shapes they /// touch (ADR 0031). On by default, so a script's draw command makes one element; the editor /// starts with it off, as Animate does. pub object_drawing: bool, + /// Snap to Objects (Animate's magnet, ADR 0042): dragged points and selections snap to + /// points, lines and fill edges nearby. On by default; off, the `snap` params do nothing. + pub snap_objects: bool, } impl Default for ToolStyle { fn default() -> Self { - ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, object_drawing: true } + ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, line: anicraft_doc::StrokeStyle::default(), object_drawing: true, snap_objects: true } } } @@ -179,6 +217,14 @@ impl ToolStyle { pub fn profile(&self) -> Option { self.custom_profile.clone().or_else(|| self.stroke_profile.profile()) } + /// A new stroke of `color` and `width` with the current profile and line style. + pub fn new_stroke(&self, color: anicraft_doc::Rgba, width: f32) -> anicraft_doc::Stroke { + anicraft_doc::Stroke::new(color, width).with_profile(self.profile()).with_style(self.line.clone()) + } + /// The snapping radius a command asked for (`snap`), or none when Snap to Objects is off. + pub fn snap_radius(&self, asked: f32) -> f32 { + if self.snap_objects { asked } else { 0.0 } + } /// Sets the profile to a preset (dropping a picked custom one). pub fn set_profile(&mut self, p: anicraft_doc::ProfilePreset) { self.stroke_profile = p; @@ -199,8 +245,8 @@ pub struct Session { pub frame: u32, /// Active layer. pub layer: LayerId, - /// Selected elements on the active layer. - pub selection: Vec, + /// Selected elements at the playhead, each with its layer (ADR 0044). + pub selection: Selection, /// Bumped on every document change, undo and redo (UI invalidation). pub revision: u64, /// Identity of the current document content (equal ids ⇒ identical content). @@ -227,6 +273,33 @@ pub struct Session { /// A name for the undo step the running command records, set by the command /// (`plugin.run` names its step after the plug-in). pub(crate) step_label: Option, + /// A marquee's cut that nothing has used yet (ADR 0041). + provisional: Option, + /// Set by `raw.select_rect` when it cut: each piece and the shape it was cut from, and the + /// pieces inside the marquee. + pub(crate) pending_cut: Option<(CutOrigin, Vec)>, + /// The open gesture began on a provisional cut: the document with the cut. + gesture_cut: Option, +} + +/// Each piece of a marquee's cut, with the shape it was cut from. +pub(crate) type CutOrigin = Vec<(ElementId, ElementId)>; + +/// A marquee's cut that nothing has used yet (ADR 0041). In Animate a marquee only selects: the +/// drawing is cut where it crosses once the selection is moved or changed. Here the cut happens +/// at once (the parts must be elements to be selected) and records no undo step. It is taken +/// back as soon as the selection lets go of its pieces with nothing else changed; the first edit +/// that uses it records one step from before the cut. +struct Provisional { + /// Before the cut. + before: history::Snapshot, + /// The document with the cut, and its state. + cut: Document, + state: history::StateId, + /// Each piece and the shape it was cut from. + origin: Vec<(ElementId, ElementId)>, + /// The pieces inside the marquee(s): while one of them is selected, the cut is in use. + inside: Vec, } impl Default for Session { @@ -252,7 +325,7 @@ impl Session { scene: 0, frame: 0, layer, - selection: Vec::new(), + selection: Selection::default(), revision: 1, state, saved_state: Some(state), @@ -267,6 +340,9 @@ impl Session { motion_edit: None, plugins: anicraft_plugins::Registry::default(), step_label: None, + provisional: None, + pending_cut: None, + gesture_cut: None, } } @@ -304,16 +380,35 @@ impl Session { /// 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)); + if self.gesture.is_some() { + return; + } + // On a marquee's cut, the step (if the gesture makes one) starts from before the cut. + let cut = self.live_cut().map(|p| (history::Snapshot { label: label.to_string(), ..p.before.clone() }, p.cut.clone())); + match cut { + Some((before, doc)) => { + self.gesture_cut = Some(doc); + self.gesture = Some(before); + } + 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 - { + let cut = self.gesture_cut.take(); + let Some(before) = self.gesture.take() else { return }; + if let Some(cut) = &cut { + if self.doc == *cut { + // Nothing used the marquee's cut: it stays provisional. + if let Some(p) = &self.provisional { + self.state = p.state; + } + return; + } + self.provisional = None; + } + if self.doc != before.doc { self.history.record(before, &self.doc); } } @@ -349,12 +444,22 @@ impl Session { { return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message))); } + self.settle_cut(id, params); if !spec.mutates { - return (spec.run)(self, params); + let r = (spec.run)(self, params); + self.settle_cut(id, params); + return r; } - let mut before = self.snapshot(spec.label); + // An edit on a marquee's cut records its step from before the cut (ADR 0041). + let cut = self.live_cut().map(|p| (history::Snapshot { label: spec.label.to_string(), ..p.before.clone() }, p.cut.clone())); + let rollback = cut.as_ref().map(|_| self.snapshot(spec.label)); + let mut before = match &cut { + Some((b, _)) => b.clone(), + None => self.snapshot(spec.label), + }; // A command must never observe a display list of the state it is changing. self.dl_cache.replace(None); + self.pending_cut = None; self.motion_edit = None; self.step_label = None; let result = (spec.run)(self, params); @@ -368,26 +473,105 @@ impl Session { if let Some(label) = self.step_label.take() { before.label = label; } + let pending = self.pending_cut.take(); match result { Ok(v) => { - // O(changed): unchanged subtrees compare by pointer. - if self.doc != before.doc { + let changed = match &cut { + Some((_, doc)) => self.doc != *doc, + // O(changed): unchanged subtrees compare by pointer. + None => self.doc != before.doc, + }; + if changed { self.state = history::fresh_state(); self.revision += 1; - if self.gesture.is_none() { - self.history.record(before, &self.doc); + match pending.filter(|_| self.gesture.is_none()) { + // A marquee's cut: provisional, no step (yet). + Some((origin, inside)) => self.begin_cut(before, cut.is_some(), origin, inside), + None => { + if cut.is_some() { + self.provisional = None; + } + if self.gesture.is_none() && self.doc != before.doc { + self.history.record(before, &self.doc); + } + } } } self.fix_selection(); Ok(v) } Err(e) => { - self.restore(before); + // Back to the cut, which stays provisional, or to before the command. + self.restore(rollback.unwrap_or(before)); Err(e) } } } + /// The marquee's cut, while nothing has changed since it. + fn live_cut(&self) -> Option<&Provisional> { + self.provisional.as_ref().filter(|p| p.state == self.state && self.gesture.is_none()) + } + + /// Keeps a marquee's cut provisional. `before` is the document before it; `chained` when + /// it cut a provisional cut again (Shift), whose pieces then lead back to the shapes the + /// first cut took. + fn begin_cut(&mut self, before: history::Snapshot, chained: bool, origin: Vec<(ElementId, ElementId)>, inside: Vec) { + let (mut origin, mut inside) = (origin, inside); + if chained && let Some(p) = self.provisional.take() { + inside.extend(p.inside.iter().copied()); + for o in &mut origin { + if let Some(&(_, first)) = p.origin.iter().find(|(piece, _)| *piece == o.1) { + o.1 = first; + } + } + let new: Vec = origin.iter().map(|o| o.0).collect(); + origin.extend(p.origin.into_iter().filter(|(piece, _)| !new.contains(piece))); + } + // A marquee alone leaves the document as it was saved. + if self.saved_state == Some(before.state) { + self.saved_state = Some(self.state); + } + self.provisional = Some(Provisional { before, cut: self.doc.clone(), state: self.state, origin, inside }); + } + + /// Takes back a provisional cut that the selection has let go of (none of the pieces inside + /// the marquee is selected), and before saving, undo, redo or a new marquee. + fn settle_cut(&mut self, id: &str, params: &Value) { + if self.gesture.is_none() && self.provisional.as_ref().is_some_and(|p| p.state != self.state) { + self.provisional = None; + } + let Some(p) = self.live_cut() else { return }; + let held = self.selection.ids().any(|s| p.inside.contains(&s)); + let fresh_marquee = id == "raw.select_rect" && params.get("add").and_then(Value::as_bool) != Some(true); + if !held || fresh_marquee || id.starts_with("file.") || id == "edit.undo" || id == "edit.redo" { + self.heal_cut(); + } + } + + /// Puts the document back as it was before a provisional cut. Selected pieces become the + /// shapes they were cut from. + fn heal_cut(&mut self) { + let Some(p) = self.provisional.take() else { return }; + if p.state != self.state || self.gesture.is_some() { + return; + } + let mut sel = Selection::default(); + for (layer, id) in self.selection.iter() { + let id = p.origin.iter().find(|(piece, _)| *piece == id).map_or(id, |o| o.1); + sel.insert(layer, id); + } + if self.saved_state == Some(p.state) { + self.saved_state = Some(p.before.state); + } + self.doc = p.before.doc; + self.state = p.before.state; + self.selection = sel; + self.dl_cache.replace(None); + self.revision += 1; + self.fix_selection(); + } + /// Runs a command inside another one (a plug-in's requests during `plugin.run`): checked /// and atomic like [`Session::execute`], but it records no undo step of its own, so the /// outer command stays one step. @@ -405,6 +589,7 @@ impl Session { self.dl_cache.replace(None); let result = (spec.run)(self, params); self.dl_cache.replace(None); + self.pending_cut = None; match result { Ok(v) => { // Later requests must see this change (display list, hit tests): new state. @@ -424,6 +609,10 @@ impl Session { /// Puts the document back where the open gesture started, keeping the gesture open. A /// live preview re-runs from the same start on every change, and Cancel leaves no step. pub fn revert_gesture(&mut self) { + if self.gesture_cut.is_some() { + // Back to before the marquee's cut: it is gone. + self.provisional = None; + } let Some(g) = &self.gesture else { return }; if g.doc == self.doc && g.selection == self.selection { return; @@ -463,6 +652,7 @@ impl Session { pub fn undo(&mut self) -> Result { self.end_gesture(); + self.heal_cut(); let cur = self.snapshot(""); let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?; let label = s.label.clone(); @@ -474,6 +664,7 @@ impl Session { pub fn redo(&mut self) -> Result { self.end_gesture(); + self.heal_cut(); let cur = self.snapshot(""); let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?; let label = s.label.clone(); @@ -534,28 +725,10 @@ impl Session { /// 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 tl = self.doc.timeline(self.scene); let dl = self.display_list(); - for item in dl.items.iter().rev() { - let hw = item.stroke.as_ref().map_or(0.0, |s| s.reach() * item.transform.mean_scale()); - let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop); - if !bounds.contains(p) { - continue; - } - let tl = self.doc.timeline(self.scene); - let Some(layer) = tl.layer(item.layer) else { continue }; - if layer.locked || tl.locked_by_folder(layer.id) { - 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 + let i = pick_index(&dl, p, slop, |_, it| tl.layer(it.layer).is_some_and(|layer| !layer.locked && !tl.locked_by_folder(layer.id)))?; + dl.items.get(i).map(|it| (it.layer, it.element)) } /// Stage-space bounds of a top-level element at the playhead. @@ -568,24 +741,6 @@ impl Session { 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) { - self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); - if self.doc.timeline(self.scene).layer(self.layer).is_none() { - self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id); - } - 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(); @@ -601,20 +756,24 @@ impl Session { /// 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> { - self.editable_keyframe_in(false) + self.editable_keyframe_in(KeyEdit::Artwork) } - /// [`Session::editable_keyframe`]; with `camera`, on the camera layer (which holds only the - /// camera: every other edit is refused there, ADR 0027). - pub(crate) fn editable_keyframe_in(&mut self, camera: bool) -> Result<&mut Keyframe> { + /// [`Session::editable_keyframe`] for `what`: the camera layer holds only the camera (ADR + /// 0027) and an armature layer only its posed armature (ADR 0043); every other edit is + /// refused there. + pub(crate) fn editable_keyframe_in(&mut self, what: KeyEdit) -> Result<&mut Keyframe> { let frame = self.frame; let tl = self.doc.timeline(self.scene); if let Some(l) = tl.layer(self.layer) { if l.kind == LayerKind::Folder { return Err(EngineError::State(format!("'{}' is a folder; pick a layer inside it to draw on", l.name))); } - if (l.kind == LayerKind::Camera) != camera { - return Err(EngineError::State(if camera { "that is not the camera layer".into() } else { format!("'{}' is the camera layer: it holds the camera, not artwork. Pick another layer to draw on, or move the camera with the Camera tool", l.name) })); + if (l.kind == LayerKind::Camera) != (what == KeyEdit::Camera) { + return Err(EngineError::State(if what == KeyEdit::Camera { "that is not the camera layer".into() } else { format!("'{}' is the camera layer: it holds the camera, not artwork. Pick another layer to draw on, or move the camera with the Camera tool", l.name) })); + } + if (l.kind == LayerKind::Armature) != (what == KeyEdit::Pose) { + return Err(EngineError::State(if what == KeyEdit::Pose { "that is not an armature layer".into() } else { format!("'{}' is an armature layer: it holds the armature's instances, posed by their bones. Drag a bone (or an instance) to pose it, drag the root instance to move it all, or pick another layer to draw on", l.name) })); } if tl.locked_by_folder(l.id) { return Err(EngineError::State(format!("layer '{}' is in a locked folder", l.name))); @@ -651,7 +810,7 @@ impl Session { /// 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(); + let sel: std::collections::HashSet = self.selection.on(self.layer).into_iter().collect(); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -683,7 +842,8 @@ impl Session { "scenes": self.doc.scenes.iter().map(|s| json!({"name": s.name, "frames": s.timeline.frame_count()})).collect::>(), "movie_frames": self.doc.frame_count(), "layer": self.layer.0, - "selection": self.selection.iter().map(|e| e.0).collect::>(), + "selection": self.selection.id_list(), + "selection_layers": self.selected_layers().iter().map(|l| l.0).collect::>(), "layers": layers, "library": symbols, "sounds": sounds, @@ -695,6 +855,17 @@ impl Session { } } +/// What [`Session::editable_keyframe_in`] is asked to edit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum KeyEdit { + /// Artwork: any layer but the camera and armature layers. + Artwork, + /// The camera, on the camera layer. + Camera, + /// A pose, on an armature layer. + Pose, +} + /// Short human label for an element (properties panel, library, CLI). pub fn element_label(doc: &Document, e: &Element) -> String { let kind = match &e.kind { @@ -724,6 +895,8 @@ mod motion_tests; #[cfg(test)] mod motion_path_tests; #[cfg(test)] +mod motion_pin_tests; +#[cfg(test)] mod plugin_tests; #[cfg(test)] mod tests_sound; @@ -736,8 +909,14 @@ mod tests_script; #[cfg(test)] mod tests_camera; #[cfg(test)] +mod tests_bone; +#[cfg(test)] mod merge_tests; #[cfg(test)] +mod raw_tests; +#[cfg(test)] +mod rawsub_tests; +#[cfg(test)] mod brush_tests; #[cfg(test)] mod web_tests; @@ -745,3 +924,5 @@ mod web_tests; mod erase_tests; #[cfg(test)] mod eyedropper_tests; +#[cfg(test)] +mod selection_tests; diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index d593a664..3e41aca4 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -4,7 +4,7 @@ use crate::params::*; use crate::{CommandSpec, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Paint, Shape, Stroke}; +use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Paint, Shape, Stroke, Timeline}; use anicraft_geom::planar::{self, Item, SNAP}; use anicraft_geom::{Affine, Path, PathCmd, Rect, Vec2}; use serde_json::{Value, json}; @@ -13,23 +13,26 @@ 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.drop", "Drop", "", None, "{} the selected raw shapes cut and join the raw shapes they touch (after a move)", true, drop as crate::RunFn), + c("draw.drop", "Drop", "", None, "{} the selected raw shapes cut and join the raw shapes they touch (after a move), on each layer", true, (|s, p| s.each_layer(true, |s| drop(s, p))) as crate::RunFn), c("element.select_connected", "Select Connected", "", None, "{x, y, add?, slop?} a raw stroke and the strokes joined to it, or a raw fill and the strokes on and in it", false, select_connected), ] } -/// A raw shape the merge can take: a solid fill (or none) and a stroke of one width (or none). +/// A raw shape the merge can take: any fill (solid, gradient or bitmap: the paint is carried +/// into each piece, ADR 0042) or none, and a stroke of one width or none. A width profile runs +/// along the whole stroke, so cutting it would need its length carried through the merge; those +/// strokes stay whole, as objects, for now. pub(crate) fn mergeable(e: &Element) -> Option<&Shape> { match &e.kind { - ElementKind::Shape(s) if s.merge && matches!(s.fill, None | Some(Paint::Solid(_))) && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s), + ElementKind::Shape(s) if s.merge && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s), _ => None, } } -/// Whether a new shape with this style can join the drawing (other paints and width profiles are +/// Whether a new shape with this style can join the drawing (strokes with a width profile are /// drawn as objects for now). -pub(crate) fn can_merge(fill: Option<&Paint>, stroke: Option<&Stroke>) -> bool { - matches!(fill, None | Some(Paint::Solid(_))) && stroke.is_none_or(|st| st.profile.is_none()) +pub(crate) fn can_merge(stroke: Option<&Stroke>) -> bool { + stroke.is_none_or(|st| st.profile.is_none()) } pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect { @@ -113,6 +116,27 @@ const ERASED: u32 = u32::MAX; /// and returns them with the ids of the pieces whose topmost source part was marked. `None` when /// there is too much to merge at once. pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec>, Vec)> { + remerge_with(s, parts, None).map(|r| (r.out, r.picked)) +} + +/// What [`remerge_with`] makes. +pub(crate) struct Remerged { + pub out: Vec>, + /// Pieces whose topmost source part was marked. + pub picked: Vec, + /// Pieces inside the cutter (ADR 0041). + pub inside: Vec, + /// Each piece and the index in `parts` of its topmost source. + pub from: Vec<(ElementId, usize)>, +} + +/// [`remerge`], cutting along `cutter` too when there is one ([`planar::merge_cut`]). +pub(crate) fn remerge_with(s: &mut Session, parts: &[Part], cutter: Option<&Path>) -> Option { + remerge_doc(&mut s.doc, parts, cutter) +} + +/// [`remerge_with`] for any document (new pieces take ids from `doc`). +fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Option { // Style tables: equal entries are one style to the merge. let mut fills: Vec<(Paint, ColorEffect)> = Vec::new(); let mut strokes: Vec<(Stroke, ColorEffect)> = Vec::new(); @@ -124,8 +148,10 @@ pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec { let Some(sh) = mergeable(e) else { continue }; paths.push(sh.path.transformed(&e.transform)); - let fill = sh.fill.clone().map(|f| index_of(&mut fills, (f, e.color))); - let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (Stroke { width: st.width * e.transform.mean_scale(), ..st }, e.color))); + // Gradients and bitmaps are placed in keyframe space, so every piece shows its + // part of the paint where it was. + let fill = sh.fill.as_ref().map(|f| fill_index(&mut fills, (f.transformed(&e.transform), e.color))); + let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (st.scaled(e.transform.mean_scale()), e.color))); styles.push((fill, stroke, sh.fill_rule)); marked.push(*mark); } @@ -137,9 +163,14 @@ pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec = paths.iter().zip(&styles).map(|(path, &(fill, stroke, fill_rule))| Item { path, fill, fill_rule, stroke }).collect(); - let merged = planar::merge(&items)?; + let merged = match cutter { + Some(c) => planar::merge_cut(&items, c)?, + None => planar::merge(&items)?, + }; + // Item numbers back to part numbers (parts that are not raw shapes made no item). + let part_of: Vec = parts.iter().enumerate().filter(|(_, p)| !matches!(p, Part::Shape(e, _) if mergeable(e).is_none())).map(|(i, _)| i).collect(); let mut out: Vec> = Vec::with_capacity(merged.fills.len() + merged.strokes.len()); - let mut picked = Vec::new(); + let (mut picked, mut inside, mut from) = (Vec::new(), Vec::new(), Vec::new()); for (piece, is_fill) in merged.fills.iter().map(|p| (p, true)).chain(merged.strokes.iter().map(|p| (p, false))) { let (fill, stroke, color) = if is_fill { // Erased regions (and anything without a style) are left out. @@ -151,19 +182,25 @@ pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec, order: Order) { } } +/// The fill table's entry for `v`: paints that differ only by rounding (a gradient carried into a +/// piece and back) are one style, so pieces of one fill join again. +fn fill_index(table: &mut Vec<(Paint, ColorEffect)>, v: (Paint, ColorEffect)) -> u32 { + match table.iter().position(|x| x.1 == v.1 && same_paint(&x.0, &v.0)) { + Some(i) => i as u32, + None => { + table.push(v); + (table.len() - 1) as u32 + } + } +} + +/// Whether two paints look the same (positions within a thousandth of a unit). +pub(crate) fn same_paint(a: &Paint, b: &Paint) -> bool { + const EPS: f32 = 1e-3; + let near = |p: Vec2, q: Vec2| p.distance(q) <= EPS; + match (a, b) { + (Paint::Solid(x), Paint::Solid(y)) => x == y, + (Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => near(*s0, *s1) && near(*e0, *e1) && a == b, + (Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => near(*c0, *c1) && (r0 - r1).abs() <= EPS && a == b, + (Paint::Bitmap { bitmap: b0, repeat: r0, matrix: m0 }, Paint::Bitmap { bitmap: b1, repeat: r1, matrix: m1 }) => { + b0 == b1 && r0 == r1 && m0.m.iter().zip(m1.m).all(|(x, y)| (x - y).abs() <= EPS * x.abs().max(y.abs()).max(1.0)) + } + _ => false, + } +} + fn index_of(table: &mut Vec, v: T) -> u32 { match table.iter().position(|x| *x == v) { Some(i) => i as u32, @@ -208,7 +272,7 @@ fn index_of(table: &mut Vec, v: T) -> u32 { /// `draw.drop`: the selected raw shapes go back into the drawing, on top (Animate merges a moved /// shape when it is let go). fn drop(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); let kf = s.editable_keyframe()?; let mut moving = Vec::new(); kf.elements.retain(|e| { @@ -224,8 +288,128 @@ fn drop(s: &mut Session, _: &Value) -> Result { } let mut keep: Vec = sel.into_iter().filter(|id| !moving.iter().any(|e| e.id == *id)).collect(); keep.extend(merge_in(s, moving)?); - s.selection = keep; - Ok(json!({"dropped": n, "selected": s.selection.iter().map(|e| e.0).collect::>()})) + s.select_only(keep); + Ok(json!({"dropped": n, "selected": s.selection.id_list()})) +} + +// ----- the Paint Bucket and imported drawings (ADR 0042) --------------------------------------- + +/// The probe's fill style: what is left of it after the merge is empty area. +const PROBE: u32 = u32::MAX - 1; + +/// The empty area around `at` that the raw strokes and fills of `els` close off, as Animate's +/// Paint Bucket fills it: exactly up to the lines and fill edges, holes and all. `None` when the +/// raw shapes leave it open (it reaches past them), when `at` is on a fill, or when there is too +/// much to merge at once. +/// +/// A fill under everything (the probe) is merged with the raw shapes: what remains of it are the +/// empty areas, divided by every line and fill edge, and the one under `at` is the answer unless +/// it reaches the probe's border. The probe starts as a small window around `at`, with only the +/// shapes that reach into it, and grows while the area reaches its border, so a fill costs what +/// is near it rather than the whole drawing (shapes wholly outside a window cannot touch an area +/// inside it). +pub(crate) fn enclosed_area(els: &[Arc], at: Vec2) -> Option { + let raw: Vec<(&Element, &Shape, Rect)> = els.iter().filter_map(|e| mergeable(e).map(|sh| (e.as_ref(), sh, reach(sh, &e.transform)))).collect(); + let area = raw.iter().fold(Rect::EMPTY, |r, (_, _, b)| r.union(b)); + if area.is_empty() || !area.contains(at) { + return None; + } + let all = area.inflate(8.0); + let mut half = 64.0f32; + loop { + let window = Rect::new(at.x - half, at.y - half, at.x + half, at.y + half); + let last = window.min.x <= all.min.x && window.min.y <= all.min.y && window.max.x >= all.max.x && window.max.y >= all.max.y; + let outer = if last { all } else { window }; + let near: Vec<&(&Element, &Shape, Rect)> = raw.iter().filter(|(_, _, b)| !b.intersect(&outer).is_empty()).collect(); + match probe(&near, &outer, at)? { + Some(path) => return Some(path), + None if last => return None, + // It reaches the window's border: look wider. + None => half *= 4.0, + } + } +} + +/// One probe merge over `outer`: `Some(Some(area))` when the empty area at `at` is closed off +/// inside it, `Some(None)` when it reaches the border, `None` when `at` is not in an empty area +/// or the merge declines. +fn probe(raw: &[&(&Element, &Shape, Rect)], outer: &Rect, at: Vec2) -> Option> { + let rect = Path::rect(outer.min.x, outer.min.y, outer.width(), outer.height()); + let paths: Vec = raw.iter().map(|(e, sh, _)| sh.path.transformed(&e.transform)).collect(); + let mut items = vec![Item { path: &rect, fill: Some(PROBE), fill_rule: anicraft_geom::FillRule::NonZero, stroke: None }]; + for (i, ((_, sh, _), path)) in raw.iter().map(|x| **x).zip(&paths).enumerate() { + let n = u32::try_from(i).ok()?; + items.push(Item { path, fill: sh.fill.as_ref().map(|_| n), fill_rule: sh.fill_rule, stroke: sh.stroke.as_ref().map(|_| n) }); + } + let merged = planar::merge(&items)?; + let piece = merged.fills.into_iter().find(|p| p.style == PROBE && p.path.contains(at, &Affine::IDENTITY, anicraft_geom::FillRule::default()))?; + let b = piece.path.bounds(); + let open = b.min.x <= outer.min.x + 1.0 || b.min.y <= outer.min.y + 1.0 || b.max.x >= outer.max.x - 1.0 || b.max.y >= outer.max.y - 1.0; + Some((!open).then_some(piece.path)) +} + +/// Merges every keyframe's raw shapes in `doc` into one merged drawing each (scenes and +/// symbols): what an imported Animate file's raw shapes need, as their styles arrive one shape +/// per style. Keyframes with too much to merge at once keep their shapes as they are. Returns +/// how many keyframes changed. +pub(crate) fn merge_document(doc: &mut Document) -> usize { + let mut n = 0; + let mut scenes = doc.scenes.clone(); + for sc in scenes.iter_mut() { + let mut tl = sc.timeline.clone(); + let k = merge_timeline(doc, &mut tl); + if k > 0 { + Arc::make_mut(sc).timeline = tl; + n += k; + } + } + let mut library = doc.library.clone(); + for sym in library.iter_mut() { + let mut tl = sym.timeline.clone(); + let k = merge_timeline(doc, &mut tl); + if k > 0 { + Arc::make_mut(sym).timeline = tl; + n += k; + } + } + if n > 0 { + doc.scenes = scenes; + doc.library = library; + } + n +} + +fn merge_timeline(doc: &mut Document, tl: &mut Timeline) -> usize { + let mut n = 0; + for layer in tl.layers.iter_mut() { + if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| mergeable(e).is_some())) { + continue; + } + let layer = Arc::make_mut(layer); + // A tween pairs its keyframes' shapes in order, so the keyframes it joins keep theirs. + let shape_tween = |k: &anicraft_doc::Keyframe| k.tween.is_some() || k.motion.is_some(); + let morphing: Vec = (0..layer.keyframes.len()).map(|i| layer.keyframes.get(i).is_some_and(|k| shape_tween(k)) || i.checked_sub(1).and_then(|j| layer.keyframes.get(j)).is_some_and(|k| shape_tween(k))).collect(); + for (kf, morph) in layer.keyframes.iter_mut().zip(morphing) { + let idx: Vec = kf.elements.iter().enumerate().filter(|(_, e)| mergeable(e).is_some()).map(|(i, _)| i).collect(); + if idx.is_empty() || morph { + continue; + } + let kf = Arc::make_mut(kf); + let existing = kf.elements.clone(); + let parts: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), false)).collect(); + let Some(rm) = remerge_doc(doc, &parts, None) else { continue }; + let at = idx.first().copied().unwrap_or(0); + for &i in idx.iter().rev() { + if i < kf.elements.len() { + kf.elements.remove(i); + } + } + let at = at.min(kf.elements.len()); + kf.elements.splice(at..at, rm.out); + n += 1; + } + } + n } /// The ends of every open subpath (where raw strokes join), in keyframe space. @@ -305,10 +489,6 @@ fn select_connected(s: &mut Session, p: &Value) -> Result { if !add { s.selection.clear(); } - for id in picked { - if !s.selection.contains(&id) { - s.selection.push(id); - } - } - Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>()})) + s.selection.extend_on(s.layer, picked); + Ok(json!({"selected": s.selection.id_list()})) } diff --git a/crates/engine/src/merge_tests.rs b/crates/engine/src/merge_tests.rs index 7a787c59..b25aa588 100644 --- a/crates/engine/src/merge_tests.rs +++ b/crates/engine/src/merge_tests.rs @@ -125,3 +125,19 @@ fn double_click_selects_connected_strokes_or_a_fill_with_its_outline() { let r = run(&mut s, "element.select_connected", json!({"x": 350, "y": 0})); assert_eq!(r["selected"].as_array().map(Vec::len), Some(1)); } + +#[test] +fn dashed_raw_strokes_keep_their_style_when_cut() { + let mut s = blank(); + // A dashed, butt-capped, mitred square outline, then a solid line across it. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000", "stroke_width": 2, "cap": "none", "join": "miter", "dash": [6, 3]})); + run(&mut s, "draw.line", json!({"x0": -20, "y0": 50, "x1": 120, "y1": 50, "stroke": "#000000", "stroke_width": 2})); + let strokes: Vec = shapes(&s).into_iter().filter_map(|x| x.stroke).collect(); + let dashed = strokes.iter().filter(|st| st.style.dash == anicraft_doc::Dash::dashed(6.0, 3.0)).count(); + assert!(dashed >= 5, "the cut sides are pieces, all still dashed: {dashed} of {}", strokes.len()); + assert!(strokes.iter().filter(|st| st.style.dash.is_some()).all(|st| st.style.cap == anicraft_doc::Cap::Butt && st.style.join == anicraft_doc::Join::Miter)); + assert!(strokes.iter().any(|st| st.style.is_default()), "the solid line stays solid, a style of its own"); + // Saved and loaded, the pieces keep it. + let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap_or_default()).unwrap_or_default(); + assert_eq!(back, s.doc); +} diff --git a/crates/engine/src/motion_path_tests.rs b/crates/engine/src/motion_path_tests.rs index f01e57b2..b5cd82e2 100644 --- a/crates/engine/src/motion_path_tests.rs +++ b/crates/engine/src/motion_path_tests.rs @@ -154,13 +154,14 @@ fn moving_the_object_on_a_path_reshapes_the_path() { s.set_frame(23); run(&mut s, "element.translate", json!({"dx": 10, "dy": 0})); assert!(pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3); - // In between: the path bends through where the object was put; no key is added. - let before = keys(&s); + // In between: an anchor where the object was put, pinned to that frame (ADR 0049; ADR 0030 + // bent the path instead and added no key). let want = pos(&mut s, 9) + Vec2::new(0.0, 40.0); s.set_frame(9); run(&mut s, "element.translate", json!({"dx": 0, "dy": 40})); - assert!(pos(&mut s, 9).distance(want) < 0.01, "{:?} vs {want:?}", pos(&mut s, 9)); - assert_eq!(keys(&s), before, "the timing keeps its keys"); + assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9)); + assert_eq!(keys(&s), Some(vec![0, 9, 23]), "a position key on the pinned frame"); + assert_eq!(motion(&s).pins, vec![anicraft_doc::Pin { frame: 9, anchor: 1 }]); assert!(pos(&mut s, 0).distance(Vec2::new(0.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3, "the ends stay"); // A drag on the stage is a gesture: one undo step however many moves. let steps = s.history_len(); diff --git a/crates/engine/src/motion_pin_tests.rs b/crates/engine/src/motion_pin_tests.rs new file mode 100644 index 00000000..447f9e5c --- /dev/null +++ b/crates/engine/src/motion_pin_tests.rs @@ -0,0 +1,229 @@ +//! Motion path anchors pinned to frames (ADR 0049) through the command registry: auto-key +//! pinning where the object is put, `motion.pin_point` / `motion.unpin_point`, the X/Y keys of a +//! pinned frame as its anchor's place, point edits keeping pins on their anchors, F6, undo and +//! the file round trip. + +use super::*; +use anicraft_doc::{Pin, Property}; +use anicraft_geom::Vec2; +use anicraft_geom::edit::ANCHOR; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn fails(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// A 10 × 10 square centred on (5, 5) with a motion tween over frames 0..24 travelling the hump +/// from (5, 5) up and over to (105, 5), reached on frame 23. +fn on_hump() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s.set_frame(23); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 0})); + s.set_frame(0); + run(&mut s, "motion.set_path", json!({"d": "M5 5 C38 -60 72 -60 105 5"})); + s +} + +fn pos(s: &mut Session, frame: u32) -> Vec2 { + s.set_frame(frame); + s.visible_elements().first().map(|e| e.transform.translation()).unwrap_or_default() +} + +fn motion(s: &Session) -> &anicraft_doc::MotionTween { + s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).expect("motion tween") +} + +fn anchor(s: &Session, i: usize) -> Vec2 { + motion(s).path.as_ref().and_then(|p| p.point(i, ANCHOR)).expect("anchor") +} + +fn key_frames(s: &Session, p: Property) -> Vec { + motion(s).track(p).map(|t| t.keys.iter().map(|k| k.frame).collect()).unwrap_or_default() +} + +#[test] +fn moving_the_object_at_a_middle_frame_pins_an_anchor_there() { + let mut s = on_hump(); + let was = pos(&mut s, 9); + // A drag on the stage: one undo step however many moves, one pin. + let steps = s.history_len(); + s.set_frame(9); + s.begin_gesture("Move"); + for _ in 0..4 { + run(&mut s, "element.translate", json!({"dx": 5, "dy": 10})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + let want = was + Vec2::new(20.0, 40.0); + assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9)); + assert!(anchor(&s, 1).distance(want) < 1e-3, "the new anchor is where the object was put"); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]); + assert!(pos(&mut s, 0).distance(Vec2::new(5.0, 5.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 5.0)) < 1e-3, "the ends stay"); + // motion.info reports every anchor tied to a frame, ends included. + let info = run(&mut s, "motion.info", json!({})); + let pins: Vec<(u64, u64, bool)> = info["pins"].as_array().unwrap().iter().map(|p| (p["anchor"].as_u64().unwrap(), p["frame"].as_u64().unwrap(), p["end"].as_bool().unwrap())).collect(); + assert_eq!(pins, vec![(0, 0, true), (1, 9, false), (2, 23, true)]); + // A later frame pins a later anchor; the first pin holds. + s.set_frame(16); + run(&mut s, "element.translate", json!({"dx": 0, "dy": -30})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }, Pin { frame: 16, anchor: 2 }]); + assert!(pos(&mut s, 9).distance(want) < 1e-3); + assert!(pos(&mut s, 16).distance(anchor(&s, 2)) < 1e-3); + // Undo takes the pin back with its anchor and keys. + s.undo().expect("undo"); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]); + assert_eq!(key_frames(&s, Property::X), vec![0, 9, 23]); +} + +#[test] +fn moving_after_the_last_position_key_carries_the_path_on() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s.set_frame(12); + run(&mut s, "element.translate", json!({"dx": 60, "dy": 0})); + run(&mut s, "motion.set_path", json!({"d": "M5 5 C25 -30 45 -30 65 5"})); + let before: Vec = (0..=12).map(|f| pos(&mut s, f)).collect(); + s.set_frame(20); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 40})); + assert!(pos(&mut s, 20).distance(Vec2::new(105.0, 45.0)) < 1e-3); + assert_eq!(motion(&s).position_range(), Some((0, 20))); + assert_eq!(motion(&s).pins, vec![Pin { frame: 12, anchor: 1 }], "the old end stays pinned to its frame"); + for (f, b) in before.iter().enumerate() { + assert!(pos(&mut s, f as u32).distance(*b) < 1e-2, "frame {f} as it was"); + } +} + +#[test] +fn pin_and_unpin_an_anchor_by_command() { + let mut s = on_hump(); + let v = run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5})); + assert_eq!(v["anchor"], 1); + let unpinned = motion(&s).clone(); + let off = pos(&mut s, 6); + assert!(off.distance(anchor(&s, 1)) > 5.0, "an anchor alone is reached when the timing says"); + let steps = s.history_len(); + let v = run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6})); + assert_eq!(s.history_len(), steps + 1); + assert_eq!((v["anchor"].as_u64(), v["frame"].as_u64()), (Some(1), Some(6))); + assert_eq!(v["pins"].as_array().map(Vec::len), Some(3)); + assert!(pos(&mut s, 6).distance(anchor(&s, 1)) < 1e-3, "passed exactly on its frame"); + assert_eq!(key_frames(&s, Property::Y), vec![0, 6, 23]); + // What can't be pinned is refused with the reason. + assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 0, "frame": 6})).contains("always pinned")); + assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 7, "frame": 6})).contains("no such anchor")); + assert!(fails(&mut s, "motion.unpin_point", json!({"anchor": 2})).contains("always pinned")); + assert!(fails(&mut s, "motion.unpin_point", json!({"frame": 3})).contains("no anchor is pinned to frame 4")); + // Unpinning (by anchor or by frame) gives the tween back as it was. + run(&mut s, "motion.unpin_point", json!({"anchor": 1})); + assert_eq!(*motion(&s), unpinned); + assert!(pos(&mut s, 6).distance(off) < 1e-3, "ADR 0038's timing again"); + run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6})); + run(&mut s, "motion.unpin_point", json!({"frame": 6})); + assert_eq!(*motion(&s), unpinned); +} + +#[test] +fn pin_point_without_an_anchor_pins_where_the_object_is() { + let mut s = on_hump(); + let was = pos(&mut s, 10); + let v = run(&mut s, "motion.pin_point", json!({"frame": 10})); + assert_eq!(v["anchor"], 1); + assert!(pos(&mut s, 10).distance(was) < 0.01, "nothing moves on that frame"); + assert!(anchor(&s, 1).distance(was) < 0.01); + // Outside the motion, or on an end: refused. + assert!(fails(&mut s, "motion.pin_point", json!({"frame": 0})).contains("outside the motion")); + // A straight motion's middle keys are pinned as soon as its path is the tween's own. + let mut t = Session::default(); + run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut t, "timeline.create_motion_tween", json!({})); + t.set_frame(10); + run(&mut t, "element.translate", json!({"dx": 100, "dy": 0})); + t.set_frame(20); + run(&mut t, "element.translate", json!({"dx": 0, "dy": 100})); + let info = run(&mut t, "motion.info", json!({})); + assert_eq!(info["pins"].as_array().map(Vec::len), Some(3), "shown pinned while straight"); + run(&mut t, "motion.pin_point", json!({"frame": 15})); + assert_eq!(motion(&t).pins, vec![Pin { frame: 10, anchor: 1 }, Pin { frame: 15, anchor: 2 }]); +} + +#[test] +fn a_pinned_frames_x_and_y_keys_are_its_anchors_place() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 8})); + let a = anchor(&s, 1); + // The Motion Editor sets X on the pinned frame: the anchor moves, and the object with it. + let v = run(&mut s, "motion.set_key", json!({"property": "x", "frame": 8, "value": a.x + 12.0})); + assert_eq!(v["anchor"], 1); + assert!(anchor(&s, 1).distance(a + Vec2::new(12.0, 0.0)) < 1e-3); + assert!(pos(&mut s, 8).distance(a + Vec2::new(12.0, 0.0)) < 1e-3); + // And the ends: X on the last frame moves the path's end. + run(&mut s, "motion.set_key", json!({"property": "y", "frame": 23, "value": 25.0})); + assert!(anchor(&s, 2).distance(Vec2::new(105.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 25.0)) < 1e-3); + // Removing the pinned frame's X key lets the pin go, with its Y key. + let v = run(&mut s, "motion.remove_key", json!({"property": "x", "frame": 8})); + assert_eq!(v["unpinned"], 1); + assert_eq!(v["removed"], json!(["x", "y"])); + assert!(motion(&s).pins.is_empty() && !key_frames(&s, Property::Y).contains(&8)); +} + +#[test] +fn point_edits_keep_pins_on_their_anchors() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 14})); + let pinned = anchor(&s, 1); + // A point added before the pinned anchor: the pin follows it to index 2. + run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 2 }]); + assert!(pos(&mut s, 14).distance(pinned) < 1e-3); + // Deleting the point before it keeps the pin; deleting the pinned point lets it go. + let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + assert_eq!(v["unpinned"], 0); + assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 1 }]); + assert!(pos(&mut s, 14).distance(pinned) < 1e-3); + let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + assert_eq!(v["unpinned"], 1); + assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X) == vec![0, 23], "its keys went with it"); + // Straighten forgets the pins; their keys stay as the straight path's corners. + run(&mut s, "motion.pin_point", json!({"frame": 14})); + run(&mut s, "motion.clear_path", json!({})); + assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X).contains(&14)); +} + +#[test] +fn insert_keyframe_inside_a_path_tween_pins_the_path_there() { + let mut s = on_hump(); + let was = pos(&mut s, 11); + s.set_frame(11); + run(&mut s, "timeline.insert_keyframe", json!({})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 11, anchor: 1 }]); + assert!(pos(&mut s, 11).distance(was) < 0.01, "{:?} vs {was:?}", pos(&mut s, 11)); + assert!(key_frames(&s, Property::Rotation).contains(&11), "every other property keyed too"); +} + +#[test] +fn pins_round_trip_through_the_file_format() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 7})); + let text = format::to_json(&s.doc).expect("save"); + assert!(text.contains("\"pins\"")); + let back = format::from_json(&text).expect("load"); + assert_eq!(back, s.doc); + // A path tween from before pins writes none and reads back the same. + let plain = on_hump(); + let text = format::to_json(&plain.doc).expect("save"); + assert!(!text.contains("\"pins\"")); + assert_eq!(format::from_json(&text).expect("load"), plain.doc); +} diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs new file mode 100644 index 00000000..932b58ab --- /dev/null +++ b/crates/engine/src/onion.rs @@ -0,0 +1,544 @@ +//! Onion skin and Edit Multiple Frames (ADR 0047). +//! +//! **Onion skin** draws the frames around the playhead under it, faded: frames before it in the +//! *past* colour, frames after it in the *future* colour, each fainter the farther it is (when +//! fading is on). Which frames are shown is set by two markers: they follow the playhead +//! (`before` and `after` frames of it) or stay where they were put (anchored). Options: tint or +//! the artwork's own colours, outlines only, keyframes only. +//! +//! **Edit Multiple Frames** shows the artwork on every keyframe within the markers at full +//! strength, as if on one frame, and `frames.edit_multiple` moves it: the elements chosen (or all +//! of them) on each of those keyframes, as one undo step. +//! +//! Both are *view* settings: the shell keeps an [`OnionSkin`] and passes it with each render job +//! (keyed by [`OnionSkin::key`], so the frame cache keeps working), and the composition here is a +//! pure function of the document, the frame and the settings. Only the moves change the +//! document, through the command. +//! +//! Behaviour learned from Adobe's public help pages on onion skinning and from watching the +//! program; nothing was copied. + +use crate::params::*; +use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session}; +use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; +use anicraft_geom::{Affine, Rect, Vec2}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, HashSet}; +use std::hash::{Hash, Hasher}; + +/// Most frames onion skin or Edit Multiple Frames draws besides the playhead's (the nearest +/// ones are kept): each is one more evaluation of the scene. +pub const MAX_EXTRA_FRAMES: usize = 120; +/// Opacity of the nearest onion frame, and of the farthest when fading by distance. +pub const NEAR_ALPHA: f32 = 0.5; +pub const FAR_ALPHA: f32 = 0.12; +/// How much of the past or future colour tints an onion frame (the rest is its own colour, so +/// fills and lines inside it stay apart). +pub const TINT_AMOUNT: f32 = 0.8; +/// The marker presets (Onion 2, Onion 5): frames on each side of the playhead. +pub const PRESETS: [u32; 2] = [2, 5]; + +/// Where the onion markers are. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Markers { + /// `before` frames before the playhead to `after` frames after it, following it. + Relative { before: u32, after: u32 }, + /// Fixed frames (0-based, inclusive), whatever the playhead does. `last` beyond the end + /// reaches the end however long the timeline gets (Onion All). + Anchored { first: u32, last: u32 }, +} + +/// Onion skin and Edit Multiple Frames settings (view state the shell owns). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OnionSkin { + /// Onion skin is on: frames around the playhead show under it. + pub ghosts: bool, + /// Edit Multiple Frames is on: keyframes within the markers show at full strength (and + /// onion frames are not drawn). + pub edit_multiple: bool, + pub markers: Markers, + /// Tint onion frames with `past` and `future`; off, they keep their own colours. + pub tint: bool, + pub past: Rgba, + pub future: Rgba, + /// Fainter with distance from the playhead; off, every onion frame has [`NEAR_ALPHA`]. + pub fade: bool, + /// Onion frames as hairline outlines in their colour. + pub outlines: bool, + /// Only frames where a keyframe starts (on each layer, its own keyframes). + pub keyframes_only: bool, +} + +impl Default for OnionSkin { + fn default() -> Self { + OnionSkin { + ghosts: true, + edit_multiple: false, + markers: Markers::Relative { before: 2, after: 2 }, + tint: true, + past: Rgba::hex(0x4f8dff), + future: Rgba::hex(0x4cd07d), + fade: true, + outlines: false, + keyframes_only: false, + } + } +} + +/// Most frames a marker reaches from the playhead. +pub const MAX_REACH: u32 = MAX_FRAME; + +impl OnionSkin { + /// Whether it changes what the stage shows. + pub fn shows(&self) -> bool { + self.ghosts || self.edit_multiple + } + + /// The frames within the markers (0-based, inclusive) for a timeline of `frames` frames + /// with the playhead on `playhead`: always inside the timeline, `first <= last`. + pub fn range(&self, playhead: u32, frames: u32) -> (u32, u32) { + let end = frames.max(1) - 1; + match self.markers { + Markers::Relative { before, after } => { + let p = playhead.min(end); + (p.saturating_sub(before.min(MAX_REACH)), p.saturating_add(after.min(MAX_REACH)).min(end)) + } + Markers::Anchored { first, last } => { + let (a, b) = (first.min(last), first.max(last)); + (a.min(end), b.min(end)) + } + } + } + + /// Anchors the markers where they are now (`on`), or makes them follow the playhead again, + /// the same distance from it (a marker the playhead has passed is moved onto it). + pub fn set_anchored(&mut self, on: bool, playhead: u32, frames: u32) { + let (first, last) = self.range(playhead, frames); + self.markers = match (on, self.markers) { + (true, Markers::Relative { .. }) => Markers::Anchored { first, last }, + (false, Markers::Anchored { .. }) => { + let p = playhead.min(frames.max(1) - 1); + Markers::Relative { before: p.saturating_sub(first), after: last.saturating_sub(p) } + } + (_, m) => m, + }; + } + + pub fn anchored(&self) -> bool { + matches!(self.markers, Markers::Anchored { .. }) + } + + /// Onion 2 / Onion 5: `n` frames on each side, following the playhead. + pub fn preset(&mut self, n: u32) { + self.markers = Markers::Relative { before: n.min(MAX_REACH), after: n.min(MAX_REACH) }; + } + + /// Onion All: the whole timeline, however long it gets. + pub fn all(&mut self) { + self.markers = Markers::Anchored { first: 0, last: MAX_FRAME }; + } + + /// Whether the markers are Onion All's. + pub fn is_all(&self) -> bool { + self.markers == Markers::Anchored { first: 0, last: MAX_FRAME } + } + + /// Moves the start marker (`start`) or the end marker to frame `to`, keeping the range on + /// the right side of the playhead when relative, and never past the other marker. + pub fn drag_marker(&mut self, start: bool, to: u32, playhead: u32, frames: u32) { + let end = frames.max(1) - 1; + let to = to.min(end); + let (first, last) = self.range(playhead, frames); + let p = playhead.min(end); + self.markers = match self.markers { + Markers::Relative { after, .. } if start => Markers::Relative { before: p.saturating_sub(to.min(p)), after }, + Markers::Relative { before, .. } => Markers::Relative { before, after: to.max(p) - p }, + Markers::Anchored { .. } if start => Markers::Anchored { first: to.min(last), last }, + Markers::Anchored { .. } => Markers::Anchored { first, last: to.max(first) }, + }; + } + + /// Opacity of an onion frame `distance` frames from the playhead, on a side whose marker + /// is `reach` frames away. + pub fn alpha(&self, distance: u32, reach: u32) -> f32 { + if !self.fade || reach <= 1 { + return NEAR_ALPHA; + } + let t = (distance.saturating_sub(1) as f32 / (reach - 1) as f32).clamp(0.0, 1.0); + NEAR_ALPHA * (1.0 - t) + FAR_ALPHA * t + } + + /// The colour effect an onion frame gets, and the outline colour (when outlines are on). + pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorEffect, Option) { + let alpha = self.alpha(distance, reach); + let color = if past { self.past } else { self.future }; + let (tint, tint_amount) = if self.tint { (color, TINT_AMOUNT) } else { (Rgba::WHITE, 0.0) }; + let outline = self.outlines.then(|| color.with_alpha(alpha * color.a.clamp(0.0, 1.0))); + (ColorEffect { alpha, tint, tint_amount }, outline) + } + + /// A hash of everything that changes the picture, for render-cache keys. + pub fn key(&self) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (self.ghosts, self.edit_multiple, self.markers, self.tint, self.fade, self.outlines, self.keyframes_only).hash(&mut h); + for c in [self.past, self.future] { + [c.r, c.g, c.b, c.a].map(f32::to_bits).hash(&mut h); + } + h.finish() + } +} + +/// One extra frame to draw under the playhead's: frame `frame`, only `layers`' artwork. +#[derive(Clone, Debug, PartialEq)] +pub struct Extra { + pub frame: u32, + pub layers: Vec, + /// An onion frame before the playhead (`Some(true)`), after it (`Some(false)`), or an Edit + /// Multiple Frames keyframe at full strength (`None`). + pub past: Option, + /// Frames from the playhead. + pub distance: u32, +} + +/// Whether onion skin draws `layer` (Animate doesn't onion-skin locked layers). +fn ghosted(tl: &Timeline, i: usize) -> bool { + tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder && !tl.locked_by_folder(l.id) && !tl.hidden_by_folder(i)) +} + +/// Whether Edit Multiple Frames shows and edits `layer`'s other keyframes: it is shown and +/// unlocked, and holds artwork (not a folder, the camera or an armature posed by its bones). +pub fn multi_editable(tl: &Timeline, i: usize) -> bool { + ghosted(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature)) +} + +/// The onion frames to draw for the playhead on `playhead`, farthest first (nearest on top), +/// past and future taking turns at each distance. +pub fn onion_frames(tl: &Timeline, playhead: u32, skin: &OnionSkin) -> Vec { + let (first, last) = skin.range(playhead, tl.frame_count()); + let layers: Vec = (0..tl.layers.len()).filter(|&i| ghosted(tl, i)).collect(); + if layers.is_empty() { + return Vec::new(); + } + let mut out: Vec = Vec::new(); + // Nearest first, so the cap keeps the nearest; reversed at the end. + let reach = playhead.saturating_sub(first).max(last.saturating_sub(playhead)); + for d in 1..=reach { + if out.len() >= MAX_EXTRA_FRAMES { + break; + } + // Future first: the list is reversed below, so at each distance the past frame is drawn + // first. + for (past, f) in [(false, playhead.checked_add(d)), (true, playhead.checked_sub(d))] { + let Some(f) = f.filter(|f| (first..=last).contains(f)) else { continue }; + let ids: Vec = if skin.keyframes_only { + // A layer's keyframe starting there; the one the playhead is on only when it + // tweens (otherwise it looks the same as the playhead's frame). + layers.iter().filter_map(|&i| tl.layers.get(i)).filter(|l| l.keyframe_starting_at(f).and_then(|k| l.keyframes.get(k)).is_some_and(|k| !k.covers(playhead) || k.tween.is_some() || k.motion.is_some())).map(|l| l.id).collect() + } else { + layers.iter().filter_map(|&i| tl.layers.get(i)).map(|l| l.id).collect() + }; + if !ids.is_empty() && out.len() < MAX_EXTRA_FRAMES { + out.push(Extra { frame: f, layers: ids, past: Some(past), distance: d }); + } + } + } + out.reverse(); + out +} + +/// The keyframes Edit Multiple Frames draws besides the playhead's: on each editable layer, +/// every keyframe whose span reaches into `first..=last` except the one under the playhead, +/// drawn as it looks on its first frame. Grouped by that frame, in frame order. +pub fn multi_frames(tl: &Timeline, playhead: u32, first: u32, last: u32) -> Vec { + let mut at: BTreeMap> = BTreeMap::new(); + for (i, l) in tl.layers.iter().enumerate() { + if !multi_editable(tl, i) { + continue; + } + for k in l.keyframes.iter().filter(|k| k.start <= last && k.end() > first && !k.covers(playhead)) { + at.entry(k.start).or_default().push(l.id); + } + } + let mut out: Vec = at.into_iter().map(|(frame, layers)| Extra { frame, layers, past: None, distance: frame.abs_diff(playhead) }).collect(); + if out.len() > MAX_EXTRA_FRAMES { + // Keep the nearest, still in frame order. + let mut by: Vec = out.iter().map(|e| e.distance).collect(); + by.sort_unstable(); + let cut = by.get(MAX_EXTRA_FRAMES - 1).copied().unwrap_or(0); + let mut kept = 0usize; + out.retain(|e| { + let keep = e.distance <= cut && kept < MAX_EXTRA_FRAMES; + kept += usize::from(keep); + keep + }); + } + out +} + +/// Keeps only `layers`' items (and the mask artwork their clips need, which draws nothing). +fn keep_layers(dl: &mut DisplayList, layers: &[LayerId]) { + let set: HashSet = layers.iter().copied().collect(); + dl.items.retain(|i| set.contains(&i.layer) || (i.masks.is_some() && i.group.is_none())); +} + +/// The parts as one list, layer by layer: each layer's items from every part, in part order, +/// then the next layer up. So a frame before or after the playhead shows under the playhead's +/// artwork *on its own layer* and over the layers below, as in Animate, and an opaque +/// background never hides it. Also says which part each item came from. +/// +/// Reordering items is safe: a group's run lies within one layer (it stays unbroken), and the +/// renderers take mask artwork apart from what they draw, whatever its place in the list. +fn interleave(tl: &Timeline, parts: Vec) -> (DisplayList, Vec) { + let n = tl.layers.len(); + let rank: std::collections::HashMap = tl.layers.iter().enumerate().map(|(i, l)| (l.id, i)).collect(); + // Back to front: the bottom layer (the highest index) first; an unknown layer before all. + let bucket = |l: LayerId| rank.get(&l).map_or(0, |r| n - r); + let total = parts.iter().map(|p| p.items.len()).sum(); + let mut dl = DisplayList::default(); + let mut iters = Vec::with_capacity(parts.len()); + for part in parts { + // Clips and groups renumbered as `DisplayList::append` does. + let (base, gbase) = (dl.clip_parents.len() as u32, dl.groups.len() as u32); + let shift = move |c: Option| c.map(|c| c + base); + let gshift = move |g: Option| g.map(|g| g + gbase); + dl.clip_parents.extend(part.clip_parents.into_iter().map(shift)); + dl.groups.extend(part.groups.into_iter().map(|g| anicraft_doc::Group { parent: gshift(g.parent), clip: shift(g.clip), ..g })); + iters.push( + part.items + .into_iter() + .map(move |mut i| { + i.clip = shift(i.clip); + i.masks = shift(i.masks); + i.group = gshift(i.group); + i + }) + .peekable(), + ); + } + // Each part is already back to front, layer by layer: one merge, each item moved once. + let mut items = Vec::with_capacity(total); + let mut from = Vec::with_capacity(total); + for b in 0..=n { + for (k, it) in iters.iter_mut().enumerate() { + while let Some(x) = it.next_if(|x| bucket(x.layer) <= b) { + items.push(x); + from.push(k); + } + } + } + // (Nothing is left unless a part was out of layer order; keep it rather than drop it.) + for (k, it) in iters.into_iter().enumerate() { + for x in it { + items.push(x); + from.push(k); + } + } + dl.items = items; + (dl, from) +} + +/// Scene `scene` at its frame `local` with what `skin` adds (nothing for `None`): onion frames, +/// or Edit Multiple Frames' keyframes, each under the playhead's artwork on its own layer. +/// `eval` evaluates one frame of the scene (with or without its camera). +pub fn compose(doc: &Document, scene: usize, local: u32, skin: Option<&OnionSkin>, eval: impl Fn(usize, u32) -> DisplayList + Sync) -> DisplayList { + let now = eval(scene, local); + let Some(skin) = skin.filter(|s| s.shows()) else { return now }; + let tl = doc.timeline(scene); + let (first, last) = skin.range(local, tl.frame_count()); + let extras = if skin.edit_multiple { multi_frames(tl, local, first, last) } else { onion_frames(tl, local, skin) }; + if extras.is_empty() { + return now; + } + // The frames are independent: evaluated in parallel, kept in order. + use rayon::prelude::*; + let mut parts: Vec = extras.par_iter().map(|e| eval(scene, e.frame)).collect(); + for (part, e) in parts.iter_mut().zip(&extras) { + keep_layers(part, &e.layers); + if let Some(past) = e.past { + let reach = if past { local.saturating_sub(first) } else { last.saturating_sub(local) }; + let (fx, outline) = skin.look(past, e.distance, reach); + for item in &mut part.items { + item.color = item.color.concat(&fx); + if outline.is_some() && item.masks.is_none() { + item.outline = outline; + } + } + } + } + parts.push(now); + interleave(tl, parts).0 +} + +// ----- Edit Multiple Frames: artwork, picking and moves ------------------------------------ + +/// An element on one keyframe: its layer, the keyframe's first frame and its id (an element +/// keeps its id from keyframe to keyframe, so the frame says which copy). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct FrameItem { + pub layer: LayerId, + pub frame: u32, + pub element: ElementId, +} + +impl FrameItem { + pub fn to_json(&self) -> Value { + json!([self.layer.0, self.frame, self.element.0]) + } +} + +impl Session { + /// What Edit Multiple Frames shows in `first..=last`, layer by layer as the stage draws it + /// (each keyframe as it looks on its first frame, the playhead's as it looks there), with + /// the keyframe start of each item's layer (`None`: a layer it doesn't edit). + fn multi_list(&self, first: u32, last: u32) -> (DisplayList, Vec>) { + let tl = self.doc.timeline(self.scene); + let mut parts = Vec::new(); + let mut starts: Vec> = Vec::new(); + for e in multi_frames(tl, self.frame, first, last) { + let mut dl = anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame); + keep_layers(&mut dl, &e.layers); + parts.push(dl); + starts.push(e.layers.iter().map(|l| (*l, e.frame)).collect()); + } + // The playhead's frame: every editable layer, at the start of its keyframe there. + let now: Vec<(LayerId, u32)> = tl.layers.iter().enumerate().filter(|(i, _)| multi_editable(tl, *i)).filter_map(|(_, l)| l.keyframe_at(self.frame).map(|k| (l.id, k.start))).collect(); + let mut dl = (*self.display_list()).clone(); + keep_layers(&mut dl, &now.iter().map(|(l, _)| *l).collect::>()); + parts.push(dl); + starts.push(now); + let (dl, from) = interleave(tl, parts); + let frames = dl.items.iter().zip(&from).map(|(it, &k)| starts.get(k).and_then(|s| s.iter().find(|(l, _)| *l == it.layer)).map(|(_, f)| *f)).collect(); + (dl, frames) + } + + /// Every element Edit Multiple Frames shows in `first..=last`, with its stage bounds (the + /// playhead's elements as they look there), back to front. + pub fn multi_frame_items(&self, first: u32, last: u32) -> Vec<(FrameItem, Rect)> { + let (first, last) = (first.min(last), first.max(last)); + let mut out: Vec<(FrameItem, Rect)> = Vec::new(); + let mut index: std::collections::HashMap = std::collections::HashMap::new(); + let (dl, frames) = self.multi_list(first, last); + { + for (item, frame) in dl.items.iter().zip(frames) { + let Some(frame) = frame else { continue }; + let key = FrameItem { layer: item.layer, frame, element: item.element }; + let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach); + let b = item.path.bounds().inflate(pad).transformed(&item.transform); + match index.get(&key).and_then(|&i| out.get_mut(i)) { + Some((_, r)) => *r = r.union(&b), + None => { + index.insert(key, out.len()); + out.push((key, b)); + } + } + } + } + out + } + + /// The topmost element Edit Multiple Frames shows under `p` in `first..=last`. + pub fn multi_frame_pick(&self, first: u32, last: u32, p: Vec2, slop: f32) -> Option { + let (first, last) = (first.min(last), first.max(last)); + let (dl, frames) = self.multi_list(first, last); + let i = crate::pick_index(&dl, p, slop, |i, _| frames.get(i).copied().flatten().is_some())?; + let item = dl.items.get(i)?; + Some(FrameItem { layer: item.layer, frame: frames.get(i).copied().flatten()?, element: item.element }) + } +} + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("frames.artwork", "Artwork on Multiple Frames", "", None, "{first, last} lists every element Edit Multiple Frames shows in frames first..=last (0-based): [layer, frame (its keyframe's first frame), id] with stage bounds; the playhead's elements as they look there", false, artwork as crate::RunFn), + c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..]} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; one undo step", true, edit_multiple), + ] +} + +/// The `first` and `last` params, in order. +fn range_param(p: &Value) -> Result<(u32, u32)> { + let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)"))); + let (a, b) = (req("first")?, req("last")?); + if a.max(b) > MAX_FRAME { + return Err(EngineError::Param(format!("frames go up to {MAX_FRAME}"))); + } + Ok((a.min(b), a.max(b))) +} + +fn artwork(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let items: Vec = s.multi_frame_items(first, last).into_iter().map(|(it, b)| json!({"layer": it.layer.0, "frame": it.frame, "id": it.element.0, "bounds": [b.min.x, b.min.y, b.max.x, b.max.y]})).collect(); + Ok(json!({"first": first, "last": last, "items": items})) +} + +/// Most items `frames.edit_multiple` takes. +const MAX_ITEMS: usize = 100_000; + +fn items_param(p: &Value) -> Result>> { + let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) }; + let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into()); + let list = v.as_array().ok_or_else(bad)?; + if list.len() > MAX_ITEMS { + return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items"))); + } + list.iter() + .map(|t| { + let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?; + let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad); + let frame = u32::try_from(n(1)?).map_err(|_| bad())?; + Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) }) + }) + .collect::>>() + .map(Some) +} + +fn edit_multiple(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); + if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT { + return Err(EngineError::Param("the move is too large".into())); + } + let shown: Vec = s.multi_frame_items(first, last).into_iter().map(|(it, _)| it).collect(); + let items = match items_param(p)? { + Some(list) => { + let have: HashSet = shown.iter().copied().collect(); + if let Some(bad) = list.iter().find(|it| !have.contains(it)) { + return Err(EngineError::State(format!( + "element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)", + bad.element.0, bad.layer.0, bad.frame + ))); + } + list + } + None => shown, + }; + // One pass per keyframe: (layer, keyframe start) → its ids. + let mut by_key: BTreeMap<(LayerId, u32), HashSet> = BTreeMap::new(); + for it in &items { + by_key.entry((it.layer, it.frame)).or_default().insert(it.element); + } + let mv = Affine::translate(d.x, d.y); + let mut moved = 0usize; + for ((layer, start), ids) in &by_key { + let l = s.layer_mut(Some(*layer))?; + let Some(ki) = l.keyframe_starting_at(*start) else { continue }; + let Some(kf) = l.keyframe_mut(ki) else { continue }; + // A motion tween's object carries its path and X/Y keys along (refused, with nothing + // changed, if they would leave the stage's range). + if let Some(m) = kf.motion.as_mut() + && ids.contains(&m.target) + && d != Vec2::ZERO + && !m.translate(d) + { + return Err(EngineError::State("the motion path would move out of range".into())); + } + for e in kf.elements_mut_where(|id| ids.contains(&id)) { + e.transform = mv.mul(&e.transform); + moved += 1; + } + } + Ok(json!({"moved": moved, "keyframes": by_key.len(), "dx": d.x, "dy": d.y})) +} + +#[cfg(test)] +#[path = "onion_tests.rs"] +mod tests; diff --git a/crates/engine/src/onion_tests.rs b/crates/engine/src/onion_tests.rs new file mode 100644 index 00000000..014bc507 --- /dev/null +++ b/crates/engine/src/onion_tests.rs @@ -0,0 +1,431 @@ +//! Onion skin and Edit Multiple Frames (ADR 0047): markers, tint and fade, outlines, keyframes +//! only, the composed display list and its render, and moves on several keyframes. + +use super::*; +use crate::Session; +use anicraft_doc::{DisplayItem, ElementId, LayerId, Rgba, evaluate_scene, sample}; +use anicraft_render::{View, render}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// One layer, a 20 × 20 drawing object walking right: keyframes on frames 0, 4 and 8 (the last +/// one frame long) with it at x = 10, 50 and 90 (y = 10). The playhead is on frame 4. +fn walk() -> (Session, LayerId, ElementId) { + let mut s = Session::default(); + let layer = s.layer; + let id = ElementId(run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()); + for f in [4, 8] { + run(&mut s, "timeline.goto", json!({"frame": f})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [id.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + run(&mut s, "timeline.goto", json!({"frame": 4})); + assert_eq!(s.frame_count(), 9); + (s, layer, id) +} + +/// The left edge of `id` on the keyframe of `layer` starting at `start`. +fn x_at(s: &Session, layer: LayerId, start: u32, id: ElementId) -> f32 { + let l = s.doc.timeline(s.scene).layer(layer).unwrap(); + let k = l.keyframes.iter().find(|k| k.start == start).unwrap(); + let e = k.elements.iter().find(|e| e.id == id).unwrap(); + e.bounds(&s.doc).min.x +} + +fn left(i: &DisplayItem) -> f32 { + i.path.bounds().transformed(&i.transform).min.x +} + +#[test] +fn markers_stay_inside_the_timeline() { + let mut o = OnionSkin::default(); + assert_eq!(o.range(0, 10), (0, 2), "nothing before frame 1"); + assert_eq!(o.range(9, 10), (7, 9), "nothing after the last frame"); + assert_eq!(o.range(50, 10), (7, 9), "a playhead past the end counts as the last frame"); + assert_eq!(o.range(0, 0), (0, 0)); + o.markers = Markers::Relative { before: u32::MAX, after: u32::MAX }; + assert_eq!(o.range(5, 10), (0, 9)); + o.markers = Markers::Anchored { first: 8, last: 3 }; + assert_eq!(o.range(0, 10), (3, 8), "anchored markers in order, whatever the playhead"); + o.markers = Markers::Anchored { first: 400, last: 900 }; + assert_eq!(o.range(0, 10), (9, 9)); + o.all(); + assert!(o.is_all() && o.anchored()); + assert_eq!(o.range(4, 10), (0, 9)); + assert_eq!(o.range(4, 500), (0, 499), "Onion All grows with the timeline"); + o.preset(5); + assert!(!o.anchored() && !o.is_all()); + assert_eq!(o.range(10, 100), (5, 15)); +} + +#[test] +fn markers_drag_and_anchor() { + let mut o = OnionSkin::default(); + o.drag_marker(true, 1, 6, 20); + assert_eq!(o.range(6, 20), (1, 8)); + o.drag_marker(true, 9, 6, 20); + assert_eq!(o.range(6, 20), (6, 8), "the start marker stops at the playhead"); + o.drag_marker(false, 50, 6, 20); + assert_eq!(o.range(6, 20), (6, 19), "the end marker stops at the last frame"); + o.drag_marker(false, 2, 6, 20); + assert_eq!(o.range(6, 20), (6, 6)); + // Anchoring keeps the frames; the playhead then moves without them. + o.preset(2); + o.set_anchored(true, 6, 20); + assert_eq!((o.range(6, 20), o.range(15, 20)), ((4, 8), (4, 8))); + o.drag_marker(true, 12, 15, 20); + assert_eq!(o.range(15, 20), (8, 8), "never past the other marker"); + o.drag_marker(false, 3, 15, 20); + assert_eq!(o.range(15, 20), (8, 8)); + o.drag_marker(false, 12, 15, 20); + assert_eq!(o.range(15, 20), (8, 12)); + // Following the playhead again: the same distances from it... + o.set_anchored(false, 10, 20); + assert_eq!(o.markers, Markers::Relative { before: 2, after: 2 }); + // ...and a marker the playhead has passed lands on it. + o.set_anchored(true, 10, 20); + o.set_anchored(false, 15, 20); + assert_eq!(o.range(15, 20), (8, 15)); +} + +#[test] +fn onion_frames_fade_by_distance_in_their_colours() { + let o = OnionSkin::default(); + assert_eq!(o.alpha(1, 5), NEAR_ALPHA); + assert_eq!(o.alpha(5, 5), FAR_ALPHA); + assert!((o.alpha(3, 5) - (NEAR_ALPHA + FAR_ALPHA) / 2.0).abs() < 1e-6); + assert!((1..5).all(|d| o.alpha(d, 5) > o.alpha(d + 1, 5)), "fainter with each frame"); + assert_eq!(o.alpha(1, 1), NEAR_ALPHA); + assert_eq!(o.alpha(9, 5), FAR_ALPHA, "never fainter than the farthest"); + let flat = OnionSkin { fade: false, ..o }; + assert!((1..=5).all(|d| flat.alpha(d, 5) == NEAR_ALPHA)); + + let (past, line) = o.look(true, 1, 2); + assert_eq!((past.tint, past.tint_amount, past.alpha, line), (o.past, TINT_AMOUNT, NEAR_ALPHA, None)); + let (future, _) = o.look(false, 2, 2); + assert_eq!((future.tint, future.alpha), (o.future, FAR_ALPHA)); + let (own, _) = OnionSkin { tint: false, ..o }.look(true, 1, 2); + assert_eq!(own.tint_amount, 0.0, "untinted frames keep their own colours"); + let (_, line) = OnionSkin { outlines: true, ..o }.look(false, 2, 2); + assert_eq!(line, Some(o.future.with_alpha(FAR_ALPHA))); +} + +#[test] +fn every_setting_is_in_the_key() { + let o = OnionSkin::default(); + let variants = [ + OnionSkin { ghosts: false, ..o }, + OnionSkin { edit_multiple: true, ..o }, + OnionSkin { markers: Markers::Relative { before: 2, after: 3 }, ..o }, + OnionSkin { markers: Markers::Anchored { first: 0, last: 2 }, ..o }, + OnionSkin { tint: false, ..o }, + OnionSkin { past: Rgba::hex(0x123456), ..o }, + OnionSkin { future: Rgba::hex(0x123456), ..o }, + OnionSkin { fade: false, ..o }, + OnionSkin { outlines: true, ..o }, + OnionSkin { keyframes_only: true, ..o }, + ]; + let mut keys: Vec = variants.iter().map(OnionSkin::key).collect(); + keys.push(o.key()); + let n = keys.len(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), n); + assert_eq!(o.key(), OnionSkin::default().key()); +} + +#[test] +fn onion_frames_come_farthest_first_and_skip_locked_layers() { + let (mut s, a, _) = walk(); + let b = LayerId(run(&mut s, "layer.new", json!({"name": "Locked"}))["layer"].as_u64().unwrap()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 100, "w": 9, "h": 9, "object": true})); + run(&mut s, "timeline.insert_frame", json!({"count": 8})); + run(&mut s, "layer.toggle_lock", json!({"layer": b.0})); + let tl = s.doc.timeline(s.scene); + let got: Vec<(u32, Option, u32)> = onion_frames(tl, 4, &OnionSkin::default()).iter().map(|e| (e.frame, e.past, e.distance)).collect(); + assert_eq!(got, vec![(2, Some(true), 2), (6, Some(false), 2), (3, Some(true), 1), (5, Some(false), 1)]); + assert!(onion_frames(tl, 4, &OnionSkin::default()).iter().all(|e| e.layers == vec![a]), "locked layers are not onion-skinned"); + // At the first frame there is no past. + assert!(onion_frames(tl, 0, &OnionSkin::default()).iter().all(|e| e.past == Some(false))); +} + +#[test] +fn keyframes_only_shows_each_layers_own_keyframes() { + let (mut s, a, _) = walk(); + let b = LayerId(run(&mut s, "layer.new", json!({"name": "B"}))["layer"].as_u64().unwrap()); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 100, "w": 9, "h": 9, "object": true})); + run(&mut s, "timeline.goto", json!({"frame": 2})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "timeline.insert_frame", json!({"count": 6})); + let tl = s.doc.timeline(s.scene); + let skin = OnionSkin { keyframes_only: true, markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }; + let mut got: Vec<(u32, Vec)> = onion_frames(tl, 4, &skin).into_iter().map(|e| (e.frame, e.layers)).collect(); + got.sort_by_key(|(f, _)| *f); + // Frame 0 is a keyframe on both layers, frame 8 on A. B's keyframe on 2 is the one under the + // playhead and doesn't tween: it would only repeat what the playhead shows, so it is left out. + assert_eq!(got, vec![(0, vec![b, a]), (8, vec![a])]); + // With all frames, every frame in range is there. + let all = onion_frames(tl, 4, &OnionSkin { keyframes_only: false, ..skin }).len(); + let (f0, f1) = skin.range(4, tl.frame_count()); + assert_eq!(all as u32, f1 - f0); +} + +#[test] +fn composed_onion_frames_are_tinted_faded_and_under_the_playhead() { + let (s, _, _) = walk(); + let skin = OnionSkin::default(); + let dl = compose(&s.doc, 0, 4, Some(&skin), |sc, f| evaluate_scene(&s.doc, sc, f)); + // Frames 2, 6, 3, 5 under frame 4: the keyframes there hold the rectangle at 10, 50, 10, 50. + let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect(); + assert_eq!(got, vec![(10.0, FAR_ALPHA, TINT_AMOUNT), (50.0, FAR_ALPHA, TINT_AMOUNT), (10.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, 1.0, 0.0)]); + assert_eq!(dl.items.first().map(|i| i.color.tint), Some(skin.past)); + assert_eq!(dl.items.get(1).map(|i| i.color.tint), Some(skin.future)); + // Off, or None: the frame alone. + let off = OnionSkin { ghosts: false, ..skin }; + assert_eq!(compose(&s.doc, 0, 4, Some(&off), |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1); + assert_eq!(compose(&s.doc, 0, 4, None, |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1); +} + +/// The pixel at (x, y), premultiplied RGBA8. +fn px(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] { + let i = ((y * w + x) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] +} + +#[test] +fn outline_mode_draws_onion_frames_as_edges_only() { + let (s, _, _) = walk(); + let view = View { transform: Affine::IDENTITY, width: 120, height: 40, background: Some(Rgba::WHITE) }; + let draw = |skin: &OnionSkin| { + let dl = compose(&s.doc, 0, 4, Some(skin), |sc, f| evaluate_scene(&s.doc, sc, f)); + render(&dl, &view).unwrap().0.to_premul_rgba8() + }; + let filled = draw(&OnionSkin { markers: Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() }); + let lines = draw(&OnionSkin { markers: Markers::Relative { before: 4, after: 0 }, outlines: true, ..OnionSkin::default() }); + const WHITE: [u8; 4] = [255; 4]; + // Inside the onion rectangle (frames 0–3 hold it at 10..30): tinted when filled, the stage + // when outlined; on its left edge (x = 10), the outline shows. + assert_ne!(px(&filled, 120, 20, 20), WHITE); + assert_eq!(px(&lines, 120, 20, 20), WHITE); + assert_ne!(px(&lines, 120, 10, 20), WHITE); + let edge = px(&lines, 120, 10, 20); + assert!(edge[2] > edge[0], "in the past colour (blue): {edge:?}"); + // The playhead's frame (x = 50..70) is drawn as it is, either way. + assert_eq!(px(&lines, 120, 60, 20), [0, 0, 0, 255]); + assert_eq!(px(&filled, 120, 60, 20), [0, 0, 0, 255]); +} + +#[test] +fn edit_multiple_frames_shows_keyframes_within_the_markers_at_full_strength() { + let (mut s, a, id) = walk(); + let tl = s.doc.timeline(s.scene); + let near = OnionSkin { edit_multiple: true, ..OnionSkin::default() }; + // ±2 around 4 is frames 2..6: the keyframe on 0 reaches into it (to frame 3), the one on 8 + // doesn't; the one on 4 is the playhead's. + assert_eq!(multi_frames(tl, 4, 2, 6).iter().map(|e| e.frame).collect::>(), vec![0]); + let dl = compose(&s.doc, 0, 4, Some(&near), |sc, f| evaluate_scene(&s.doc, sc, f)); + assert_eq!(dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect::>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]); + let wide = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..near }; + let dl = compose(&s.doc, 0, 4, Some(&wide), |sc, f| evaluate_scene(&s.doc, sc, f)); + assert_eq!(dl.items.iter().map(left).collect::>(), vec![10.0, 90.0, 50.0], "other keyframes in frame order, the playhead's on top"); + // What it shows is what it lists, each with its keyframe's first frame. + let items: Vec<(FrameItem, f32)> = s.multi_frame_items(0, 8).into_iter().map(|(it, b)| (it, b.min.x)).collect(); + let item = |frame| FrameItem { layer: a, frame, element: id }; + assert_eq!(items, vec![(item(0), 10.0), (item(8), 90.0), (item(4), 50.0)]); + let v = run(&mut s, "frames.artwork", json!({"first": 8, "last": 0})); + assert_eq!(v["items"].as_array().map(Vec::len), Some(3)); + assert_eq!(v["items"][1], json!({"layer": a.0, "frame": 8, "id": id.0, "bounds": [90.0, 10.0, 110.0, 30.0]})); +} + +#[test] +fn a_move_on_multiple_frames_moves_each_keyframe_and_undoes_in_one_step() { + let (mut s, a, id) = walk(); + let steps = s.history_len(); + let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 5, "dy": 7})); + assert_eq!((v["moved"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3))); + assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [15.0, 55.0, 95.0]); + assert_eq!(s.history_len(), steps + 1); + s.undo().unwrap(); + assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [10.0, 50.0, 90.0], "one undo takes back every keyframe"); + // Only the items given. + run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": -10, "dy": 0, "items": [[a.0, 8, id.0]]})); + assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [10.0, 50.0, 80.0]); + // A drag: many small moves in one gesture are one step. + let steps = s.history_len(); + s.begin_gesture("Move"); + for _ in 0..10 { + run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 4, "dx": 1, "dy": 0})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [20.0, 60.0, 80.0], "the keyframe on 8 is outside frames 0..4"); +} + +#[test] +fn moves_refuse_what_edit_multiple_frames_does_not_show() { + let (mut s, a, id) = walk(); + let before = s.doc.clone(); + let e = s.execute("frames.edit_multiple", &json!({"first": 0, "last": 3, "dx": 5, "dy": 0, "items": [[a.0, 8, id.0]]})); + assert!(e.is_err(), "the keyframe on 8 is outside the markers"); + assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 8, 999]]})).is_err()); + assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 8]]})).is_err()); + assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "dx": 5, "dy": 0})).is_err()); + assert!(s.doc == before); + run(&mut s, "layer.toggle_lock", json!({"layer": a.0})); + assert!(s.multi_frame_items(0, 8).is_empty(), "nothing on a locked layer"); + assert_eq!(run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 5, "dy": 0}))["moved"], json!(0)); + assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 0, id.0]]})).is_err()); +} + +#[test] +fn picking_finds_artwork_on_every_keyframe_shown() { + let (s, a, id) = walk(); + let at = |x: f32| s.multi_frame_pick(0, 8, Vec2::new(x, 20.0), 1.0); + assert_eq!(at(100.0), Some(FrameItem { layer: a, frame: 8, element: id })); + assert_eq!(at(60.0), Some(FrameItem { layer: a, frame: 4, element: id })); + assert_eq!(at(20.0), Some(FrameItem { layer: a, frame: 0, element: id })); + assert_eq!(at(150.0), None); + assert_eq!(s.multi_frame_pick(2, 6, Vec2::new(100.0, 20.0), 1.0), None, "outside the markers"); +} + +#[test] +fn a_motion_tweens_path_and_keys_move_with_its_object() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "object": true})); + run(&mut s, "timeline.insert_frame", json!({"count": 9})); + run(&mut s, "timeline.create_motion_tween", json!({})); + run(&mut s, "timeline.goto", json!({"frame": 9})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 0})); + let x_on = |s: &Session, f: u32| evaluate_scene(&s.doc, 0, f).items.first().map(left).unwrap_or(f32::NAN); + let before: Vec = (0..10).map(|f| x_on(&s, f)).collect(); + run(&mut s, "timeline.goto", json!({"frame": 0})); + let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 9, "dx": 10, "dy": 0})); + assert_eq!(v["moved"], json!(1)); + let after: Vec = (0..10).map(|f| x_on(&s, f)).collect(); + for (b, a) in before.iter().zip(&after) { + assert!((a - b - 10.0).abs() < 1e-3, "{before:?} → {after:?}"); + } +} + +#[test] +fn every_setting_composes_and_renders_on_the_sample() { + let doc = sample::demo(); + let n = doc.timeline(0).frame_count(); + let view = View { transform: Affine::scale(0.1, 0.1), width: 128, height: 72, background: Some(doc.stage.background) }; + let mut count = 0; + for bits in 0u32..64 { + let mut o = OnionSkin { ghosts: bits & 1 != 0, edit_multiple: bits & 2 != 0, tint: bits & 4 != 0, fade: bits & 8 != 0, outlines: bits & 16 != 0, keyframes_only: bits & 32 != 0, ..OnionSkin::default() }; + for (i, f) in [0, n / 2, n - 1, n + 40].into_iter().enumerate() { + match i { + 1 => o.all(), + 2 => o.markers = Markers::Anchored { first: n + 5, last: 1 }, + 3 => o.preset(5), + _ => {} + } + let dl = compose(&doc, 0, f.min(n - 1), Some(&o), |sc, fr| evaluate_scene(&doc, sc, fr)); + count += dl.items.len(); + if bits % 7 == 0 { + assert!(render(&dl, &view).is_ok()); + } + } + } + assert!(count > 0); +} + +/// Measures the stage's cost with onion skin ±5 at 1080p, through the tiled path the stage uses +/// (one scene evaluation per frame, tiles in parallel), and that a second look is a cache hit: +/// `cargo test --release -p anicraft-engine onion_timings -- --ignored --nocapture`. +#[test] +#[ignore] +fn onion_timings() { + use crate::render_service::{RenderService, make_job}; + for doc in [sample::demo(), sample::stress(20, 100, 48)] { + println!("-- {} items on a frame", evaluate_scene(&doc, 0, 30).items.len()); + timings_of(&doc); + } + // The cache: the same frame and settings again are hits, other settings keyed apart. + let doc = sample::demo(); + let five = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }; + let view = View { transform: Affine::scale(1.5, 1.5), width: 256, height: 256, background: Some(doc.stage.background) }; + let jobs = |o: &OnionSkin| (0..40).map(|i| make_job(1, &doc, 30, View { transform: Affine::translate(-(i as f32) * 10.0, 0.0).mul(&view.transform), ..view }, Some(o))).collect::>(); + let svc = RenderService::new(1 << 30, None); + let first = svc.render_now_batch(jobs(&five)); + let t = std::time::Instant::now(); + let again = svc.request_batch(jobs(&five)); + let hit = t.elapsed().as_secs_f32() * 1000.0; + assert!(again.iter().all(Option::is_some) && first.len() == again.len()); + let outlined = svc.request_batch(jobs(&OnionSkin { outlines: true, ..five })); + assert!(outlined.iter().all(Option::is_none), "other settings are other pictures"); + println!("cache: {} tiles, second look {hit:.3} ms, all hits", again.len()); +} + +fn timings_of(doc: &anicraft_doc::Document) { + use crate::render_service::{make_job, render_batch}; + let (w, h) = (1920u32, 1080u32); + let z = w as f32 / doc.stage.width as f32; + let tile = 256u32; + let jobs = |onion: Option<&OnionSkin>, frame: u32| -> Vec { + let mut v = Vec::new(); + for ty in 0..h.div_ceil(tile) { + for tx in 0..w.div_ceil(tile) { + let view = View { transform: Affine::translate(-((tx * tile) as f32), -((ty * tile) as f32)).mul(&Affine::scale(z, z)), width: tile.min(w - tx * tile), height: tile.min(h - ty * tile), background: Some(doc.stage.background) }; + v.push(make_job(1, doc, frame, view, onion)); + } + } + v + }; + let five = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }; + let cases: [(&str, Option); 5] = [ + ("off", None), + ("±5, tinted, fading", Some(five)), + ("±5, outlines", Some(OnionSkin { outlines: true, ..five })), + ("±5, keyframes only", Some(OnionSkin { keyframes_only: true, ..five })), + ("Edit Multiple Frames ±5", Some(OnionSkin { edit_multiple: true, ..five })), + ]; + for (name, o) in cases { + let mut best = f32::MAX; + for frame in [12u32, 30, 48] { + let t = std::time::Instant::now(); + let _ = render_batch(&jobs(o.as_ref(), frame)); + best = best.min(t.elapsed().as_secs_f32() * 1000.0); + } + let t = std::time::Instant::now(); + let items = crate::render_service::display_list_with_onion(doc, 30, o.as_ref()).items.len(); + let eval = t.elapsed().as_secs_f32() * 1000.0; + println!("{name}: 1080p {best:.1} ms (best of frames 12, 30, 48), scene {eval:.2} ms, {items} items on frame 30"); + } +} + +#[test] +fn extra_frames_sit_on_their_own_layer_over_an_opaque_background() { + // The sample's sky (locked) and hills cover the stage: frames before or after the playhead + // must show over them, under the playhead's artwork on their own layer only. + let doc = sample::demo(); + let tl = doc.timeline(0); + let rank = |l: LayerId| tl.layers.iter().position(|x| x.id == l).unwrap(); + for o in [OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }, OnionSkin { edit_multiple: true, markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }] { + let dl = compose(&doc, 0, 12, Some(&o), |sc, f| evaluate_scene(&doc, sc, f)); + let plain = evaluate_scene(&doc, 0, 12); + assert!(dl.items.len() > plain.items.len()); + // Back to front: layer by layer, bottom first. + assert!(dl.items.windows(2).all(|w| rank(w[0].layer) >= rank(w[1].layer)), "items are grouped by layer, bottom up"); + // On each layer, its own extra frames come before (under) the playhead's artwork. + let ball = plain.items.last().unwrap().layer; + let on_ball: Vec<&DisplayItem> = dl.items.iter().filter(|i| i.layer == ball).collect(); + assert!(on_ball.len() > 1); + assert_eq!(on_ball.last().map(|i| (i.color.alpha, i.color.tint_amount)), Some((1.0, 0.0)), "the playhead's ball is on top"); + } + // Rendered: the ball on frame 1 (top left of its path) shows over the sky, in Edit Multiple + // Frames at full strength. + let view = View { transform: Affine::IDENTITY, width: 1280, height: 720, background: Some(Rgba::WHITE) }; + let multi = OnionSkin { edit_multiple: true, markers: Markers::Relative { before: 12, after: 0 }, ..OnionSkin::default() }; + let with = render(&compose(&doc, 0, 12, Some(&multi), |sc, f| evaluate_scene(&doc, sc, f)), &view).unwrap().0.to_premul_rgba8(); + let without = render(&evaluate_scene(&doc, 0, 12), &view).unwrap().0.to_premul_rgba8(); + assert_ne!(px(&with, 1280, 200, 260), px(&without, 1280, 200, 260), "the ball on frame 1 is visible"); +} diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs index 42c4fb05..58363868 100644 --- a/crates/engine/src/params.rs +++ b/crates/engine/src/params.rs @@ -146,3 +146,86 @@ pub fn opt_profile(p: &Value, key: &str) -> Result>> Some(_) => Err(bad(key, want)), } } + +/// What the stroke style params take (`stroke.set_style`, `element.set_stroke`, the drawing +/// commands, `paint.ink`). +pub const STROKE_STYLE_PARAMS: &str = "cap?: none|round|square, join?: miter|round|bevel, miter? (limit, 1..=100), style?: solid|dashed|dotted, dash? ([on, off, ..] lengths; implies dashed), dash_offset?, dot_spacing? (implies dotted)"; + +/// The stroke style params (ADR 0046) applied to `base`, for a stroke `width` wide (which sizes +/// a new dash pattern or dot spacing); `None` when none are given. +pub fn opt_stroke_style(p: &Value, base: &anicraft_doc::StrokeStyle, width: f32) -> Result> { + use anicraft_doc::stroke_style::{MAX_DASH_ENTRIES, MAX_DASH_LENGTH, MAX_MITER_LIMIT, MIN_MITER_LIMIT}; + use anicraft_doc::{Cap, Dash, DashKind, Join}; + let keys = ["cap", "join", "miter", "style", "dash", "dash_offset", "dot_spacing"]; + if !keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return Ok(None); + } + let mut st = base.clone(); + if let Some(c) = opt_str(p, "cap")? { + st.cap = Cap::from_key(c).ok_or_else(|| bad("cap", "none, round or square"))?; + } + if let Some(j) = opt_str(p, "join")? { + st.join = Join::from_key(j).ok_or_else(|| bad("join", "miter, round or bevel"))?; + } + if let Some(m) = opt_f32(p, "miter")? { + if !(MIN_MITER_LIMIT..=MAX_MITER_LIMIT).contains(&m) { + return Err(bad("miter", &format!("a miter limit in {MIN_MITER_LIMIT}..={MAX_MITER_LIMIT}"))); + } + st.miter_limit = m; + } + let len_ok = |v: f32| (0.0..=MAX_DASH_LENGTH).contains(&v); + let dash = match p.get("dash") { + None | Some(Value::Null) => None, + Some(Value::Array(list)) => { + if list.is_empty() || list.len() > MAX_DASH_ENTRIES { + return Err(bad("dash", &format!("a list of 1 to {MAX_DASH_ENTRIES} lengths"))); + } + let mut v = Vec::with_capacity(list.len()); + for x in list { + match x.as_f64().filter(|f| f.is_finite()).map(|f| f as f32) { + Some(f) if len_ok(f) => v.push(f), + _ => return Err(bad("dash", &format!("lengths in 0..={MAX_DASH_LENGTH}"))), + } + } + Some(v) + } + Some(_) => return Err(bad("dash", "a list of [on, off, ..] lengths")), + }; + let offset = opt_f32(p, "dash_offset")?; + if offset.is_some_and(|o| o.abs() > MAX_DASH_LENGTH) { + return Err(bad("dash_offset", &format!("in -{MAX_DASH_LENGTH}..={MAX_DASH_LENGTH}"))); + } + let spacing = opt_f32(p, "dot_spacing")?; + if spacing.is_some_and(|s| !len_ok(s)) { + return Err(bad("dot_spacing", &format!("in 0..={MAX_DASH_LENGTH}"))); + } + let kind = match opt_str(p, "style")? { + Some(k) => DashKind::from_key(k).ok_or_else(|| bad("style", "solid, dashed or dotted"))?, + None if dash.is_some() || offset.is_some() => DashKind::Dashed, + None if spacing.is_some() => DashKind::Dotted, + None => st.dash_kind(), + }; + // A new pattern is sized by the stroke: dashes three widths long with two-width gaps, dots + // one width apart. + let w = if width.is_finite() { width.clamp(0.0, MAX_DASH_LENGTH) } else { 1.0 }; + st.dash = match kind { + DashKind::Solid => None, + DashKind::Dashed => { + let (lengths, old_offset) = match &st.dash { + Some(Dash::Dashed { lengths, offset }) => (lengths.to_vec(), *offset), + _ => (vec![(3.0 * w).max(2.0), (2.0 * w).max(2.0)], 0.0), + }; + let lengths = dash.unwrap_or(lengths); + let d = Dash::Dashed { lengths: lengths.into(), offset: offset.unwrap_or(old_offset) }.sanitized(); + Some(d.ok_or_else(|| bad("dash", "a pattern with a gap (some off length above 0)"))?) + } + DashKind::Dotted => { + let old = match &st.dash { + Some(Dash::Dotted { spacing }) => *spacing, + _ => w.max(2.0), + }; + Dash::dotted(spacing.unwrap_or(old)) + } + }; + Ok(Some(st.sanitized())) +} diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index 77996941..df41bd67 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -9,9 +9,9 @@ //! its scripts, so a script that loops forever costs one frame's budget, then stops with a //! message. -use anicraft_doc::actions::{Action, MAX_ACTIONS, PluginScript, check_actions}; +use anicraft_doc::actions::{Action, CompileResult, FrameScript, MAX_ACTIONS, PluginScript, check_actions}; use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step}; -use anicraft_doc::{Document, player}; +use anicraft_doc::{Document, LayerKind, SymbolKind, Timeline, player}; use anicraft_geom::Vec2; use anicraft_plugins::{Host, Kind, Limits, Registry}; use serde_json::{Map, Value, json}; @@ -187,8 +187,12 @@ pub const MAX_MOVIE_OUTPUT: usize = 10_000; pub const MAX_MOVIE_SOUNDS: usize = 4_096; impl Movie { + /// The movie at its first frame. The Output starts with a line for each kept script: which + /// run and which are skipped and why (ADR 0013 tier 2), said once rather than each time the + /// playhead passes. pub fn start(doc: &Document, scripts: &mut dyn ScriptHost) -> Movie { let mut m = Movie { state: PlayerState::default(), output: Vec::new(), sounds: Vec::new() }; + m.output.extend(script_summary(doc).into_iter().map(|l| (0, l))); let s = player::start(doc, scripts); m.take(s); m @@ -246,3 +250,70 @@ pub fn parse_events(v: &Value) -> Result, String> { other => return Err(format!("unknown event type '{other}' (move, down, up, click or leave)")), }) } + +/// A kept script (ADR 0013) and where it is. +pub struct KeptScript<'a> { + /// "Scene 1 › Actions, frame 1" (frames 1-based, as the app shows them). + pub place: String, + /// The timeline runs frame scripts there (a scene or a movie clip, on a layer that plays). + pub plays: bool, + pub compiled: &'a CompileResult, +} + +impl KeptScript<'_> { + /// It runs when the movie plays. + pub fn runs(&self) -> bool { + self.plays && self.compiled.is_ok() + } +} + +/// Most kept scripts listed. +pub const MAX_LISTED_SCRIPTS: usize = 1_000; + +fn layer_plays(tl: &Timeline, index: usize) -> bool { + tl.layers.get(index).is_some_and(|l| l.visible && !matches!(l.kind, LayerKind::Folder | LayerKind::Guide)) && !tl.hidden_by_folder(index) +} + +/// Every kept script in the document: the scenes' first, then the symbols'. +pub fn kept_scripts(doc: &Document) -> Vec> { + let scenes = doc.scenes.iter().map(|s| (s.name.as_str(), &s.timeline, true)); + let symbols = doc.library.iter().map(|s| (s.name.as_str(), &s.timeline, s.kind == SymbolKind::MovieClip)); + let mut out = Vec::new(); + for (name, tl, runs) in scenes.chain(symbols) { + for (index, layer) in tl.layers.iter().enumerate() { + for k in &layer.keyframes { + let Some(FrameScript::Source(src)) = &k.script else { continue }; + if out.len() >= MAX_LISTED_SCRIPTS { + return out; + } + out.push(KeptScript { place: format!("{name} › {}, frame {}", layer.name, u64::from(k.start) + 1), plays: runs && layer_plays(tl, index), compiled: src.compiled() }); + } + } + } + out +} + +/// The Output's opening lines: each kept script that runs (and what in it is ignored), and +/// each that doesn't, with why. +pub fn script_summary(doc: &Document) -> Vec { + let mut lines = Vec::new(); + for k in kept_scripts(doc) { + match (k.plays, k.compiled) { + (false, _) => lines.push(format!("Frame script not run: {}: graphic and button timelines, guide layers and hidden layers don't run frame scripts", k.place)), + (true, Ok(c)) => { + lines.push(format!("Frame script runs: {}", k.place)); + lines.extend(c.notes.iter().map(|n| format!("Frame script at {}: {n}", k.place))); + } + (true, Err(problems)) => { + let first = problems.first().map_or_else(String::new, ToString::to_string); + let more = match problems.len() { + 0 | 1 => String::new(), + 2 => " (and 1 more problem: see the Actions panel)".into(), + n => format!(" (and {} more problems: see the Actions panel)", n - 1), + }; + lines.push(format!("Frame script not run: {}: {first}{more}", k.place)); + } + } + } + lines +} diff --git a/crates/engine/src/raw_tests.rs b/crates/engine/src/raw_tests.rs new file mode 100644 index 00000000..16b4a58e --- /dev/null +++ b/crates/engine/src/raw_tests.rs @@ -0,0 +1,496 @@ +//! The Selection tool on raw shapes (ADR 0041) through the commands: bending, shared points, +//! snapping and the marquee. + +use crate::Session; +use anicraft_doc::{Element, ElementKind}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +/// A blank document drawing raw shapes, with a 100 × 80 rectangle (fill and outline) at the origin. +fn rect_session() -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + s +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn is_fill(e: &Element) -> bool { + matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some()) +} + +fn count(s: &Session) -> (usize, usize) { + let r = raw(s); + (r.iter().filter(|e| is_fill(e)).count(), r.iter().filter(|e| !is_fill(e)).count()) +} + +fn polylines(e: &Element) -> Vec { + match &e.kind { + ElementKind::Shape(sh) => sh.path.flatten(&e.transform, 0.01), + _ => Vec::new(), + } +} + +fn area(e: &Element) -> f32 { + polylines(e) + .iter() + .map(|pl| { + let n = pl.points.len(); + (0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::() * 0.5 + }) + .sum::() + .abs() +} + +fn length(e: &Element) -> f32 { + polylines(e).iter().map(|pl| pl.points.windows(2).map(|w| w[0].distance(w[1])).sum::()).sum() +} + +fn fill_area(s: &Session) -> f32 { + raw(s).iter().filter(|e| is_fill(e)).map(|e| area(e)).sum() +} + +/// Stage-space anchors of a raw shape. +fn anchors(e: &Element) -> Vec { + match &e.kind { + ElementKind::Shape(sh) => sh.path.anchors().into_iter().map(|(_, p)| e.transform.apply(p)).collect(), + _ => Vec::new(), + } +} + +/// Every stroke end lies on a fill corner or another stroke's end: the drawing is still joined +/// (for drawings without loose ends). +fn joined(s: &Session) -> bool { + let r = raw(s); + let corners: Vec = r.iter().flat_map(|e| anchors(e)).collect(); + r.iter().filter(|e| !is_fill(e)).all(|e| { + let a = anchors(e); + [a.first(), a.last()].into_iter().flatten().all(|p| corners.iter().filter(|q| q.distance(*p) < 1e-3).count() >= 2) + }) +} + +fn has_anchor(s: &Session, p: Vec2) -> usize { + raw(s).iter().filter(|e| anchors(e).iter().any(|q| q.distance(p) < 1e-3)).count() +} + +// ----- bending ----------------------------------------------------------------------------------- + +#[test] +fn dragging_a_segment_bends_it_through_the_dragged_point_and_the_fill_follows() { + let mut s = rect_session(); + let history = s.history_len(); + // Drag the top edge's middle up 30: the edge becomes a curve through (50, −30). + let r = run(&mut s, "path.bend_segment", json!({"x": 50, "y": 0, "dx": 0, "dy": -30})); + assert_eq!(r["merged"], true); + assert!((r["x"].as_f64().unwrap_or(0.0) - 50.0).abs() < 1e-3 && (r["y"].as_f64().unwrap_or(0.0) + 30.0).abs() < 1e-3, "{r}"); + assert_eq!(count(&s), (1, 4), "still a fill and four sides"); + // The top is a curve through the dragged point. + let top = raw(&s).into_iter().find(|e| !is_fill(e) && polylines(e).iter().any(|pl| pl.points.iter().any(|p| p.y < -29.0))); + let Some(top) = top else { panic!("no bent stroke") }; + // (A symmetric pull: the dragged point is the curve's peak.) + let peak = polylines(&top).iter().flat_map(|pl| pl.points.clone()).min_by(|a, b| a.y.total_cmp(&b.y)).unwrap_or(Vec2::ZERO); + assert!((peak.y + 30.0).abs() < 0.02 && (peak.x - 50.0).abs() < 2.0, "the curve peaks at the dragged point: {peak:?}"); + // The fill bulges with it, by exactly the area under the cubic: L·(h₁ + h₂)/4 with both + // handles raised 40 (a pull of 30 at the middle needs 30 / 0.75). + assert!((fill_area(&s) - (8000.0 + 100.0 * 80.0 / 4.0)).abs() < 2.0, "{}", fill_area(&s)); + assert!(joined(&s)); + // One undo step takes it back. + assert_eq!(s.history_len(), history + 1); + run(&mut s, "edit.undo", json!({})); + assert!((fill_area(&s) - 8000.0).abs() < 0.5); +} + +#[test] +fn a_straight_segment_stays_straight_until_it_is_dragged() { + let mut s = rect_session(); + run(&mut s, "path.bend_segment", json!({"x": 50, "y": 0, "dx": 0, "dy": -30})); + // The other three sides are still lines. + let lines = raw(&s).iter().filter(|e| !is_fill(e)).filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.path.cmds.iter().all(|c| !matches!(c, anicraft_geom::PathCmd::CubicTo(..))))).count(); + assert_eq!(lines, 3); +} + +#[test] +fn a_drag_in_steps_bends_like_one_move_and_merges_at_the_end() { + let mut s = rect_session(); + s.begin_gesture("Bend"); + let first = run(&mut s, "path.bend_segment", json!({"x": 100, "y": 40, "dx": 10, "dy": 0, "merge": false})); + let (id, cmd, t) = (first["id"].clone(), first["cmd"].clone(), first["t"].clone()); + // Later steps name the segment and pass the point where it now is. + run(&mut s, "path.bend_segment", json!({"x": 110, "y": 40, "dx": 10, "dy": 0, "id": id, "cmd": cmd, "t": t, "merge": false})); + let ids: Vec = raw(&s).iter().map(|e| e.id.0).collect(); + run(&mut s, "raw.merge", json!({"ids": ids})); + s.end_gesture(); + let far = raw(&s).iter().flat_map(|e| polylines(e)).flat_map(|pl| pl.points).fold(0.0f32, |m, p| m.max(p.x)); + assert!((far - 120.0).abs() < 0.1, "the side's middle went to x = 120: {far}"); + assert!(joined(&s)); + assert!((fill_area(&s) - (8000.0 + 80.0 * (2.0 * 20.0 / 0.75) / 4.0)).abs() < 2.0, "{}", fill_area(&s)); +} + +#[test] +fn bending_an_object_bends_only_it() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#00ff00", "stroke": null})); + let r = run(&mut s, "path.bend_segment", json!({"x": 0, "y": 40, "dx": -20, "dy": 0})); + assert_eq!(r["merged"], false); + assert_eq!(r["changed"].as_array().map(Vec::len), Some(1), "objects don't share edges"); + // The closing edge of an object's outline can be bent too. + let areas: Vec = s.visible_elements().iter().map(|e| area(e)).collect(); + assert!(areas.iter().any(|a| (a - 8000.0).abs() < 0.5) && areas.iter().any(|a| (a - (8000.0 + 80.0 * (40.0 / 0.75) / 4.0)).abs() < 2.0), "{areas:?}"); +} + +// ----- shared points ------------------------------------------------------------------------------ + +#[test] +fn moving_a_corner_moves_every_shape_that_shares_it() { + let mut s = rect_session(); + let history = s.history_len(); + let r = run(&mut s, "raw.move_point", json!({"x": 100, "y": 0, "to_x": 130, "to_y": -20})); + assert_eq!(r["moved"], 3, "the fill and the two sides that meet there: {r}"); + let to = Vec2::new(130.0, -20.0); + assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 0, "nothing stays behind"); + assert_eq!(has_anchor(&s, to), 3); + assert!(joined(&s)); + // The fill is the quadrilateral through the new corner (shoelace). + let quad = [Vec2::new(0.0, 0.0), to, Vec2::new(100.0, 80.0), Vec2::new(0.0, 80.0)]; + let want = (0..4).map(|i| quad[i].cross(quad[(i + 1) % 4])).sum::().abs() * 0.5; + assert!((fill_area(&s) - want).abs() < 0.5, "{} vs {want}", fill_area(&s)); + assert_eq!(s.history_len(), history + 1, "one undo step"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 3); +} + +#[test] +fn a_line_ending_on_an_edge_drags_the_edge_with_it() { + let mut s = rect_session(); + // A line from inside the rectangle up to its top edge: they meet at (50, 0). + run(&mut s, "draw.line", json!({"x0": 50, "y0": -40, "x1": 50, "y1": 0, "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + let r = run(&mut s, "raw.move_point", json!({"x": 50, "y": -40, "to_x": 50, "to_y": -60})); + assert_eq!(r["moved"], 1, "a free end moves alone"); + // The point where it meets the edge: the fill and both halves of the top move with it. + let r = run(&mut s, "raw.move_point", json!({"x": 50, "y": 0, "to_x": 50, "to_y": 10})); + assert!(r["moved"].as_u64().unwrap_or(0) >= 3, "{r}"); + assert!(has_anchor(&s, Vec2::new(50.0, 10.0)) >= 3); + assert_eq!(has_anchor(&s, Vec2::new(50.0, 0.0)), 0, "nothing stays behind"); + // The fill lost the triangle the dent took: 100 wide, 10 deep. + assert!((fill_area(&s) - (8000.0 - 0.5 * 100.0 * 10.0)).abs() < 0.5, "{}", fill_area(&s)); +} + +#[test] +fn a_point_drag_passes_its_points_on_and_merges_at_the_end() { + let mut s = rect_session(); + s.begin_gesture("Move Point"); + let r = run(&mut s, "raw.move_point", json!({"x": 0, "y": 80, "to_x": -5, "to_y": 85, "merge": false})); + let points = r["points"].clone(); + assert_eq!(points.as_array().map(Vec::len), Some(3)); + run(&mut s, "raw.move_point", json!({"x": -5, "y": 85, "to_x": -10, "to_y": 90, "points": points, "merge": false})); + let ids: Vec = raw(&s).iter().map(|e| e.id.0).collect(); + run(&mut s, "raw.merge", json!({"ids": ids})); + s.end_gesture(); + assert_eq!(has_anchor(&s, Vec2::new(-10.0, 90.0)), 3); + assert!(joined(&s)); +} + +// ----- snapping ------------------------------------------------------------------------------------- + +/// A raw rectangle and a separate raw line whose free end is dragged. +fn snap_session() -> Session { + let mut s = rect_session(); + run(&mut s, "draw.line", json!({"x0": 200, "y0": 0, "x1": 300, "y1": 0, "stroke": "#0000ff"})); + run(&mut s, "edit.deselect", json!({})); + s +} + +#[test] +fn a_dragged_point_snaps_within_ten_screen_pixels_at_any_zoom() { + // The drop point is 8 document units from the rectangle's corner (100, 0). + let drop = json!({"x": 200, "y": 0, "to_x": 108, "to_y": 0}); + for (zoom, snaps) in [(1.0, true), (2.0, false), (0.5, true), (4.0, false), (0.8, true)] { + let mut s = snap_session(); + let mut p = drop.clone(); + p["snap"] = json!(10.0 / zoom); + let r = run(&mut s, "raw.move_point", p); + assert_eq!(r["snapped"].is_object(), snaps, "zoom {zoom}: {r}"); + if snaps { + assert_eq!(r["snapped"]["to"], "point"); + assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 4, "zoom {zoom}: the line's end joined the corner"); + } else { + assert_eq!(has_anchor(&s, Vec2::new(108.0, 0.0)), 1, "zoom {zoom}: where it was let go"); + } + } +} + +#[test] +fn a_dragged_point_snaps_onto_a_line_without_changing_the_line() { + let mut s = snap_session(); + // 6 units below the rectangle's bottom edge, away from its corners. + let r = run(&mut s, "raw.move_point", json!({"x": 200, "y": 0, "to_x": 40, "to_y": 86, "snap": 10})); + assert_eq!(r["snapped"]["to"], "line", "{r}"); + assert!((r["y"].as_f64().unwrap_or(0.0) - 80.0).abs() < 1e-3); + // The bottom is still straight along y = 80 and the fill the same. + assert!((fill_area(&s) - 8000.0).abs() < 0.5, "{}", fill_area(&s)); + let bottom: Vec = raw(&s).iter().flat_map(|e| anchors(e)).filter(|p| (p.y - 80.0).abs() < 1.0).collect(); + assert!(bottom.iter().all(|p| (p.y - 80.0).abs() < 1e-3), "{bottom:?}"); + assert!(has_anchor(&s, Vec2::new(40.0, 80.0)) >= 2, "the edge gained a point where the line meets it"); +} + +#[test] +fn a_dragged_selection_snaps_its_nearest_corner() { + let mut s = snap_session(); + // Select the loose line and drag it by its left end towards the rectangle's corner. + run(&mut s, "element.pick", json!({"x": 250, "y": 0})); + let r = run(&mut s, "element.translate", json!({"dx": -93, "dy": 4, "snap": 10, "from": [107, 4]})); + assert_eq!(r["snapped"]["to"], "point", "{r}"); + assert!((r["dx"].as_f64().unwrap_or(0.0) + 100.0).abs() < 1e-3 && r["dy"].as_f64().unwrap_or(1.0).abs() < 1e-3, "{r}"); + // Out of reach, nothing snaps. + let r = run(&mut s, "element.translate", json!({"dx": 0, "dy": -40, "snap": 10, "from": [100, -40]})); + assert!(r["snapped"].is_null(), "{r}"); +} + +#[test] +fn arrow_key_nudges_join_ends_within_point_two_at_their_midpoint() { + let mut s = snap_session(); + // Nudge the loose line left until its end is 0.15 from the corner (100, 0) and drop it, as + // the arrow keys do at 1000 % (0.1 per press). + run(&mut s, "element.pick", json!({"x": 250, "y": 0})); + run(&mut s, "element.translate", json!({"dx": -99.85, "dy": 0})); + run(&mut s, "draw.drop", json!({})); + let mid = Vec2::new(100.075, 0.0); + assert_eq!(has_anchor(&s, mid), 4, "the corner and the end meet halfway"); + assert_eq!(has_anchor(&s, Vec2::new(100.0, 0.0)), 0); +} + +#[test] +fn arrow_key_nudges_put_an_end_onto_a_line_that_stays_straight() { + let mut s = rect_session(); + run(&mut s, "draw.line", json!({"x0": 40, "y0": -60, "x1": 40, "y1": -10, "stroke": "#0000ff"})); + // Down until the end is 0.12 above the top edge, then let go. + run(&mut s, "element.translate", json!({"dx": 0, "dy": 9.88})); + run(&mut s, "draw.drop", json!({})); + let top: Vec = raw(&s).iter().flat_map(|e| anchors(e)).filter(|p| p.y.abs() < 1.0).collect(); + assert!(top.iter().all(|p| p.y.abs() < 1e-4), "the top stays on y = 0: {top:?}"); + assert!(has_anchor(&s, Vec2::new(40.0, 0.0)) >= 2, "the end is on the edge"); + assert!((fill_area(&s) - 8000.0).abs() < 0.5); +} + +// ----- the marquee ---------------------------------------------------------------------------------- + +#[test] +fn a_marquee_selects_the_parts_under_it_and_the_parts_add_up() { + let mut s = rect_session(); + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 20, "h": 20, "object": true})); + run(&mut s, "draw.rect", json!({"x": 150, "y": 50, "w": 200, "h": 10, "object": true})); + let history = s.history_len(); + let dirty = s.is_dirty(); + // The right half of the rectangle, the small object wholly, the long one not. + let r = run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 330, "y1": 45})); + assert_eq!(r["cut"], 3, "part of the fill, of the top and of the right side: {r}"); + let sel = s.selection.clone(); + let els = s.visible_elements(); + let chosen: Vec<&Arc> = els.iter().filter(|e| sel.has_id(e.id)).collect(); + assert!(chosen.iter().any(|e| matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge && (area(e) - 400.0).abs() < 0.5)), "the object inside"); + assert!(!chosen.iter().any(|e| (area(e) - 2000.0).abs() < 0.5), "not the one across the edge"); + // Inside: 50 × 45 of the fill (y from 0 to 45), the right side's upper 45 and the top's + // right 50. + let inside: f32 = chosen.iter().filter(|e| is_fill(e) && matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).map(|e| area(e)).sum(); + assert!((inside - 50.0 * 45.0).abs() < 0.5, "{inside}"); + let lines: f32 = chosen.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_none())).map(|e| length(e)).sum(); + assert!((lines - 95.0).abs() < 0.05, "{lines}"); + // Inside and outside add up to the whole. + assert!((fill_area(&s) - 8000.0).abs() < 0.5, "{}", fill_area(&s)); + let total: f32 = raw(&s).iter().filter(|e| !is_fill(e)).map(|e| length(e)).sum(); + assert!((total - 360.0).abs() < 0.05, "{total}"); + // Selecting is not an edit: no undo step, and a saved document stays saved. + assert_eq!(s.history_len(), history); + assert_eq!(s.is_dirty(), dirty); +} + +#[test] +fn letting_go_of_a_marquee_puts_the_drawing_back_whole() { + let mut s = rect_session(); + s.mark_saved(); + let history = s.history_len(); + run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200})); + assert_eq!(count(&s), (2, 6)); + assert!(!s.is_dirty()); + // Clicking empty space: the cut goes, the drawing is as it was. + run(&mut s, "element.pick", json!({"x": 500, "y": 500})); + assert_eq!(count(&s), (1, 4)); + assert!(!s.is_dirty()); + assert_eq!(s.history_len(), history, "a marquee is not an edit"); + // Clicking the part outside selects the whole shape it came from. + run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200})); + run(&mut s, "element.pick", json!({"x": 20, "y": 40})); + assert_eq!(count(&s), (1, 4)); + assert_eq!(s.selection.len(), 1); + assert!(raw(&s).iter().any(|e| s.selection.has_id(e.id) && is_fill(e) && (area(e) - 8000.0).abs() < 0.5)); + // A new marquee replaces the old one. + run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200})); + run(&mut s, "raw.select_rect", json!({"x0": -20, "y0": -20, "x1": 50, "y1": 40})); + assert_eq!(count(&s), (2, 6), "cut once, at the new marquee (the corner: a fill and two sides)"); +} + +#[test] +fn moving_marquee_parts_is_one_undo_step_from_the_whole_drawing() { + let mut s = rect_session(); + let history = s.history_len(); + run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200})); + s.begin_gesture("Move"); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + run(&mut s, "draw.drop", json!({})); + s.end_gesture(); + assert_eq!(s.history_len(), history + 1); + // The right half moved away; the left half stayed. + assert!((fill_area(&s) - 8000.0).abs() < 0.5); + let far = raw(&s).iter().flat_map(|e| anchors(e)).fold(0.0f32, |m, p| m.max(p.x)); + assert!((far - 140.0).abs() < 1e-3, "{far}"); + // Undo goes straight back to the whole rectangle. + run(&mut s, "edit.undo", json!({})); + assert_eq!(count(&s), (1, 4)); + assert!((fill_area(&s) - 8000.0).abs() < 0.5); + // Deleting parts is an edit too. + run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200})); + run(&mut s, "edit.delete", json!({})); + assert!((fill_area(&s) - 4000.0).abs() < 0.5, "{}", fill_area(&s)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(count(&s), (1, 4)); +} + +#[test] +fn shift_marquees_add_parts() { + let mut s = rect_session(); + run(&mut s, "raw.select_rect", json!({"x0": -20, "y0": -20, "x1": 30, "y1": 30})); + let first = s.selection.len(); + run(&mut s, "raw.select_rect", json!({"x0": 70, "y0": 50, "x1": 130, "y1": 100, "add": true})); + assert!(s.selection.len() > first); + assert!((fill_area(&s) - 8000.0).abs() < 0.5); + // Letting go heals both cuts. + run(&mut s, "edit.deselect", json!({})); + assert_eq!(count(&s), (1, 4)); +} + +#[test] +fn a_marquee_over_a_whole_raw_shape_selects_it_without_cutting() { + let mut s = rect_session(); + let r = run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": -10, "x1": 110, "y1": 90})); + assert_eq!(r["cut"], 0); + assert_eq!(s.selection.len(), 5); + assert_eq!(count(&s), (1, 4)); +} + +// ----- what a drag takes ------------------------------------------------------------------------------ + +#[test] +fn the_selection_tool_knows_corners_segments_and_fills() { + let mut s = rect_session(); + let kind = |s: &mut Session, x: f32, y: f32| run(s, "raw.hit", json!({"x": x, "y": y, "slop": 3, "point_slop": 5}))["kind"].clone(); + assert_eq!(kind(&mut s, 101.0, 2.0), "point", "a corner"); + assert_eq!(kind(&mut s, 50.0, 1.0), "segment", "an edge"); + assert_eq!(kind(&mut s, 50.0, 40.0), "fill"); + assert_eq!(kind(&mut s, 500.0, 40.0), Value::Null); + // Once selected, a drag moves it. + run(&mut s, "element.pick", json!({"x": 50, "y": 40})); + assert_eq!(kind(&mut s, 50.0, 40.0), "object"); + // An object is an object anywhere on it. + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 20, "h": 20, "object": true})); + assert_eq!(kind(&mut s, 300.0, 0.0), "object"); +} + +#[test] +fn dragging_a_fill_moves_only_the_fill() { + let mut s = rect_session(); + // The click-and-drag on a fill: it is selected alone, moved and dropped. + run(&mut s, "element.pick", json!({"x": 50, "y": 40})); + assert_eq!(s.selection.len(), 1); + run(&mut s, "element.translate", json!({"dx": 0, "dy": 200})); + run(&mut s, "draw.drop", json!({})); + // The outline stayed where it was, now with nothing inside. + let strokes: Vec = raw(&s).iter().filter(|e| !is_fill(e)).flat_map(|e| anchors(e)).collect(); + assert!(strokes.iter().all(|p| p.y <= 80.0 + 1e-3), "{strokes:?}"); + let fills: Vec = raw(&s).iter().filter(|e| is_fill(e)).flat_map(|e| anchors(e)).collect(); + assert!(fills.iter().all(|p| p.y >= 200.0 - 1e-3)); +} + +#[test] +fn raw_edits_never_panic_on_odd_input() { + let mut s = rect_session(); + for (id, p) in [ + ("path.bend_segment", json!({"x": 50, "y": 0, "dx": 1e7, "dy": -1e7})), + ("path.bend_segment", json!({"x": 50, "y": 0, "dx": 1, "dy": 1, "id": 999_999})), + ("path.bend_segment", json!({"x": 50, "y": 0, "dx": 1, "dy": 1, "cmd": 99, "t": 0.5, "id": raw(&s)[1].id.0})), + ("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1e7, "to_y": 1e7})), + ("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1, "to_y": 1, "points": [[1, 2], [3]]})), + ("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1, "to_y": 1, "points": []})), + ("raw.move_point", json!({"x": 0, "y": 0, "to_x": 1, "to_y": 1, "points": [[u64::MAX, u64::MAX]]})), + ("raw.select_rect", json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0})), + ("raw.select_rect", json!({"x0": -1e7, "y0": -1e7, "x1": 1e7, "y1": 1e7})), + ("raw.merge", json!({"ids": [u64::MAX]})), + ] { + let _ = s.execute(id, &p); + } + let _ = anicraft_render::render_frame(&s.doc, 0, 0.1); + let _ = Affine::IDENTITY; +} + +/// Per-frame cost of the Selection tool's drags on a busy raw drawing (run by hand: +/// `cargo test -p anicraft-engine raw_drag_timings -- --ignored --nocapture`). +#[test] +#[ignore] +fn raw_drag_timings() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + // 12 × 12 outlined squares, and lines across every row: 144 fills, ~1,000 stroke pieces. + for i in 0..12 { + for j in 0..12 { + run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000"})); + } + run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"})); + } + run(&mut s, "edit.deselect", json!({})); + let n = s.visible_elements().len(); + let time = |s: &mut Session, label: &str, f: &dyn Fn(&mut Session)| { + let t = std::time::Instant::now(); + let reps = 20; + for _ in 0..reps { + f(s); + } + eprintln!("{label}: {:.2} ms", t.elapsed().as_secs_f64() * 1000.0 / f64::from(reps)); + }; + eprintln!("{n} raw shapes"); + time(&mut s, "raw_grab (hover)", &|s| { + let _ = s.raw_grab(Vec2::new(300.0, 300.0), 3.0, 6.0); + }); + s.begin_gesture("Bend"); + time(&mut s, "bend frame (no merge)", &|s| { + let _ = s.execute("path.bend_segment", &json!({"x": 320, "y": 300, "dx": 0, "dy": -0.5, "merge": false})); + }); + s.end_gesture(); + let r = run(&mut s, "raw.move_point", json!({"x": 340, "y": 340, "to_x": 341, "to_y": 341, "snap": 10, "merge": false})); + let points = r["points"].clone(); + time(&mut s, "point frame with snapping", &|s| { + let _ = s.execute("raw.move_point", &json!({"x": 341, "y": 341, "to_x": 341, "to_y": 341, "snap": 10, "points": points, "merge": false})); + }); + // Once: it replaces the shapes it merges. + let ids: Vec = points.as_array().into_iter().flatten().map(|p| p[0].clone()).collect(); + let t = std::time::Instant::now(); + run(&mut s, "raw.merge", json!({"ids": ids})); + eprintln!("merge at release: {:.2} ms", t.elapsed().as_secs_f64() * 1000.0); + time(&mut s, "marquee cut and heal", &|s| { + let _ = s.execute("raw.select_rect", &json!({"x0": 125, "y0": 125, "x1": 425, "y1": 425})); + let _ = s.execute("edit.deselect", &json!({})); + }); + run(&mut s, "raw.select_rect", json!({"x0": 0, "y0": 0, "x1": 45, "y1": 45})); + time(&mut s, "selection move frame with snapping", &|s| { + let _ = s.execute("element.translate", &json!({"dx": 0.5, "dy": 0, "snap": 10, "from": [10, 10]})); + }); +} diff --git a/crates/engine/src/rawsub_tests.rs b/crates/engine/src/rawsub_tests.rs new file mode 100644 index 00000000..e3a49050 --- /dev/null +++ b/crates/engine/src/rawsub_tests.rs @@ -0,0 +1,392 @@ +//! Subselection on raw shapes and merging everywhere (ADR 0042), through the commands. + +use crate::Session; +use anicraft_doc::{Element, ElementKind, GradientStop, Paint, Rgba}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn raw_session() -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + s +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn fills(s: &Session) -> Vec> { + raw(s).into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).collect() +} + +fn area(e: &Element) -> f32 { + let ElementKind::Shape(sh) = &e.kind else { return 0.0 }; + sh.path + .flatten(&e.transform, 0.01) + .iter() + .map(|pl| { + let n = pl.points.len(); + (0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::() * 0.5 + }) + .sum::() + .abs() +} + +fn fill_color(e: &Element) -> Option { + match &e.kind { + ElementKind::Shape(sh) => match &sh.fill { + Some(Paint::Solid(c)) => Some(*c), + _ => None, + }, + _ => None, + } +} + +fn ids(v: &Value, key: &str) -> Vec { + v[key].as_array().into_iter().flatten().filter_map(Value::as_u64).collect() +} + +fn xy(v: &Value) -> Vec { + v.as_array().into_iter().flatten().filter_map(|p| Some(Vec2::new(p.get(0)?.as_f64()? as f32, p.get(1)?.as_f64()? as f32))).collect() +} + +fn has(points: &[Vec2], p: (f32, f32)) -> bool { + points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 1e-2) +} + +#[test] +fn a_click_shows_the_anchors_of_everything_connected_once_each() { + let mut s = raw_session(); + // An outlined rectangle, a line from its corner, and a line far away. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "draw.line", json!({"x0": 100, "y0": 80, "x1": 160, "y1": 140, "stroke": "#000000"})); + run(&mut s, "draw.line", json!({"x0": 300, "y0": 0, "x1": 400, "y1": 0, "stroke": "#000000"})); + // Fill, four sides, the joined line: six shapes. The far line is not connected. + assert_eq!(raw(&s).len(), 7); + let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 0})); + assert_eq!(v["raw"], json!(true)); + assert_eq!(ids(&v, "selected").len(), 6, "{v}"); + let anchors = xy(&v["anchors"]); + assert_eq!(anchors.len(), 5, "four corners shared by fill and sides, and the line's far end: {anchors:?}"); + for p in [(0.0, 0.0), (100.0, 0.0), (100.0, 80.0), (0.0, 80.0), (160.0, 140.0)] { + assert!(has(&anchors, p), "{p:?} in {anchors:?}"); + } + // The clicked edge's ends (whose handles show). + let ends = xy(&v["ends"]); + assert!(has(&ends, (0.0, 0.0)) && has(&ends, (100.0, 0.0)), "{ends:?}"); + // Straight edges have no handles. + assert!(v["handles"].as_array().is_some_and(Vec::is_empty)); + // Inside the fill: the same set, no edge. + let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40})); + assert_eq!(ids(&v, "selected").len(), 6); + assert!(xy(&v["ends"]).is_empty()); + // The far line alone. + let v = run(&mut s, "raw.subselect", json!({"x": 350, "y": 0})); + assert_eq!(ids(&v, "selected").len(), 1); + assert_eq!(xy(&v["anchors"]).len(), 2); + // Shift adds; empty space clears. + let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40, "add": true})); + assert_eq!(ids(&v, "selected").len(), 7); + let v = run(&mut s, "raw.subselect", json!({"x": 700, "y": 700})); + assert!(ids(&v, "selected").is_empty()); +} + +#[test] +fn fills_that_meet_along_an_edge_and_lines_ending_on_an_edge_are_connected() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null})); + // A line standing on the blue square's top edge (a T-junction, not a corner). + run(&mut s, "draw.line", json!({"x0": 150, "y0": 0, "x1": 150, "y1": -50, "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 50})); + assert_eq!(ids(&v, "selected").len(), 3, "red, blue and the line: {v}"); +} + +#[test] +fn dragging_a_handle_changes_the_curve_in_both_shapes_that_share_it() { + let mut s = raw_session(); + run(&mut s, "draw.ellipse", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 50})); + let handles = v["handles"].as_array().cloned().unwrap_or_default(); + // A circle of four arcs: two handles per arc, each listed once although the fill and the + // outline both have it. + assert_eq!(handles.len(), 8, "{v}"); + let h = &handles[0]; + let (id, cmd, slot) = (h["id"].as_u64().unwrap(), h["cmd"].as_u64().unwrap(), h["slot"].as_u64().unwrap()); + let before: Vec> = raw(&s); + s.begin_gesture("Move Handle"); + let r = run(&mut s, "raw.move_handle", json!({"id": id, "cmd": cmd, "slot": slot, "dx": 20, "dy": -15, "merge": false})); + assert_eq!(ids(&r, "changed").len(), 2, "the fill and its outline: {r}"); + // The edge moved the same way in both: the outline still runs along the fill's edge (to + // within the flattening `distance_to_edge` measures with). + let changed: Vec> = raw(&s).into_iter().filter(|e| ids(&r, "changed").contains(&e.id.0)).collect(); + let (fill, line) = match (changed.iter().find(|e| fill_color(e).is_some()), changed.iter().find(|e| fill_color(e).is_none())) { + (Some(f), Some(l)) => (f.clone(), l.clone()), + _ => panic!("a fill and a line changed"), + }; + let ElementKind::Shape(ls) = &line.kind else { panic!() }; + let ElementKind::Shape(fs) = &fill.kind else { panic!() }; + for pl in ls.path.flatten(&line.transform, 0.05) { + for p in pl.points { + assert!(fs.path.distance_to_edge(p, &fill.transform) < 0.3, "{p:?} off the fill's edge"); + } + } + assert!(area(&fill) != area(before.iter().find(|e| fill_color(e).is_some()).unwrap())); + // Release: they merge again, still joined, in one undo step. + run(&mut s, "raw.merge", json!({"ids": ids(&r, "changed")})); + s.end_gesture(); + assert_eq!(fills(&s).len(), 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(raw(&s).iter().map(|e| e.id).collect::>(), before.iter().map(|e| e.id).collect::>()); + // Straight segments have no handles to move. + let mut t = raw_session(); + run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "fill": "#ff0000", "stroke": null})); + let id = raw(&t)[0].id.0; + assert!(t.execute("raw.move_handle", &json!({"id": id, "cmd": 1, "slot": 1, "dx": 1, "dy": 1})).is_err()); +} + +#[test] +fn selected_anchors_move_together_with_every_shape_that_shares_them() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + // The top edge's two corners, 10 px up (the arrow keys, Shift: one step, merged). + run(&mut s, "raw.move_point", json!({"x": 0, "y": 0, "to_x": 0, "to_y": -10, "with": [[100, 0]]})); + let f = fills(&s); + assert_eq!(f.len(), 1); + assert!((area(&f[0]) - 100.0 * 90.0).abs() < 0.5, "{}", area(&f[0])); + let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40})); + let anchors = xy(&v["anchors"]); + assert!(has(&anchors, (0.0, -10.0)) && has(&anchors, (100.0, -10.0)) && anchors.len() == 4, "{anchors:?}"); +} + +#[test] +fn the_marquee_takes_whole_connected_shapes_on_the_active_layer_and_selects_the_anchors_inside() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "draw.line", json!({"x0": 300, "y0": 0, "x1": 400, "y1": 0, "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + // Over the bottom-right corner only. + let v = run(&mut s, "raw.subselect_rect", json!({"x0": 90, "y0": 70, "x1": 120, "y1": 100})); + assert_eq!(ids(&v, "selected").len(), 5, "the fill and its four sides: {v}"); + let inside = xy(&v["anchors"]); + assert_eq!(inside.len(), 1); + assert!(has(&inside, (100.0, 80.0))); + // Through the middle of the fill, no anchors inside: the shapes, no anchors. + let v = run(&mut s, "raw.subselect_rect", json!({"x0": 40, "y0": 30, "x1": 60, "y1": 50})); + assert_eq!(ids(&v, "selected").len(), 5); + assert!(xy(&v["anchors"]).is_empty()); + // Another layer is not reached. + run(&mut s, "layer.new", json!({})); + let v = run(&mut s, "raw.subselect_rect", json!({"x0": -10, "y0": -10, "x1": 500, "y1": 100})); + assert!(ids(&v, "selected").is_empty(), "{v}"); +} + +#[test] +fn snapping_off_disables_snapping_for_both_tools() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.line", json!({"x0": 200, "y0": 0, "x1": 300, "y1": 0, "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + let drag_point = |s: &mut Session| run(s, "raw.move_point", json!({"x": 200, "y": 0, "to_x": 104, "to_y": 3, "snap": 10, "merge": false})); + // On: the line's end goes onto the rectangle's corner. + s.begin_gesture("t"); + let v = drag_point(&mut s); + assert_eq!(v["snapped"]["to"], json!("point"), "{v}"); + assert!((v["x"].as_f64().unwrap() - 100.0).abs() < 1e-3); + s.end_gesture(); + run(&mut s, "edit.undo", json!({})); + // Off: it goes where the pointer took it. + assert_eq!(run(&mut s, "draw.snap_to_objects", json!({}))["snap_to_objects"], json!(false)); + let v = drag_point(&mut s); + assert!(v["snapped"].is_null(), "{v}"); + assert!((v["x"].as_f64().unwrap() - 104.0).abs() < 1e-3); + run(&mut s, "edit.undo", json!({})); + // A selection move (the Selection tool's, and Subselection's on connected shapes) too. + run(&mut s, "raw.subselect", json!({"x": 250, "y": 0})); + let v = run(&mut s, "element.translate", json!({"dx": -96, "dy": 3, "snap": 10, "from": [200, 0]})); + assert!(v["snapped"].is_null() && (v["dx"].as_f64().unwrap() + 96.0).abs() < 1e-3, "{v}"); + run(&mut s, "draw.snap_to_objects", json!({"on": true})); + let v = run(&mut s, "element.translate", json!({"dx": 1, "dy": -1, "snap": 10, "from": [105, 3]})); + assert!(!v["snapped"].is_null(), "{v}"); +} + +#[test] +fn a_paint_bucket_fill_merges_with_an_adjacent_fill_of_its_colour() { + let mut s = raw_session(); + // A red square, and lines that close an area against its right edge. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.path", json!({"d": "M100 0 L200 0 L200 100 L100 100", "fill": null, "stroke": "#000000"})); + let v = run(&mut s, "paint.bucket", json!({"x": 150, "y": 50, "color": "#ff0000"})); + assert_eq!(v["merged"], json!(true)); + assert_eq!(v["exact"], json!(true), "closed by raw lines and a fill edge: filled exactly"); + let f = fills(&s); + assert_eq!(f.len(), 1, "one red fill"); + assert!((area(&f[0]) - 20_000.0).abs() < 1.0, "{}", area(&f[0])); + // Another colour stays its own fill, up to the lines exactly. + let mut t = raw_session(); + run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000"})); + run(&mut t, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null})); + run(&mut t, "paint.bucket", json!({"x": 50, "y": 50, "color": "#00ff00"})); + let f = fills(&t); + assert_eq!(f.len(), 2); + let green = f.iter().find(|e| fill_color(e) == Rgba::parse_hex("#00ff00")).unwrap(); + assert!((area(green) - 10_000.0).abs() < 1.0, "{}", area(green)); + // Recolouring the blue square green joins the two greens (no line between them? there is + // one: the square's right side stays, so they stay two). + run(&mut t, "paint.bucket", json!({"x": 150, "y": 50, "color": "#00ff00"})); + assert_eq!(fills(&t).len(), 2, "the outline's right side divides them"); + // An open area: nothing is filled. + let mut u = raw_session(); + run(&mut u, "draw.path", json!({"d": "M0 0 L100 0 L100 100", "fill": null, "stroke": "#000000"})); + assert!(u.execute("paint.bucket", &json!({"x": 60, "y": 30})).is_err()); + // Headless sessions (Object Drawing on) keep making an object. + let mut o = Session::new(anicraft_doc::Document::default()); + run(&mut o, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000"})); + let v = run(&mut o, "paint.bucket", json!({"x": 50, "y": 50})); + assert!(v.get("merged").is_none()); +} + +#[test] +fn recolouring_a_raw_fill_joins_the_fills_of_its_new_colour() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null})); + assert_eq!(fills(&s).len(), 2); + let v = run(&mut s, "paint.bucket", json!({"x": 150, "y": 50, "color": "#ff0000"})); + assert_eq!(v["merged"], json!(true)); + let f = fills(&s); + assert_eq!(f.len(), 1); + assert!((area(&f[0]) - 20_000.0).abs() < 1.0); +} + +#[test] +fn a_pasted_raw_shape_cuts_what_it_lands_on() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 50, "h": 50, "fill": "#0000ff", "stroke": null})); + run(&mut s, "edit.copy", json!({})); + let v = run(&mut s, "edit.paste", json!({"x": 50, "y": 50})); + assert_eq!(v["merged"], json!(true)); + let red = fills(&s).into_iter().find(|e| fill_color(e) == Rgba::parse_hex("#ff0000")).unwrap(); + assert!((area(&red) - (10_000.0 - 2_500.0)).abs() < 1.0, "the blue square cut a hole: {}", area(&red)); + assert_eq!(fills(&s).len(), 3); + // The pasted piece is selected. + assert_eq!(ids(&v, "pasted").len(), 1); + // Paste in Place over itself: one blue square there, not two. + run(&mut s, "edit.paste_in_place", json!({})); + assert_eq!(fills(&s).len(), 3); + // Objects on the clipboard still go on top, whole. + run(&mut s, "draw.object_drawing", json!({"on": true})); + run(&mut s, "draw.rect", json!({"x": 500, "y": 0, "w": 10, "h": 10, "fill": "#00ff00", "stroke": null})); + run(&mut s, "edit.copy", json!({})); + let v = run(&mut s, "edit.paste", json!({"x": 50, "y": 50})); + assert_eq!(v["merged"], json!(false)); + assert_eq!(fills(&s).len(), 3); +} + +fn linear() -> Paint { + Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(200.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }] } +} + +#[test] +fn gradient_fills_take_part_in_the_merge() { + let mut s = raw_session(); + s.style.fill_paint = Some(linear()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null})); + assert_eq!(fills(&s).len(), 1, "raw, not an object"); + // A line across cuts it in two; each half shows its part of the gradient where it was. + run(&mut s, "draw.line", json!({"x0": 100, "y0": -20, "x1": 100, "y1": 120, "stroke": "#000000"})); + let f = fills(&s); + assert_eq!(f.len(), 2); + for e in &f { + let ElementKind::Shape(sh) = &e.kind else { panic!() }; + let Some(Paint::Linear { start, end, .. }) = sh.fill.as_ref().map(|p| p.transformed(&e.transform)) else { panic!("{:?}", sh.fill) }; + assert!(start.distance(Vec2::ZERO) < 1e-3 && end.distance(Vec2::new(200.0, 0.0)) < 1e-3, "{start:?} {end:?}"); + } + // Deleting the line joins the halves again: one gradient fill. + let line = raw(&s).into_iter().find(|e| fill_color(e).is_none() && matches!(&e.kind, ElementKind::Shape(sh) if sh.stroke.is_some())).unwrap(); + s.select_only([line.id]); + run(&mut s, "edit.delete", json!({})); + let halves: Vec = fills(&s).iter().map(|e| e.id.0).collect(); + run(&mut s, "raw.merge", json!({"ids": halves})); + assert_eq!(fills(&s).len(), 1); + assert!((area(&fills(&s)[0]) - 20_000.0).abs() < 1.0); + // A solid fill drawn over it cuts into the gradient as into any fill. + run(&mut s, "draw.rect", json!({"x": 50, "y": 25, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null})); + let g = fills(&s).into_iter().find(|e| fill_color(e).is_none()).unwrap(); + assert!((area(&g) - (20_000.0 - 2_500.0)).abs() < 1.0); + // A width profile still makes an object. + let mut t = raw_session(); + t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth); + run(&mut t, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0})); + assert!(raw(&t).is_empty()); + let _ = Affine::IDENTITY; +} + +#[test] +fn subselection_timings() { + // 12 × 12 outlined squares and lines across every row (ADR 0041's test drawing). + let mut s = raw_session(); + for i in 0..12 { + for j in 0..12 { + run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000", "radius": 6})); + } + run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"})); + } + // An empty outlined square for the Paint Bucket. + run(&mut s, "draw.rect", json!({"x": 700, "y": 0, "w": 40, "h": 40, "fill": null, "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + let n = s.visible_elements().len(); + let t = std::time::Instant::now(); + let v = run(&mut s, "raw.subselect", json!({"x": 320, "y": 320})); + let click = t.elapsed(); + let sel: Vec = s.selection.ids().collect(); + let t = std::time::Instant::now(); + let pts = s.raw_points(&sel); + let list = t.elapsed(); + let h = pts.handles.first().copied().unwrap(); + s.begin_gesture("Move Handle"); + let t = std::time::Instant::now(); + let r = run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 1, "dy": 1, "merge": false})); + let frame = t.elapsed(); + let t = std::time::Instant::now(); + run(&mut s, "raw.merge", json!({"ids": ids(&r, "changed")})); + let merge = t.elapsed(); + s.end_gesture(); + let t = std::time::Instant::now(); + assert_eq!(run(&mut s, "paint.bucket", json!({"x": 720, "y": 20, "color": "#00ff00"}))["exact"], json!(true)); + let bucket = t.elapsed(); + let t = std::time::Instant::now(); + let _ = s.execute("paint.bucket", &json!({"x": 45, "y": 45, "color": "#00ff00"})); + let open = t.elapsed(); + eprintln!( + "{n} raw shapes; connected set {} shapes, {} anchors, {} handles; click {:.2} ms, list {:.2} ms, handle frame {:.2} ms, merge {:.2} ms, bucket {:.2} ms (open area {:.2} ms)", + ids(&v, "selected").len(), + pts.anchors.len(), + pts.handles.len(), + click.as_secs_f64() * 1e3, + list.as_secs_f64() * 1e3, + frame.as_secs_f64() * 1e3, + merge.as_secs_f64() * 1e3, + bucket.as_secs_f64() * 1e3, + open.as_secs_f64() * 1e3 + ); +} + +#[test] +fn the_eraser_takes_gradient_fills_too() { + let mut s = raw_session(); + s.style.fill_paint = Some(linear()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null})); + let before: f32 = fills(&s).iter().map(|e| area(e)).sum(); + run(&mut s, "draw.erase", json!({"points": [[100, -20], [100, 120]], "size": 20})); + let after: f32 = fills(&s).iter().map(|e| area(e)).sum(); + assert_eq!(fills(&s).len(), 2, "cut in two"); + assert!(before - after > 1500.0, "{before} → {after}"); +} diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index 8cea6d1a..db6e1a17 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -15,7 +15,8 @@ //! a budget of their own, and only the shell knows what they are. use crate::history::StateId; -use anicraft_doc::{ColorEffect, DisplayList, Document, Rgba, evaluate_scene, evaluate_scene_camera}; +use crate::onion::OnionSkin; +use anicraft_doc::{DisplayList, Document, evaluate_scene, evaluate_scene_camera}; use anicraft_render::{RenderStats, View, render}; use rayon::prelude::*; use std::collections::{HashMap, HashSet, VecDeque}; @@ -35,7 +36,8 @@ pub struct FrameJob { pub doc: Document, pub frame: u32, pub view: View, - pub onion: bool, + /// Onion skin or Edit Multiple Frames (ADR 0047); `None`: the frame alone. + pub onion: Option, /// Seen through the scene's camera (View › Preview Through Camera, ADR 0027): what the /// movie shows, rather than the stage as edited. pub camera: bool, @@ -94,15 +96,20 @@ pub enum Raster { /// draws it). pub type Rasterizer = Arc Result<(Raster, RenderStats), String> + Send + Sync>; +/// What onion settings add to a key: nothing when they show nothing. +fn onion_key(onion: Option<&OnionSkin>) -> u64 { + onion.filter(|o| o.shows()).map_or(0, OnionSkin::key) +} + /// 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 { +pub fn scene_key(state: StateId, frame: u32, onion: Option<&OnionSkin>) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); - (state, frame, onion).hash(&mut h); + (state, frame, onion_key(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 { +pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSkin>) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); state.hash(&mut h); frame.hash(&mut h); @@ -114,18 +121,19 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 { 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); + onion_key(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), raster: 0, scene: scene_key(state, frame, onion), doc: doc.clone(), frame, view, onion, camera: false } +pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob { + let onion = onion.filter(|o| o.shows()).copied(); + FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false } } /// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and /// gives [`make_job`]'s key), keyed apart from other rasterizers' pictures. -pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob { +pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob { let mut j = make_job(state, doc, frame, view, onion); if raster != 0 { let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -136,33 +144,16 @@ pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, vie j } -/// Movie frame `frame`'s display list, with ±2 onion-skin frames (tinted red before, green after) -/// underneath, taken from the same scene only. -pub fn display_list_with_onion(doc: &Document, frame: u32, onion: bool) -> DisplayList { +/// Movie frame `frame`'s display list, with what `onion` adds underneath (onion frames or Edit +/// Multiple Frames' keyframes, ADR 0047), taken from the same scene only. +pub fn display_list_with_onion(doc: &Document, frame: u32, onion: Option<&OnionSkin>) -> DisplayList { display_list_for(doc, frame, onion, false) } /// [`display_list_with_onion`], seen through the scene's camera when `camera` (ADR 0027). -pub fn display_list_for(doc: &Document, frame: u32, onion: bool, camera: bool) -> DisplayList { - let eval = |scene: usize, f: u32| if camera { evaluate_scene_camera(doc, scene, f) } else { evaluate_scene(doc, scene, f) }; - let mut dl = DisplayList::default(); +pub fn display_list_for(doc: &Document, frame: u32, onion: Option<&OnionSkin>, camera: bool) -> DisplayList { let (scene, local) = doc.locate(frame); - if onion { - let n = i64::from(doc.timeline(scene).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(local) + off; - if f < 0 || f >= n { - continue; - } - let mut ghost = eval(scene, 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(eval(scene, local)); - dl + crate::onion::compose(doc, scene, local, onion, |scene, f| if camera { evaluate_scene_camera(doc, scene, f) } else { evaluate_scene(doc, scene, f) }) } /// Renders a job against an already evaluated scene, on the CPU oracle. @@ -201,7 +192,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>) /// Renders a job synchronously, evaluating its scene. pub fn render_job(job: &FrameJob) -> FrameImage { - render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion, job.camera)) + render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion.as_ref(), job.camera)) } /// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel. @@ -213,7 +204,7 @@ pub fn render_batch(jobs: &[FrameJob]) -> Vec { fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { let mut scenes: HashMap> = HashMap::new(); for j in jobs { - scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion, j.camera))); + scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera))); } jobs.par_iter() .map(|j| { @@ -221,7 +212,7 @@ fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id); match scenes.get(&j.scene) { Some(dl) => render_job_by(j, dl, raster), - None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion, j.camera), raster), + None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera), raster), } }) .collect() @@ -391,7 +382,7 @@ impl RenderService { } /// A job for the rasterizer in use ([`make_job_for`] with [`RenderService::raster_id`]). - pub fn job(&self, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob { + pub fn job(&self, state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob { make_job_for(self.raster_id(), state, doc, frame, view, onion) } @@ -594,7 +585,7 @@ mod tests { 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) + make_job(state, doc, frame, view, None) } #[test] @@ -629,7 +620,7 @@ mod tests { 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 full = render_job(&make_job(1, &doc, 13, View { transform: Affine::scale(z, z), width: w, height: h, background: bg }, None)); let t = 128u32; let mut jobs = Vec::new(); for ty in 0..h.div_ceil(t) { @@ -640,7 +631,7 @@ mod tests { height: t.min(h - ty * t), background: bg, }; - jobs.push((tx, ty, make_job(1, &doc, 13, view, false))); + jobs.push((tx, ty, make_job(1, &doc, 13, view, None))); } } let batch: Vec = jobs.iter().map(|(_, _, j)| j.clone()).collect(); @@ -698,10 +689,10 @@ mod tests { let doc = sample::demo(); let svc = RenderService::new(64 << 20, None); let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) }; - let cpu = svc.job(1, &doc, 9, view, false); - assert_eq!(cpu.key, make_job(1, &doc, 9, view, false).key, "no rasterizer: the oracle's keys"); + let cpu = svc.job(1, &doc, 9, view, None); + assert_eq!(cpu.key, make_job(1, &doc, 9, view, None).key, "no rasterizer: the oracle's keys"); // A stand-in GPU that paints everything one colour, and refuses onion-skinned frames. - let plain = display_list_with_onion(&doc, 9, false).items.len(); + let plain = display_list_with_onion(&doc, 9, None).items.len(); let flat: Rasterizer = Arc::new(move |dl: &DisplayList, v: &View| { if dl.items.len() > plain { return Err("too much".into()); @@ -710,23 +701,23 @@ mod tests { }); svc.set_rasterizer(Some(flat)); assert!(svc.has_rasterizer()); - let gpu = svc.job(1, &doc, 9, view, false); + let gpu = svc.job(1, &doc, 9, view, None); assert_ne!(gpu.key, cpu.key, "pictures are keyed by who drew them"); let img = svc.render_now(gpu.clone()); assert!(img.gpu && img.fallback.is_none() && img.rgba_premul[..4] == [10, 20, 30, 255]); // What it refuses, the oracle draws, saying why. - let onion = svc.job(1, &doc, 9, view, true); + let onion = svc.job(1, &doc, 9, view, Some(&OnionSkin::default())); let img = svc.render_now(onion.clone()); assert!(!img.gpu && img.fallback.as_deref() == Some("too much")); - assert_eq!(img.rgba_premul, render_job(&make_job(1, &doc, 9, view, true)).rgba_premul); + assert_eq!(img.rgba_premul, render_job(&make_job(1, &doc, 9, view, Some(&OnionSkin::default()))).rgba_premul); // Through the worker too; and a job made for an older rasterizer is drawn by the oracle. - let ahead = svc.job(1, &doc, 10, view, false); + let ahead = svc.job(1, &doc, 10, view, None); svc.prefetch(vec![ahead.clone()]); assert!(svc.wait_for(ahead.key, 10_000).is_some_and(|i| i.gpu)); svc.set_rasterizer(None); let stale = FrameJob { key: 77, ..ahead }; assert!(!render_batch_by(&[stale], &svc.slot())[0].gpu); - assert_eq!(svc.job(1, &doc, 9, view, false).key, cpu.key, "back to the oracle's keys"); + assert_eq!(svc.job(1, &doc, 9, view, None).key, cpu.key, "back to the oracle's keys"); } #[test] @@ -773,11 +764,11 @@ mod tests { Ok((Raster::Native { image: Arc::new(7u32), width: v.width + u32::from(bad), height: v.height }, RenderStats::default())) }); svc.set_rasterizer(Some(native)); - let img = svc.render_now(svc.job(1, &doc, 3, view, false)); + let img = svc.render_now(svc.job(1, &doc, 3, view, None)); assert!(img.gpu && img.rgba_premul.is_empty()); assert_eq!(img.native.as_ref().and_then(|n| n.downcast_ref::()), Some(&7)); wrong.store(true, std::sync::atomic::Ordering::Relaxed); - let img = svc.render_now(svc.job(1, &doc, 4, view, false)); + let img = svc.render_now(svc.job(1, &doc, 4, view, None)); assert!(!img.gpu && img.native.is_none() && img.fallback.as_deref() == Some("the GPU returned a wrong-sized image")); assert_eq!(img.rgba_premul.len(), 320 * 180 * 4, "the oracle drew it instead"); } @@ -794,8 +785,12 @@ mod tests { #[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); + let plain = display_list_with_onion(&doc, 10, None).items.len(); + let onion = display_list_with_onion(&doc, 10, Some(&OnionSkin::default())).items.len(); + // ±2 frames of every unlocked layer (Animate doesn't onion-skin locked ones). + let tl = doc.timeline(0); + let unlocked = display_list_with_onion(&doc, 10, None).items.iter().filter(|i| tl.layer(i.layer).is_some_and(|l| !l.locked)).count(); + assert!(unlocked < plain, "the sample has a locked layer"); + assert_eq!(onion, plain + 4 * unlocked); } } diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs new file mode 100644 index 00000000..964cfa78 --- /dev/null +++ b/crates/engine/src/selection.rs @@ -0,0 +1,349 @@ +//! The selection (ADR 0044): elements at the playhead, each named with its layer, so one +//! selection holds artwork on several layers as in Animate. +//! +//! Commands see the selection in one of three ways: +//! * **per layer** ([`Session::each_layer`]): the command's single-layer body runs once for every +//! layer that has selected items, with that layer active and the selection narrowed to it +//! (move, delete, duplicate, arrange, filters, colour effects, break apart, …). A selection on +//! the active layer alone runs the body exactly as before; +//! * **across** the layers: the command reads every selected item with its layer (align and +//! distribute, the Free Transform box, copy, convert to symbol, snapping a move); +//! * **on the active layer** only, where Animate does the same (Subselection, the Width tool, +//! the Eraser's selected fills): [`Selection::on`] with [`Session::layer`]. + +use crate::{EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, LayerId, LayerKind, evaluate_layer_elements}; +use anicraft_geom::Rect; +use serde_json::{Map, Value, json}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +/// The selected elements, in the order they were selected, each with its layer. +#[derive(Clone, Debug, Default)] +pub struct Selection { + items: Vec<(LayerId, ElementId)>, + /// The same pairs, for constant-time membership. + set: HashSet<(LayerId, ElementId)>, +} + +impl PartialEq for Selection { + fn eq(&self, other: &Self) -> bool { + self.items == other.items + } +} + +impl Eq for Selection {} + +impl Selection { + /// `ids` on `layer`. + pub fn only(layer: LayerId, ids: impl IntoIterator) -> Selection { + let mut s = Selection::default(); + s.extend_on(layer, ids); + s + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn len(&self) -> usize { + self.items.len() + } + + pub fn clear(&mut self) { + self.items.clear(); + self.set.clear(); + } + + /// Every `(layer, element)`, in selection order. + pub fn iter(&self) -> impl Iterator + '_ { + self.items.iter().copied() + } + + /// Every selected element id (ids are unique within a document), in selection order. + pub fn ids(&self) -> impl Iterator + '_ { + self.items.iter().map(|(_, e)| *e) + } + + /// The ids as plain numbers, for command results. + pub fn id_list(&self) -> Vec { + self.ids().map(|e| e.0).collect() + } + + pub fn first(&self) -> Option<(LayerId, ElementId)> { + self.items.first().copied() + } + + /// Whether `id` on `layer` is selected. + pub fn contains(&self, layer: LayerId, id: ElementId) -> bool { + self.set.contains(&(layer, id)) + } + + /// Whether `id` is selected on any layer. + pub fn has_id(&self, id: ElementId) -> bool { + self.items.iter().any(|(_, e)| *e == id) + } + + /// The selected ids on `layer`, in selection order. + pub fn on(&self, layer: LayerId) -> Vec { + self.items.iter().filter(|(l, _)| *l == layer).map(|(_, e)| *e).collect() + } + + /// The part of the selection on `layer`. + pub fn narrowed(&self, layer: LayerId) -> Selection { + Selection::only(layer, self.on(layer)) + } + + /// The layers with selected items, in the order they were first selected on. + pub fn layers(&self) -> Vec { + let mut out: Vec = Vec::new(); + for (l, _) in &self.items { + if !out.contains(l) { + out.push(*l); + } + } + out + } + + /// Adds `id` on `layer`; false when it already was selected. + pub fn insert(&mut self, layer: LayerId, id: ElementId) -> bool { + if !self.set.insert((layer, id)) { + return false; + } + self.items.push((layer, id)); + true + } + + pub fn extend_on(&mut self, layer: LayerId, ids: impl IntoIterator) { + for id in ids { + self.insert(layer, id); + } + } + + pub fn remove(&mut self, layer: LayerId, id: ElementId) -> bool { + if !self.set.remove(&(layer, id)) { + return false; + } + self.items.retain(|x| *x != (layer, id)); + true + } + + /// Selects `id` on `layer`, or lets go of it when it was selected (Shift-click). + pub fn toggle(&mut self, layer: LayerId, id: ElementId) { + if !self.remove(layer, id) { + self.insert(layer, id); + } + } + + pub fn retain(&mut self, mut keep: impl FnMut(LayerId, ElementId) -> bool) { + let set = &mut self.set; + self.items.retain(|&(l, e)| { + let k = keep(l, e); + if !k { + set.remove(&(l, e)); + } + k + }); + } + + /// Replaces what is selected on `layer` with `ids`, leaving the other layers alone. + pub fn set_on(&mut self, layer: LayerId, ids: impl IntoIterator) { + self.retain(|l, _| l != layer); + self.extend_on(layer, ids); + } +} + +/// Result keys that are values, not counts: they are not summed over layers. +const VALUE_KEYS: &[&str] = &["filters"]; + +/// One result for a command that ran on several layers: lists are joined, counts added, other +/// values come from the first layer; `layers` lists the layers it ran on. +fn merge_results(results: Vec<(LayerId, Value)>) -> Value { + let mut out = Map::new(); + for (_, v) in &results { + let Value::Object(m) = v else { continue }; + for (k, x) in m { + match (out.get_mut(k), x) { + (None, _) => { + out.insert(k.clone(), x.clone()); + } + (Some(Value::Array(a)), Value::Array(b)) => a.extend(b.iter().cloned()), + (Some(Value::Number(a)), Value::Number(b)) if !VALUE_KEYS.contains(&k.as_str()) => { + if let (Some(p), Some(q)) = (a.as_u64(), b.as_u64()) { + *a = p.saturating_add(q).into(); + } + } + _ => {} + } + } + } + out.insert("layers".into(), json!(results.iter().map(|(l, _)| l.0).collect::>())); + Value::Object(out) +} + +impl Session { + /// The elements on `layer` at the playhead (tweens applied). + pub fn elements_on(&self, layer: LayerId) -> Vec> { + self.doc.timeline(self.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() + } + + /// Whether artwork on `layer` can be selected: it is in this scene, shown and unlocked + /// (folders included), and not a folder. + pub fn selectable(&self, layer: LayerId) -> bool { + let tl = self.doc.timeline(self.scene); + let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return false }; + tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder) && !tl.locked_by_folder(layer) && !tl.hidden_by_folder(i) + } + + /// Whether a marquee or Select All gathers artwork from `layer`: a selectable layer with + /// artwork on it. The camera layer holds only the camera, and an armature layer's + /// instances are posed by their bones, so they are gathered only while active. + pub fn gathers(&self, layer: LayerId) -> bool { + let kind = self.doc.timeline(self.scene).layer(layer).map(|l| l.kind); + self.selectable(layer) && (layer == self.layer || !matches!(kind, Some(LayerKind::Camera | LayerKind::Armature))) + } + + /// The layers with selected items, top to bottom. + pub fn selected_layers(&self) -> Vec { + let mine = self.selection.layers(); + self.doc.timeline(self.scene).layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() + } + + /// Every selected element as it looks at the playhead, with its layer: layers top to + /// bottom, each in stacking order. + pub fn selected_elements(&self) -> Vec<(LayerId, Arc)> { + let mut out = Vec::new(); + for l in self.selected_layers() { + out.extend(self.elements_on(l).into_iter().filter(|e| self.selection.contains(l, e.id)).map(|e| (l, e))); + } + out + } + + /// Selects `ids` on the active layer, and nothing else. + pub fn select_only(&mut self, ids: impl IntoIterator) { + self.selection = Selection::only(self.layer, ids); + } + + /// Stage-space bounds of element `id` on `layer` at the playhead. + pub fn element_bounds_on(&self, layer: LayerId, id: ElementId) -> Rect { + let mut r = Rect::EMPTY; + for item in self.display_list().items.iter().filter(|i| i.element == id && i.layer == layer) { + let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach); + r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform)); + } + r + } + + /// Bounds of the whole selection, over every layer (the Free Transform box). + pub fn selection_bounds(&self) -> Rect { + let sel: HashSet<(LayerId, ElementId)> = self.selection.iter().collect(); + let mut r = Rect::EMPTY; + for item in self.display_list().items.iter().filter(|i| sel.contains(&(i.layer, i.element))) { + let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach); + r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform)); + } + r + } + + /// Drops selected items that are gone at the playhead, or whose layer is gone, hidden or + /// locked (a locked or hidden layer is never selected), and keeps the active layer valid. + pub fn fix_selection(&mut self) { + self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); + if self.doc.timeline(self.scene).layer(self.layer).is_none() { + self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id); + } + if self.selection.is_empty() { + return; + } + let mut present: HashMap> = HashMap::new(); + for l in self.selection.layers() { + if self.selectable(l) { + present.insert(l, self.elements_on(l).iter().map(|e| e.id).collect()); + } + } + self.selection.retain(|l, id| present.get(&l).is_some_and(|ids| ids.contains(&id))); + } + + /// Runs a command's single-layer body once for every layer with selected items, top to + /// bottom, with that layer active and the selection narrowed to it; the selection is then + /// what the runs left selected, and the active layer stays. A selection on the active layer + /// alone (or none) runs the body once, as before. + /// + /// `strict`: every layer must succeed (an error undoes the whole command). Otherwise a layer + /// where the edit does not apply (no movie clips for a filter, no text to restyle) is left + /// as it was, and the command fails only when it applies nowhere. + pub(crate) fn each_layer(&mut self, strict: bool, mut run: impl FnMut(&mut Session) -> Result) -> Result { + let layers = self.selected_layers(); + match layers.as_slice() { + [] => return run(self), + [one] if *one == self.layer => return run(self), + _ => {} + } + let active = self.layer; + let full = self.selection.clone(); + let mut after = Selection::default(); + let mut results = Vec::new(); + let mut first_err: Option = None; + for l in layers { + let before = (!strict).then(|| self.doc.clone()); + self.layer = l; + self.selection = full.narrowed(l); + // Each layer's run sees what the runs before it changed. + self.dl_cache.replace(None); + let r = run(self); + // A motion tween's target on this layer turns into property keys now (the session + // does this once per command, for one layer). + if let Some(edit) = self.motion_edit.take() + && r.is_ok() + { + crate::cmds_motion::finish_edit(self, edit); + } + self.dl_cache.replace(None); + match r { + Ok(v) => { + for (sl, id) in self.selection.iter() { + after.insert(sl, id); + } + results.push((l, v)); + } + Err(e) if strict => { + self.layer = active; + return Err(e); + } + Err(e) => { + if let Some(d) = before { + self.doc = d; + } + for (sl, id) in full.narrowed(l).iter() { + after.insert(sl, id); + } + first_err.get_or_insert(e); + } + } + } + if self.doc.timeline(self.scene).layer(active).is_some() { + self.layer = active; + } + self.selection = after; + if results.is_empty() { + return Err(first_err.unwrap_or_else(|| EngineError::State("nothing is selected".into()))); + } + Ok(merge_results(results)) + } + + /// Runs `f` with `layer` active, then makes the active layer what it was. + pub(crate) fn with_layer(&mut self, layer: LayerId, f: impl FnOnce(&mut Session) -> T) -> T { + let active = self.layer; + self.layer = layer; + self.dl_cache.replace(None); + let r = f(self); + if let Some(edit) = self.motion_edit.take() { + crate::cmds_motion::finish_edit(self, edit); + } + self.dl_cache.replace(None); + if self.doc.timeline(self.scene).layer(active).is_some() { + self.layer = active; + } + r + } +} diff --git a/crates/engine/src/selection_tests.rs b/crates/engine/src/selection_tests.rs new file mode 100644 index 00000000..6ae32395 --- /dev/null +++ b/crates/engine/src/selection_tests.rs @@ -0,0 +1,564 @@ +//! Selection across layers (ADR 0044): every command that reads the selection, with a selection +//! on two layers; the marquee across layers with raw parts; locked and hidden layers. + +use crate::Session; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId}; +use anicraft_geom::Rect; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn el_id(v: &Value) -> ElementId { + ElementId(v["element"].as_u64().unwrap()) +} + +/// Two layers, "Top" over "Bottom", one drawing object on each: Top's at (0, 0) 100 × 100, +/// Bottom's at (200, 100) 50 × 50. Both are selected; Top is active. +fn two_layers() -> (Session, LayerId, LayerId, ElementId, ElementId) { + let mut s = Session::default(); + let bottom = s.layer; + run(&mut s, "layer.rename", json!({"name": "Bottom"})); + let b = el_id(&run(&mut s, "draw.rect", json!({"x": 200, "y": 100, "w": 50, "h": 50, "fill": "#00ff00"}))); + let top = LayerId(run(&mut s, "layer.new", json!({"name": "Top"}))["layer"].as_u64().unwrap()); + let a = el_id(&run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100}))); + run(&mut s, "element.select", json!({"ids": [a.0, b.0]})); + assert_eq!(s.selected_layers(), vec![top, bottom], "top to bottom"); + (s, top, bottom, a, b) +} + +/// `id` on `layer` at the playhead. +fn element(s: &Session, layer: LayerId, id: ElementId) -> Option> { + s.elements_on(layer).into_iter().find(|e| e.id == id) +} + +fn pos(s: &Session, layer: LayerId, id: ElementId) -> (f32, f32) { + let t = element(s, layer, id).unwrap().transform.translation(); + (t.x, t.y) +} + +fn bounds(s: &Session, layer: LayerId, id: ElementId) -> Rect { + s.element_bounds_on(layer, id) +} + +// ----- the model --------------------------------------------------------------------------------- + +#[test] +fn select_takes_ids_on_any_layer_and_reports_them() { + let (mut s, top, bottom, a, b) = two_layers(); + assert!(s.selection.contains(top, a) && s.selection.contains(bottom, b)); + assert_eq!(s.layer, top, "the active layer had some of them: it stays"); + let info = s.info(); + assert_eq!(info["selection"], json!([a.0, b.0])); + assert_eq!(info["selection_layers"], json!([top.0, bottom.0])); + // Only the bottom one: its layer becomes active, as a click on it would. + run(&mut s, "element.select", json!({"ids": [b.0]})); + assert_eq!(s.layer, bottom); + // `add` keeps what was selected; `layer` says where to look. + run(&mut s, "element.select", json!({"ids": [a.0], "add": true, "layer": top.0})); + assert_eq!(s.selection.len(), 2); + assert!(s.execute("element.select", &json!({"ids": [a.0], "layer": bottom.0})).is_err(), "a is not on Bottom"); + assert!(s.execute("element.select", &json!({"ids": [999_999]})).is_err()); +} + +#[test] +fn shift_click_adds_and_removes_across_layers() { + let (mut s, top, bottom, a, b) = two_layers(); + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "element.pick", json!({"x": 50, "y": 50})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a)]); + run(&mut s, "element.pick", json!({"x": 225, "y": 125, "add": true})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a), (bottom, b)], "Shift keeps the other layer's"); + assert_eq!(s.layer, bottom, "the clicked layer becomes active"); + // A plain click on a selected element keeps the selection (so a drag moves it all). + run(&mut s, "element.pick", json!({"x": 50, "y": 50})); + assert_eq!(s.selection.len(), 2); + assert_eq!(s.layer, top); + // Shift-click again lets go of it; a plain click elsewhere selects only that. + run(&mut s, "element.pick", json!({"x": 50, "y": 50, "add": true})); + assert_eq!(s.selection.iter().collect::>(), vec![(bottom, b)]); + run(&mut s, "element.pick", json!({"x": 50, "y": 50})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a)]); +} + +#[test] +fn locked_or_hidden_layers_are_never_selected() { + let (mut s, top, bottom, a, b) = two_layers(); + // Locking a layer lets go of what was selected on it. + run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a)]); + assert!(s.execute("element.select", &json!({"ids": [b.0], "add": true})).is_err(), "locked"); + assert_eq!(run(&mut s, "element.pick", json!({"x": 225, "y": 125, "add": true}))["element"], Value::Null, "a click goes through it"); + run(&mut s, "edit.select_all", json!({})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a)], "Select All skips it"); + run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": -10, "x1": 300, "y1": 300})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a)], "so does the marquee"); + // Hiding works the same. + run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0})); + run(&mut s, "edit.select_all", json!({})); + assert_eq!(s.selection.len(), 2); + run(&mut s, "layer.toggle_visible", json!({"layer": top.0})); + assert_eq!(s.selection.iter().collect::>(), vec![(bottom, b)]); + assert!(s.execute("element.select", &json!({"ids": [a.0]})).is_err(), "hidden"); + // A locked folder locks the layers in it. + run(&mut s, "layer.toggle_visible", json!({"layer": top.0})); + run(&mut s, "layer.select", json!({"layer": top.0})); + let folder = LayerId(run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap()); + s.doc.timeline_mut(0).layer_mut(top).unwrap().parent = Some(folder); + run(&mut s, "layer.toggle_lock", json!({"layer": folder.0})); + run(&mut s, "edit.select_all", json!({})); + assert_eq!(s.selection.iter().collect::>(), vec![(bottom, b)]); +} + +#[test] +fn moving_to_another_frame_keeps_what_is_there() { + let (mut s, top, bottom, a, _) = two_layers(); + // Bottom ends at frame 1; Top goes on to frame 10. + run(&mut s, "timeline.insert_keyframe", json!({"layer": top.0, "frame": 9})); + run(&mut s, "timeline.goto", json!({"frame": 5})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a)], "Bottom has nothing at frame 6"); + assert!(!s.selected_layers().contains(&bottom)); +} + +// ----- per-layer edits ------------------------------------------------------------------------ + +#[test] +fn move_and_nudge_move_both_layers_in_one_step() { + let (mut s, top, bottom, a, b) = two_layers(); + let steps = s.history_len(); + let (pa, pb) = (pos(&s, top, a), pos(&s, bottom, b)); + let v = run(&mut s, "element.translate", json!({"dx": 5, "dy": -3})); + assert_eq!(v["moved"], 2); + assert_eq!(pos(&s, top, a), (pa.0 + 5.0, pa.1 - 3.0)); + assert_eq!(pos(&s, bottom, b), (pb.0 + 5.0, pb.1 - 3.0)); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + // A drag is one gesture: many moves, one step. + s.begin_gesture("Move"); + for _ in 0..10 { + run(&mut s, "element.translate", json!({"dx": 1, "dy": 0})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 2); + assert_eq!(pos(&s, bottom, b).0, pb.0 + 15.0); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!((pos(&s, top, a), pos(&s, bottom, b)), (pa, pb)); + assert_eq!(s.selection.len(), 2, "undo brings the selection back with it"); +} + +#[test] +fn a_move_snaps_onto_artwork_on_the_selected_layers() { + let (mut s, top, bottom, a, b) = two_layers(); + // Something unselected on Bottom, just right of Top's square (whose right edge is x = 100). + run(&mut s, "layer.select", json!({"layer": bottom.0})); + let target = el_id(&run(&mut s, "draw.rect", json!({"x": 104, "y": 0, "w": 20, "h": 20}))); + run(&mut s, "element.select", json!({"ids": [a.0, b.0]})); + assert!(!s.selection.contains(bottom, target)); + let (pa, pb) = (pos(&s, top, a), pos(&s, bottom, b)); + let v = run(&mut s, "element.translate", json!({"dx": 1, "dy": 0, "snap": 5, "from": [100, 0]})); + assert_eq!(v["snapped"]["to"], "point", "{v}"); + assert!((pos(&s, top, a).0 - (pa.0 + 4.0)).abs() < 1e-3, "the corner at (100, 0) met the target's at (104, 0)"); + assert!((pos(&s, bottom, b).0 - (pb.0 + 4.0)).abs() < 1e-3, "and the other layer moved by as much"); +} + +#[test] +fn delete_duplicate_and_arrange_work_on_each_layer() { + let (mut s, top, bottom, a, b) = two_layers(); + // Something unselected on each layer, above the selected ones. + let above_a = el_id(&run(&mut s, "draw.rect", json!({"x": 500, "y": 0, "w": 10, "h": 10}))); + run(&mut s, "layer.select", json!({"layer": bottom.0})); + let above_b = el_id(&run(&mut s, "draw.rect", json!({"x": 500, "y": 50, "w": 10, "h": 10}))); + run(&mut s, "element.select", json!({"ids": [a.0, b.0]})); + let order = |s: &Session, l: LayerId| s.elements_on(l).iter().map(|e| e.id).collect::>(); + run(&mut s, "arrange.bring_to_front", json!({})); + assert_eq!(order(&s, top), vec![above_a, a]); + assert_eq!(order(&s, bottom), vec![above_b, b]); + run(&mut s, "arrange.send_backward", json!({})); + assert_eq!(order(&s, top), vec![a, above_a]); + assert_eq!(order(&s, bottom), vec![b, above_b]); + + let v = run(&mut s, "edit.duplicate", json!({"dx": 10, "dy": 10})); + assert_eq!(v["created"].as_array().unwrap().len(), 2, "{v}"); + assert_eq!(s.elements_on(top).len(), 3); + assert_eq!(s.elements_on(bottom).len(), 3); + let copies: Vec<(LayerId, ElementId)> = s.selection.iter().collect(); + assert_eq!(copies.iter().map(|c| c.0).collect::>(), vec![top, bottom], "the copies are selected, each on its layer"); + + let steps = s.history_len(); + let v = run(&mut s, "edit.delete", json!({})); + assert_eq!(v["deleted"], 2); + assert!(s.selection.is_empty()); + assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (2, 2)); + assert_eq!(s.history_len(), steps + 1, "one step"); + s.undo().unwrap(); + assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (3, 3)); +} + +#[test] +fn properties_edits_apply_to_each_layer() { + let (mut s, top, bottom, a, b) = two_layers(); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + run(&mut s, "element.set_fill", json!({"color": "#ff0000"})); + run(&mut s, "element.set_stroke", json!({"width": 7})); + run(&mut s, "element.rename", json!({"name": "both"})); + run(&mut s, "element.set_transform", json!({"rotation": 45})); + for (l, id) in [(top, a), (bottom, b)] { + let e = element(&s, l, id).unwrap(); + assert_eq!(e.color.alpha, 0.5); + assert_eq!(e.name, "both"); + assert!((e.transform.decompose().rotation.to_degrees() - 45.0).abs() < 1e-3); + let ElementKind::Shape(sh) = &e.kind else { panic!() }; + assert_eq!(sh.fill.as_ref().map(anicraft_doc::Paint::primary_color), Some(anicraft_doc::Rgba::hex(0xff0000))); + assert_eq!(sh.stroke.as_ref().map(|st| st.width), Some(7.0)); + } +} + +#[test] +fn filters_apply_where_they_can_and_fail_where_nothing_takes_them() { + let (mut s, top, bottom, a, b) = two_layers(); + // Top's square becomes a movie clip; Bottom's stays a shape. + run(&mut s, "element.select", json!({"ids": [a.0]})); + let clip = ElementId(run(&mut s, "modify.convert_to_symbol", json!({}))["instance"].as_u64().unwrap()); + run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); + run(&mut s, "element.select", json!({"ids": [clip.0, b.0]})); + let v = run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]})); + assert_eq!((v["set"].as_u64(), v["filters"].as_u64()), (Some(1), Some(1)), "one instance, one filter: {v}"); + assert!(matches!(&element(&s, top, clip).unwrap().kind, ElementKind::Symbol { filters, .. } if filters.len() == 1)); + run(&mut s, "element.set_blend", json!({"mode": "multiply"})); + // Shapes only: nothing to filter anywhere. + run(&mut s, "element.select", json!({"ids": [b.0]})); + assert!(s.execute("element.set_filters", &json!({"filters": []})).is_err()); + assert!(element(&s, bottom, b).is_some()); +} + +#[test] +fn a_tweened_frame_gets_a_keyframe_on_each_layer() { + let (mut s, top, bottom, a, b) = two_layers(); + // Classic tweens over frames 1–10 on both layers. + for l in [top, bottom] { + run(&mut s, "timeline.insert_keyframe", json!({"layer": l.0, "frame": 9})); + run(&mut s, "timeline.create_tween", json!({"layer": l.0, "frame": 0})); + } + run(&mut s, "timeline.goto", json!({"frame": 4})); + run(&mut s, "element.select", json!({"ids": [a.0, b.0]})); + assert_eq!(s.selection.len(), 2); + run(&mut s, "element.translate", json!({"dx": 0, "dy": 30})); + for l in [top, bottom] { + let layer = s.doc.timeline(0).layer(l).unwrap(); + assert!(layer.keyframes.iter().any(|k| k.start == 4), "{}: a key at the playhead", layer.name); + } +} + +// ----- across the layers ---------------------------------------------------------------------- + +#[test] +fn align_and_distribute_work_across_layers() { + let (mut s, top, bottom, a, b) = two_layers(); + run(&mut s, "align.left", json!({})); + assert!((bounds(&s, top, a).min.x - bounds(&s, bottom, b).min.x).abs() < 1e-3); + run(&mut s, "align.bottom", json!({})); + assert!((bounds(&s, top, a).max.y - bounds(&s, bottom, b).max.y).abs() < 1e-3); + // A third on Bottom: the three centres spread evenly. + run(&mut s, "layer.select", json!({"layer": bottom.0})); + let c = el_id(&run(&mut s, "draw.rect", json!({"x": 400, "y": 400, "w": 20, "h": 20}))); + run(&mut s, "element.select", json!({"ids": [a.0, b.0, c.0]})); + run(&mut s, "align.distribute_v", json!({})); + let mut ys: Vec = [(top, a), (bottom, b), (bottom, c)].iter().map(|&(l, id)| bounds(&s, l, id).center().y).collect(); + ys.sort_by(f32::total_cmp); + assert!(((ys[1] - ys[0]) - (ys[2] - ys[1])).abs() < 1e-3, "{ys:?}"); +} + +#[test] +fn free_transform_turns_the_combined_box() { + let (mut s, top, bottom, a, b) = two_layers(); + let before = s.selection_bounds(); + assert_eq!(before, bounds(&s, top, a).union(&bounds(&s, bottom, b)), "one box for the whole selection"); + let c = before.center(); + run(&mut s, "modify.rotate_cw", json!({})); + let after = s.selection_bounds(); + assert!((after.center().x - c.x).abs() < 1e-2 && (after.center().y - c.y).abs() < 1e-2, "about the combined centre"); + assert!((after.width() - before.height()).abs() < 1e-2, "turned a quarter"); + // modify.transform applies the same matrix on both layers. + let (pa, pb) = (pos(&s, top, a), pos(&s, bottom, b)); + run(&mut s, "modify.transform", json!({"a": 1, "b": 0, "c": 0, "d": 1, "e": 3, "f": 4})); + assert_eq!(pos(&s, top, a), (pa.0 + 3.0, pa.1 + 4.0)); + assert_eq!(pos(&s, bottom, b), (pb.0 + 3.0, pb.1 + 4.0)); + run(&mut s, "modify.flip_h", json!({})); + run(&mut s, "modify.remove_transform", json!({})); + for (l, id) in [(top, a), (bottom, b)] { + assert!((element(&s, l, id).unwrap().transform.decompose().rotation).abs() < 1e-4); + } +} + +#[test] +fn copy_and_paste_keep_each_layer() { + let (mut s, top, bottom, ..) = two_layers(); + let v = run(&mut s, "edit.copy", json!({})); + assert_eq!((v["copied"].as_u64(), v["layers"].as_u64()), (Some(2), Some(2))); + // Back where they came from, each on its layer. + let v = run(&mut s, "edit.paste_in_place", json!({})); + assert_eq!(v["layers"], json!([top.0, bottom.0]), "{v}"); + assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (2, 2)); + assert_eq!(s.selected_layers(), vec![top, bottom], "the pasted copies are selected"); + // Cut takes both away in one step. + let steps = s.history_len(); + run(&mut s, "edit.cut", json!({})); + assert_eq!((s.elements_on(top).len(), s.elements_on(bottom).len()), (1, 1)); + assert_eq!(s.history_len(), steps + 1); + // Into another document: layers named after the copied ones are made for them. + run(&mut s, "file.new", json!({"confirm": true})); + let first = s.layer; + let v = run(&mut s, "edit.paste", json!({"x": 300, "y": 200})); + let layers = s.doc.timeline(0).layers.clone(); + assert_eq!(layers.len(), 2, "{v}"); + assert_eq!(layers[0].id, first, "the first copied layer lands on the active one"); + assert_eq!(layers[1].name, "Bottom", "the next is made, named after the copied one"); + assert_eq!(s.elements_on(layers[0].id).len(), 1); + assert_eq!(s.elements_on(layers[1].id).len(), 1); + // One copied layer always goes on the active layer, as before. + let lower = s.elements_on(layers[1].id)[0].id; + run(&mut s, "element.select", json!({"ids": [lower.0]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "layer.select", json!({"layer": first.0})); + run(&mut s, "edit.paste_in_place", json!({})); + assert_eq!(s.elements_on(first).len(), 2); + assert_eq!(s.selected_layers(), vec![first]); +} + +#[test] +fn convert_to_symbol_keeps_the_layers_inside_and_lands_on_the_topmost() { + let (mut s, top, bottom, a, b) = two_layers(); + let center = s.selection_bounds().center(); + let px = |s: &Session| anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let was = px(&s); + let steps = s.history_len(); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Both"})); + assert_eq!(s.history_len(), steps + 1); + assert_eq!(v["layer"], top.0); + let inst = ElementId(v["instance"].as_u64().unwrap()); + assert_eq!(s.selection.iter().collect::>(), vec![(top, inst)]); + assert_eq!(s.layer, top); + assert!(element(&s, top, a).is_none() && element(&s, bottom, b).is_none(), "both moved into the symbol"); + assert!(s.elements_on(bottom).is_empty()); + let t = element(&s, top, inst).unwrap().transform.translation(); + assert!((t.x - center.x).abs() < 1e-3 && (t.y - center.y).abs() < 1e-3, "registered at the combined centre"); + let sym = s.doc.library.iter().find(|x| x.name == "Both").unwrap(); + let names: Vec<&str> = sym.timeline.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, vec!["Top", "Bottom"], "the layers, as they were stacked"); + let inside: Vec = sym.timeline.layers.iter().flat_map(|l| l.keyframes[0].elements.iter().map(|e| e.id)).collect(); + assert_eq!(inside, vec![a, b]); + // It looks the same as before. + let now = px(&s); + for (x, y) in [(225, 125), (50, 50), (150, 150)] { + assert_eq!(now.pixel(x, y), was.pixel(x, y), "at ({x}, {y})"); + } + // Break Apart brings both back onto the top layer, selected. + let v = run(&mut s, "modify.break_apart", json!({})); + assert_eq!(v["created"], 2); + assert_eq!(s.selection.len(), 2); +} + +#[test] +fn break_apart_works_on_each_layer() { + let (mut s, top, bottom, a, b) = two_layers(); + for (l, id) in [(top, a), (bottom, b)] { + run(&mut s, "element.select", json!({"ids": [id.0], "layer": l.0})); + run(&mut s, "modify.convert_to_symbol", json!({})); + } + run(&mut s, "edit.select_all", json!({})); + assert_eq!(s.selected_layers(), vec![top, bottom]); + let v = run(&mut s, "modify.break_apart", json!({})); + assert_eq!(v["created"], 2, "{v}"); + assert!(s.elements_on(top).iter().chain(s.elements_on(bottom).iter()).all(|e| matches!(e.kind, ElementKind::Shape(_)))); + assert_eq!(s.selected_layers(), vec![top, bottom]); +} + +// ----- the marquee across layers with raw parts (ADR 0041) ------------------------------------ + +/// Raw squares on two layers: Top's 0..100, Bottom's 200..300 (both 0..100 high). +fn raw_two_layers() -> (Session, LayerId, LayerId) { + let mut s = Session::default(); + s.style.object_drawing = false; + let bottom = s.layer; + run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null})); + let top = LayerId(run(&mut s, "layer.new", json!({"name": "Top"}))["layer"].as_u64().unwrap()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null})); + run(&mut s, "edit.deselect", json!({})); + s.mark_saved(); + (s, top, bottom) +} + +fn area(e: &Element) -> f64 { + let ElementKind::Shape(sh) = &e.kind else { return 0.0 }; + sh.path + .flatten(&e.transform, 0.05) + .iter() + .map(|pl| { + let n = pl.points.len(); + let twice: f64 = (0..n).filter_map(|i| Some(f64::from(pl.points.get(i)?.cross(*pl.points.get((i + 1) % n)?)))).sum(); + twice * 0.5 + }) + .sum::() + .abs() +} + +#[test] +fn the_marquee_cuts_raw_parts_on_every_layer() { + let (mut s, top, bottom) = raw_two_layers(); + let saved = s.doc.clone(); + // The lower half of both squares. + let v = run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": 50, "x1": 310, "y1": 110})); + assert_eq!(v["cut"], 2, "one piece inside on each layer: {v}"); + assert_eq!(s.selected_layers(), vec![top, bottom]); + for l in [top, bottom] { + let picked: Vec> = s.elements_on(l).into_iter().filter(|e| s.selection.contains(l, e.id)).collect(); + assert_eq!(picked.len(), 1); + assert!((area(&picked[0]) - 5000.0).abs() < 1.0, "half the square: {}", area(&picked[0])); + assert_eq!(s.elements_on(l).len(), 2, "cut in two on its own layer"); + } + assert!(!s.is_dirty(), "a marquee alone leaves the document saved"); + // Letting go takes the cut back exactly, on both layers. + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "element.pick", json!({"x": 900, "y": 900})); + assert!(s.doc == saved, "the cut is healed on both layers"); + + // A move uses the cut: one step from before it, and the pieces merge back per layer. + run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": 50, "x1": 310, "y1": 110})); + let steps = s.history_len(); + s.begin_gesture("Move"); + run(&mut s, "element.translate", json!({"dx": 0, "dy": 40})); + run(&mut s, "draw.drop", json!({})); + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1, "the move and the drop are one step"); + for l in [top, bottom] { + let total: f64 = s.elements_on(l).iter().map(|e| area(e)).sum(); + assert!((total - 10_000.0).abs() < 2.0, "both halves still there: {total}"); + let lowest = s.elements_on(l).iter().map(|e| s.element_bounds_on(l, e.id).max.y).fold(f32::MIN, f32::max); + assert!((lowest - 140.0).abs() < 0.5, "the lower half moved down: {lowest}"); + } + s.undo().unwrap(); + assert!(s.doc == saved, "one undo goes straight back to the whole drawings"); +} + +#[test] +fn the_marquee_with_shift_adds_across_layers_and_raw_merge_works_per_layer() { + let (mut s, top, bottom) = raw_two_layers(); + run(&mut s, "raw.select_rect", json!({"x0": -10, "y0": -10, "x1": 50, "y1": 110})); + assert_eq!(s.selected_layers(), vec![top]); + assert_eq!(s.layer, top); + run(&mut s, "raw.select_rect", json!({"x0": 250, "y0": -10, "x1": 310, "y1": 110, "add": true})); + assert_eq!(s.selected_layers(), vec![top, bottom], "Shift keeps the first layer's parts"); + // Merging the selection again joins each layer's pieces on that layer only. + run(&mut s, "element.set_fill", json!({"color": "#ff0000"})); + run(&mut s, "raw.merge", json!({})); + for l in [top, bottom] { + assert!(s.elements_on(l).len() <= 2, "{} pieces", s.elements_on(l).len()); + let total: f64 = s.elements_on(l).iter().map(|e| area(e)).sum(); + assert!((total - 10_000.0).abs() < 2.0, "{total}"); + } + // A marquee that starts over a layer with nothing makes the topmost hit layer active. + run(&mut s, "layer.select", json!({"layer": top.0})); + run(&mut s, "raw.select_rect", json!({"x0": 190, "y0": -10, "x1": 310, "y1": 110})); + assert_eq!(s.layer, bottom); +} + +// ----- robustness ------------------------------------------------------------------------------ + +#[test] +fn every_command_survives_a_selection_on_two_layers() { + let mut cmds = crate::commands(); + cmds.retain(|c| !c.id.starts_with("file.")); + for spec in cmds { + for p in [json!({}), json!({"dx": 3, "dy": 4, "x": 50, "y": 50, "name": "x", "alpha": 0.5, "filters": [], "mode": "multiply", "loop": "loop", "kind": "movie_clip", "color": "#123456", "profile": "bulge", "text": "t"})] { + let (mut s, ..) = two_layers(); + let _ = s.execute(spec.id, &p); + // Undo and redo always work, and the selection stays on visible, unlocked layers. + let _ = s.undo(); + let _ = s.redo(); + for (l, _) in s.selection.iter() { + assert!(s.selectable(l), "{}: selection on an unselectable layer", spec.id); + } + let _ = anicraft_render::render_frame(&s.doc, 0, 0.25); + } + } +} + +/// Timings across layers (ADR 0044's table; run with +/// `cargo test -p anicraft-engine selection_timings -- --ignored --nocapture`). +#[test] +#[ignore] +fn selection_timings() { + let mut s = Session::default(); + s.style.object_drawing = false; + // 8 layers, each with 6 × 6 outlined raw squares: 288 fills and their outlines. + for l in 0..8 { + if l > 0 { + run(&mut s, "layer.new", json!({})); + } + for i in 0..6 { + for j in 0..6 { + run(&mut s, "draw.rect", json!({"x": i * 50 + l * 3, "y": j * 50 + l * 3, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000"})); + } + } + } + run(&mut s, "edit.deselect", json!({})); + let layers = s.doc.timeline(0).layers.len(); + let shapes: usize = s.doc.timeline(0).layers.iter().map(|l| s.elements_on(l.id).len()).sum(); + eprintln!("{shapes} raw shapes on {layers} layers"); + let time = |s: &mut Session, label: &str, reps: u32, f: &dyn Fn(&mut Session)| { + let t = std::time::Instant::now(); + for _ in 0..reps { + f(s); + } + eprintln!("{label}: {:.2} ms", t.elapsed().as_secs_f64() * 1000.0 / f64::from(reps)); + }; + time(&mut s, "select all", 20, &|s| { + let _ = s.execute("edit.select_all", &json!({})); + }); + time(&mut s, "fix_selection (after every command)", 20, &|s| s.fix_selection()); + s.begin_gesture("Move"); + time(&mut s, "move frame, every layer", 20, &|s| { + let _ = s.execute("element.translate", &json!({"dx": 0.5, "dy": 0})); + }); + time(&mut s, "snapping move frame, every layer", 20, &|s| { + let _ = s.execute("element.translate", &json!({"dx": 0.5, "dy": 0, "snap": 10, "from": [0, 0]})); + }); + s.end_gesture(); + s.undo().unwrap(); + time(&mut s, "marquee cut and heal, every layer", 10, &|s| { + let _ = s.execute("raw.select_rect", &json!({"x0": 65, "y0": 65, "x1": 215, "y1": 215})); + let _ = s.execute("edit.deselect", &json!({})); + }); + let v = run(&mut s, "raw.select_rect", json!({"x0": 65, "y0": 65, "x1": 215, "y1": 215})); + eprintln!("a marquee selects {} parts on {} layers ({} cut)", s.selection.len(), s.selected_layers().len(), v["cut"]); +} + +#[test] +fn clicking_a_layer_name_selects_its_artwork() { + let (mut s, top, bottom, a, b) = two_layers(); + // Another element on Bottom: the click takes both. + run(&mut s, "layer.select", json!({"layer": bottom.0})); + let c = el_id(&run(&mut s, "draw.rect", json!({"x": 400, "y": 400, "w": 20, "h": 20}))); + run(&mut s, "layer.select", json!({"layer": top.0})); + assert!(s.selection.is_empty(), "without `select`, as before"); + let v = run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true})); + assert_eq!(v["selected"], json!([b.0, c.0])); + assert_eq!(s.layer, bottom); + assert_eq!(s.selection.iter().collect::>(), vec![(bottom, b), (bottom, c)]); + // Again on the same layer: still all of it. On a locked layer: active, nothing selected. + run(&mut s, "element.select", json!({"ids": [a.0]})); + run(&mut s, "layer.select", json!({"layer": top.0, "select": true})); + assert_eq!(s.selection.iter().collect::>(), vec![(top, a)]); + run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0})); + run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true})); + assert_eq!(s.layer, bottom); + assert!(s.selection.is_empty()); + // At a frame where the layer is empty, nothing is selected. + run(&mut s, "layer.toggle_lock", json!({"layer": bottom.0})); + run(&mut s, "timeline.insert_keyframe", json!({"layer": top.0, "frame": 5})); + run(&mut s, "timeline.goto", json!({"frame": 5})); + run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true})); + assert!(s.selection.is_empty()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4ea6acf9..d1f34945 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -215,16 +215,16 @@ fn undoable_bulk_deletions_ask_but_are_not_blocked() { 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]; + let orig = s.selection.ids().next().unwrap(); 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_ne!(s.selection.ids().next().unwrap(), orig, "pasted elements get fresh ids"); + let pasted = els.iter().find(|e| e.id == s.selection.ids().next().unwrap()).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(); + let last = s.visible_elements().into_iter().find(|e| e.id == s.selection.ids().next().unwrap()).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})); @@ -241,12 +241,17 @@ fn copy_paste_cut_and_paste_in_place() { fn clipboard_carries_symbols_into_another_document() { let mut s = Session::new(sample::demo()); run(&mut s, "layer.select", json!({"index": 0})); + // Select All takes every unlocked layer's artwork (ADR 0044). run(&mut s, "edit.select_all", json!({})); - run(&mut s, "edit.copy", json!({})); + let copied = run(&mut s, "edit.copy", json!({})); + let used = s.doc.library.len(); 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!(s.doc.library.iter().any(|x| x.name == "Ball"), "the Ball symbol came along"); + assert_eq!(s.doc.library.len(), used); + // Each copied layer lands on a layer of its own, made for it here. + assert_eq!(s.doc.timeline(0).layers.len() as u64, copied["layers"].as_u64().unwrap()); 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()); @@ -280,10 +285,10 @@ fn align_and_distribute() { } 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(); + let lefts: Vec = s.selection.ids().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(); + let mut ys: Vec = s.selection.ids().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 @@ -481,13 +486,13 @@ fn commands_png(s: &Session) -> Vec { 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]; + let a = s.selection.ids().next().unwrap(); run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100})); - let b = s.selection[0]; + let b = s.selection.ids().next().unwrap(); run(&mut s, "element.pick", json!({"x": 75, "y": 75})); - assert_eq!(s.selection, vec![b]); + assert_eq!(s.selection.ids().collect::>(), vec![b]); run(&mut s, "element.pick", json!({"x": 10, "y": 10})); - assert_eq!(s.selection, vec![a]); + assert_eq!(s.selection.ids().collect::>(), vec![a]); run(&mut s, "element.pick", json!({"x": 500, "y": 500})); assert!(s.selection.is_empty()); } @@ -547,6 +552,12 @@ fn panic_hunt_every_command() { json!({"id": 3, "profile": [[0, 1e30, -5], ["x"], [0.5, 16, 16]], "index": u64::MAX, "t": -0.5, "left": 1e9, "width": f64::MAX}), json!({"id": 3, "profile": "taper_both", "index": 0, "t": 1, "x": 1e30, "y": -1e30, "left": 0, "right": 16}), json!({"profile": (0..500).map(|i| json!([f64::from(i) / 500.0, 2, 2])).collect::>()}), + // Stroke styles (ADR 0046): junk, extremes and patterns that would be very fine. + json!({"cap": "none", "join": "miter", "miter": 100, "dash": [0, 1e-30], "dash_offset": -1e4, "style": "dashed"}), + json!({"cap": 7, "join": "mitre", "miter": f64::NAN, "dash": vec![1e4; 16], "dot_spacing": 0, "style": "dotted"}), + json!({"style": "dotted", "dot_spacing": 0, "x0": 0, "y0": 0, "x1": 1e6, "y1": 1, "stroke_width": 1000}), + json!({"dash": [0.001, 0.001], "x0": -1e6, "y0": 0, "x1": 1e6, "y1": 0, "x": 0, "y": 0}), + json!({"dash": "x", "cap": "square", "style": "ragged", "dash_offset": 1e30}), json!({"sound": SOUND, "sync": "stream", "repeat": 9999, "loop": true, "extend": true, "frame": 99_999}), json!({"sound": SOUND, "sync": "nope", "repeat": 0, "loop": "x", "name": ""}), json!({"sound": SOUND, "frame": 3, "extend": true, "name": "renamed"}), @@ -580,10 +591,38 @@ fn panic_hunt_every_command() { json!({"points": [[0, 0], [40, 40], [90, 5]], "size": 30, "mode": "selected_fills", "x": 30, "y": 30, "slop": 0}), json!({"points": [[45, 45]], "size": 2000, "mode": "inside", "x": 45, "y": 45, "other": true, "fill": false, "stroke": true}), json!({"points": [[5, 5], [55, 55]], "size": 4, "mode": "lines", "shape": "square", "x": 1, "y": 1, "fill": "yes"}), + // The Selection tool on raw shapes (ADR 0041): corners and edges of the raw rectangles, + // stale and hostile point lists, huge snaps and marquees, segments that aren't there. + json!({"x": 30, "y": 30, "to_x": 1e7, "to_y": -1e7, "snap": 1e9, "merge": false, "dx": 1e7, "dy": -1e7}), + json!({"x": 60, "y": 45, "to_x": 30.1, "to_y": 30, "snap": 10, "points": [[1, 99_999], [u64::MAX, 0]], "cmd": 1, "t": 2}), + json!({"x": 45, "y": 30, "dx": 5, "dy": 5, "cmd": u64::MAX, "t": f64::NAN, "id": 2, "slop": 1e9}), + json!({"x0": 10, "y0": 10, "x1": 45, "y1": 75, "add": true, "from": [1, 2, 3], "snap": 3}), + json!({"x0": -1e7, "y0": 1e7, "x1": 1e7, "y1": -1e7, "add": false, "from": [45, 45], "snap": 0.2}), + json!({"x0": 30, "y0": 30, "x1": 30, "y1": 30, "point_slop": -5, "ids": [u64::MAX], "points": "x"}), + // Subselection on raw shapes (ADR 0042): handles that aren't there or move too far, + // anchors to move along that are hostile, connected sets of anything. + json!({"id": 3, "cmd": 1, "slot": 2, "dx": 1e30, "dy": 0, "x": 30, "y": 30, "to_x": 31, "to_y": 30, "with": [[30, 30], [1e30, 0]]}), + json!({"id": 5, "cmd": u64::MAX, "slot": 9, "dx": 1, "dy": 1, "with": "x", "x0": 0, "y0": 0, "x1": 1e9, "y1": 1e9}), + json!({"id": 4, "cmd": 2, "slot": 1, "dx": -3, "dy": 2, "x": 60, "y": 60, "to_x": 61, "to_y": 61, "with": [[60, 60], [30, 90], [90, 30]], "merge": false}), // Kept scripts (ADR 0013 tier 1): odd text, unknown languages, class names that aren't. json!({"text": "\u{0}\r\n]]>\u{202e}stop();", "language": "other", "class": "a.b", "base": "c", "symbol": 1}), json!({"text": "x".repeat(1 << 20), "language": 3, "class": "not a class", "base": ""}), json!({"text": "", "language": "ActionScript3", "class": "", "base": "Orphan"}), + // Bones (ADR 0043): the rigged session's bones are 100 and 102 (its armature layer 101), + // its instances 10–12. + json!({"bone": 102, "x": 1e30, "y": -1e30, "local": [1e9, "a"], "frame": 99_999}), + json!({"bone": 102, "x": 0, "y": 0, "local": [f64::MAX, 0], "angle": 1e9, "rotate_by": -1e9, "dx": 1e7, "dy": -1e7}), + json!({"bone": 100, "min": 400, "max": -400, "constrain": true, "pinned": "x"}), + json!({"bone": 100, "min": 10, "max": 10, "constrain": "yes", "pinned": true, "x": 250, "y": 250}), + json!({"from": 10, "to": 12, "head": [0, 0], "tail": [1e30, 0], "name": "x".repeat(300)}), + json!({"from": 12, "to": 10, "head": [5], "tail": "x", "bone": u64::MAX}), + json!({"from": 11, "to": 13, "head": [-1e6, 1e6], "layer": 101}), + // Edit Multiple Frames (ADR 0047): ranges past the end or reversed, items that aren't + // there or aren't triples, moves at the limits. + json!({"first": 0, "last": 99_999, "dx": 1e7, "dy": -1e7, "items": [[0, 0, 1], "x", [u64::MAX, u64::MAX, u64::MAX]]}), + json!({"first": u64::MAX, "last": 0, "dx": 5, "dy": 5, "items": []}), + json!({"first": 40, "last": 0, "dx": 3, "dy": -2}), + json!({"first": 0, "last": 100_001, "dx": f64::NAN, "dy": 0, "items": [[1, 2]]}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); @@ -617,7 +656,28 @@ fn panic_hunt_every_command() { for p in [json!({"x": 0, "y": 0, "w": 60, "h": 60}), json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"}), json!({"x": 1, "y": 1, "w": 10, "h": 10, "radius": 5})] { raw.execute("draw.rect", &p).unwrap(); } - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw] { + // An armature: two bones, posed at two frames with a limit and a pin (ADR 0043). + let (mut rig, b1, b2) = crate::tests_bone::rigged(); + for (id, p) in [("bone.pose", json!({"bone": b1, "angle": 30, "frame": 8})), ("bone.set_limits", json!({"bone": b2, "min": -30, "max": 30})), ("bone.pin", json!({"bone": b1, "pinned": true}))] { + rig.execute(id, &p).unwrap(); + } + assert_eq!((b1, b2), (100, 102), "the hostile params name these bones"); + rig.set_frame(4); + // Raw drawings and an object on two layers, selected on both through a marquee's cut that + // is still provisional (ADR 0041, 0044). + let mut layered = Session::default(); + layered.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("layer.new", json!({})), + ("draw.rect", json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"})), + ("draw.rect", json!({"x": 200, "y": 0, "w": 20, "h": 20, "object": true})), + ("raw.select_rect", json!({"x0": 20, "y0": 20, "x1": 250, "y1": 50})), + ] { + layered.execute(id, &p).unwrap(); + } + assert_eq!(layered.selected_layers().len(), 2, "the fuzz starts with a selection on two layers"); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -843,7 +903,7 @@ fn moving_an_anchor_brings_its_handles_and_is_one_undo_step_in_a_gesture() { 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; + let id = s.selection.ids().next().unwrap().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})); @@ -854,7 +914,7 @@ fn moves_follow_the_element_transform() { 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 id = s.selection.ids().next().unwrap().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. @@ -876,7 +936,7 @@ fn add_delete_and_convert_points() { 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; + let inst = s.selection.ids().next().unwrap().0; assert!(s.execute("path.add_point", &json!({"id": inst, "x": 0, "y": 0})).is_err()); } @@ -1179,7 +1239,7 @@ fn opening_an_xfl_folder_imports_it_untitled() { let text = s.doc.timeline(s.scene).layers[0].keyframes[0].elements.iter().find(|e| matches!(e.kind, ElementKind::Text(_))).cloned().expect("a text element"); assert_eq!(text.name, "title"); assert!(dl.items.iter().any(|i| matches!(i.fill, Some(anicraft_doc::Paint::Solid(c)) if c == anicraft_doc::Rgba::hex(0x0000ff))), "the text renders"); - s.selection = vec![text.id]; + s.select_only([text.id]); run(&mut s, "text.edit", json!({"text": "Hello again"})); // Saved and opened again, it is the same text. let file = dir.join("imported.anicraft"); @@ -1738,9 +1798,10 @@ fn images_import_as_bitmaps_render_save_and_export() { run(&mut s, "edit.select_all", json!({})); run(&mut s, "edit.duplicate", json!({})); let svg = crate::cmds_file::frame_svg(&s.doc, 0); - // Two images, three instances (the JPEG one was duplicated): each image is embedded once. + // Two images, four instances (Select All took both layers, ADR 0044): each image is + // embedded once. assert_eq!(svg.matches("data:image/png;base64,").count(), 2); - assert_eq!(svg.matches(">(), vec![id]); let el = s.active_layer().unwrap().keyframe_at(s.frame).unwrap().elements.iter().find(|e| e.id == id).unwrap().clone(); assert_eq!(el.name, "dot.png"); assert_eq!(el.transform.apply(anicraft_geom::Vec2::new(3.0, 2.0)), anicraft_geom::Vec2::new(100.0, 50.0), "centred on x/y"); @@ -1853,7 +1914,7 @@ fn text_lays_out_renders_edits_saves_and_breaks_apart() { let mut s = Session::default(); let v = run(&mut s, "text.create", json!({"text": "Hello", "x": 100, "y": 50, "size": 64, "color": "#cc2200"})); let id = ElementId(v["element"].as_u64().unwrap()); - assert_eq!(s.selection, vec![id]); + assert_eq!(s.selection.ids().collect::>(), vec![id]); assert!(v["width"].as_f64().unwrap() > 64.0); let text = |s: &Session| match &s.visible_elements().iter().find(|e| e.id == id).unwrap().kind { ElementKind::Text(t) => t.clone(), @@ -1907,7 +1968,7 @@ fn text_lays_out_renders_edits_saves_and_breaks_apart() { run(&mut s, "element.select", json!({"ids": [id.0]})); let before = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); run(&mut s, "modify.break_apart", json!({})); - assert!(matches!(s.visible_elements().iter().find(|e| s.selection.contains(&e.id)).unwrap().kind, ElementKind::Shape(_))); + assert!(matches!(s.visible_elements().iter().find(|e| s.selection.has_id(e.id)).unwrap().kind, ElementKind::Shape(_))); assert_eq!(anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().data, before.data, "a shape exactly like the text"); let fonts = run(&mut s, "text.fonts", json!({})); assert!(fonts["families"].as_array().is_some_and(|f| !f.is_empty())); diff --git a/crates/engine/src/tests_actions.rs b/crates/engine/src/tests_actions.rs index 697c094e..bf45089e 100644 --- a/crates/engine/src/tests_actions.rs +++ b/crates/engine/src/tests_actions.rs @@ -16,7 +16,7 @@ fn with_instance(kind: &str) -> (Session, u64) { let id = s.execute("draw.rect", &json!({"x": 100, "y": 100, "w": 80, "h": 40})).unwrap()["element"].as_u64().unwrap(); s.execute("element.select", &json!({"ids": [id]})).unwrap(); let v = s.execute("modify.convert_to_symbol", &json!({"name": "Thing"})).unwrap(); - let inst = v["instance"].as_u64().or_else(|| s.selection.first().map(|e| e.0)).unwrap(); + let inst = v["instance"].as_u64().or_else(|| s.selection.first().map(|(_, e)| e.0)).unwrap(); s.execute("symbol.set_kind", &json!({"kind": kind})).unwrap(); (s, inst) } diff --git a/crates/engine/src/tests_bone.rs b/crates/engine/src/tests_bone.rs new file mode 100644 index 00000000..d21f2a01 --- /dev/null +++ b/crates/engine/src/tests_bone.rs @@ -0,0 +1,255 @@ +//! Bones and inverse kinematics end to end (ADR 0043): building an armature with the Bone +//! tool's commands, posing by angle and by IK, pose tweens, limits and pins, removal, undo, +//! the file format, refusals, analytic renders and plug-in policy. + +use super::*; +use anicraft_doc::{BlendMode, ColorEffect, Document, ElementKind, LoopMode, Paint, Rgba, Shape, Stage, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_geom::{Affine, Path}; +use anicraft_render::render_frame; +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}"), + } +} + +pub(crate) const ROOT: u64 = 10; +pub(crate) const ARM: u64 = 11; +pub(crate) const HAND: u64 = 12; +const SHAPE: u64 = 13; + +/// A 500 × 300 stage, 20 frames, with three instances of a 100 × 10 black bar (registration at +/// its left end) along y = 100 from x = 100, 200 and 300, and a plain shape below them. +pub(crate) fn three_bars() -> Session { + let mut d = Document { stage: Stage { width: 500, height: 300, ..Stage::default() }, ..Document::default() }; + let bar = SymbolId(1); + let mut inner = Layer::new(LayerId(2), "bar"); + inner.keyframes[0] = Arc::new({ + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); + k + }); + d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } }); + let shape = Arc::new(Element { id: ElementId(SHAPE), name: String::new(), transform: Affine::translate(100.0, 250.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::BLACK))) }); + let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); + l.keyframes = vec![Arc::new({ + let mut k = Keyframe::new(0, 20); + k.elements = vec![inst(ROOT, 100.0), inst(ARM, 200.0), inst(HAND, 300.0), shape]; + k + })]; + d.next_id = 100; + Session::new(d) +} + +/// [`three_bars`] rigged as a chain: shoulder (200, 100) → elbow (300, 100) → wrist (400, 100). +pub(crate) fn rigged() -> (Session, u64, u64) { + let mut s = three_bars(); + let b1 = run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM, "head": [200, 100], "tail": [300, 100]}))["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add", json!({"from": ARM, "to": HAND, "tail": [400, 100]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +fn bone_at(s: &mut Session, frame: u32, bone: u64) -> Value { + let v = run(s, "bone.info", json!({"frame": frame})); + v["armatures"][0]["bones"].as_array().unwrap().iter().find(|b| b["id"] == bone).cloned().unwrap() +} + +fn pt(v: &Value) -> Vec2 { + Vec2::new(v[0].as_f64().unwrap() as f32, v[1].as_f64().unwrap() as f32) +} + +fn transform_of(s: &Session, frame: u32, id: u64) -> Affine { + let tl = s.doc.timeline(s.scene); + tl.layers.iter().find_map(|l| evaluate_layer_elements(l, frame).and_then(|(_, e)| e.iter().find(|e| e.id.0 == id).map(|e| e.transform))).unwrap() +} + +#[test] +fn the_bone_tool_moves_instances_onto_an_armature_layer() { + let (mut s, b1, b2) = rigged(); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 2); + let arm = &tl.layers[0]; + assert_eq!(arm.kind, LayerKind::Armature); + assert_eq!(arm.name, "Armature_1"); + assert_eq!(s.layer, arm.id, "the armature layer is active"); + let ids: Vec = arm.keyframes[0].elements.iter().map(|e| e.id.0).collect(); + assert_eq!(ids, vec![ROOT, ARM, HAND]); + assert_eq!((arm.keyframes[0].start, arm.keyframes[0].duration), (0, 20), "the pose spans the timeline"); + let rest: Vec = tl.layers[1].keyframes[0].elements.iter().map(|e| e.id.0).collect(); + assert_eq!(rest, vec![SHAPE], "the instances left their layer; the shape stayed"); + // Nothing moved on the stage. + assert_eq!(transform_of(&s, 0, HAND), Affine::translate(300.0, 100.0)); + let b = bone_at(&mut s, 0, b2); + assert!(pt(&b["head"]).distance(Vec2::new(300.0, 100.0)) < 1e-3, "the second bone starts where the first ends"); + assert!(pt(&b["tail"]).distance(Vec2::new(400.0, 100.0)) < 1e-3); + assert_eq!(b["parent_bone"], b1); + assert_eq!(bone_at(&mut s, 0, b1)["parent_bone"], Value::Null); +} + +#[test] +fn bone_add_refuses_what_cant_be_joined() { + let mut s = three_bars(); + let bad = |s: &mut Session, p: Value| s.execute("bone.add", &p).unwrap_err().to_string(); + assert!(bad(&mut s, json!({"from": ROOT, "to": ROOT})).contains("two different")); + assert!(bad(&mut s, json!({"from": ROOT, "to": SHAPE})).contains("symbol")); + assert!(bad(&mut s, json!({"from": ROOT, "to": 999})).contains("no instance")); + assert!(bad(&mut s, json!({"from": ROOT})).contains("required")); + assert!(bad(&mut s, json!({"from": ROOT, "to": ARM, "head": [1, "x"]})).contains("[x, y]")); + run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM})); + assert!(bad(&mut s, json!({"from": HAND, "to": ARM})).contains("armature"), "start on the armature"); + assert!(bad(&mut s, json!({"from": ARM, "to": ROOT})).contains("root")); + run(&mut s, "bone.add", json!({"from": ROOT, "to": HAND})); + assert!(bad(&mut s, json!({"from": ARM, "to": HAND})).contains("already")); + assert_eq!(s.history_len(), 2, "refusals leave no undo steps"); +} + +#[test] +fn ik_drags_reach_and_one_drag_is_one_undo_step() { + let (mut s, b1, b2) = rigged(); + let steps = s.history_len(); + s.begin_gesture("Drag Bone"); + let mut last = Value::Null; + for i in 0..=20 { + let t = i as f32 / 20.0; + last = run(&mut s, "bone.solve", json!({"bone": b2, "x": 400.0 - 100.0 * t, "y": 100.0 + 80.0 * t})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1, "one drag, one undo step"); + assert_eq!(last["reached"], true, "{last}"); + let end = pt(&bone_at(&mut s, 0, b2)["tail"]); + assert!(end.distance(Vec2::new(300.0, 180.0)) < 0.5, "{end:?}"); + // The root stays where it was; the shoulder and elbow turned. + assert_eq!(transform_of(&s, 0, ROOT), Affine::translate(100.0, 100.0)); + assert!(bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap().abs() > 1.0); + // An unreachable target: the chain points straight at it, the root still put. + let v = run(&mut s, "bone.solve", json!({"bone": b2, "x": 200, "y": 320})); + assert_eq!(v["reached"], false); + assert!(bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap().abs() < 0.1, "straight"); + let tail = pt(&bone_at(&mut s, 0, b2)["tail"]); + assert!(tail.distance(Vec2::new(200.0, 300.0)) < 0.05, "{tail:?}"); + assert_eq!(transform_of(&s, 0, ROOT), Affine::translate(100.0, 100.0)); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(transform_of(&s, 0, HAND), Affine::translate(300.0, 100.0), "undo puts the pose back"); +} + +#[test] +fn limits_and_pins_hold_in_every_pose() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 60})); + let v = run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -20, "max": 20})); + assert_eq!(v["constrain"], true); + assert!((bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap() - 20.0).abs() < 1e-3, "the pose came inside the new limits"); + run(&mut s, "bone.solve", json!({"bone": b2, "x": 230, "y": 160})); + let a = bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap(); + assert!((-20.0 - 1e-3..=20.0 + 1e-3).contains(&a), "{a}"); + assert!(s.execute("bone.set_limits", &json!({"bone": b2, "min": 30, "max": 10})).is_err()); + assert!(s.execute("bone.set_limits", &json!({"bone": b2, "min": -400})).is_err()); + run(&mut s, "bone.set_limits", json!({"bone": b2, "constrain": false})); + assert_eq!(bone_at(&mut s, 0, b2)["min"], Value::Null); + // Pinned: the shoulder keeps its angle while the elbow follows the drag. + let before = bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap(); + run(&mut s, "bone.pin", json!({"bone": b1, "pinned": true})); + run(&mut s, "bone.solve", json!({"bone": b2, "x": 350, "y": 60})); + assert_eq!(bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap(), before); + assert!(s.execute("bone.solve", &json!({"bone": b1, "x": 0, "y": 0})).unwrap_err().to_string().contains("pinned")); +} + +#[test] +fn poses_key_frames_and_tween_with_easing() { + let (mut s, b1, _) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90, "frame": 10})); + let l = s.doc.timeline(0).layers[0].clone(); + assert_eq!(l.keyframes.iter().map(|k| k.start).collect::>(), vec![0, 10], "a pose keyed at frame 10"); + let a = |s: &mut Session, f| bone_at(s, f, b1)["angle"].as_f64().unwrap(); + assert_eq!(a(&mut s, 0), 0.0, "exact at the first key"); + assert!((a(&mut s, 10) - 90.0).abs() < 1e-4, "exact at the second key"); + assert!((a(&mut s, 5) - 45.0).abs() < 1e-3, "half way"); + // The hand rides the shoulder: at frame 10 it hangs straight down from it. + assert!(transform_of(&s, 10, HAND).translation().distance(Vec2::new(200.0, 200.0)) < 1e-3); + // The span's easing shapes the pose tween. + run(&mut s, "timeline.set_easing", json!({"frame": 0, "easing": "QuadIn"})); + assert!((a(&mut s, 5) - 22.5).abs() < 1e-3, "{}", a(&mut s, 5)); + // Posing inside the tween keys that frame with the pose it showed. + run(&mut s, "bone.pose", json!({"bone": b1, "rotate_by": 10, "frame": 5})); + assert!((a(&mut s, 5) - 32.5).abs() < 1e-3); + assert_eq!(s.doc.timeline(0).layers[0].keyframes.len(), 3); + // Moving the root moves the whole armature, in that pose. + run(&mut s, "bone.pose", json!({"dx": 10, "dy": 5, "frame": 10})); + assert!(transform_of(&s, 10, HAND).translation().distance(Vec2::new(210.0, 205.0)) < 1e-3); +} + +#[test] +fn artwork_edits_are_refused_on_the_armature_layer() { + let (mut s, _, _) = rigged(); + s.select_only([ElementId(HAND)]); + for (id, p) in [("draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})), ("element.translate", json!({"dx": 5, "dy": 0})), ("edit.delete", json!({})), ("timeline.create_motion_tween", json!({}))] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("armature"), "{id}: {e}"); + } + assert!(s.execute("layer.set_type", &json!({"type": "normal"})).is_err()); +} + +#[test] +fn removing_bones_frees_the_instances_where_they_are() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90})); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 0, "frame": 10})); + // Two poses: removing asks first (undoable tier). + let c = s.confirmation("bone.remove", &json!({"bone": b2})).unwrap(); + assert!(!c.irreversible && c.message.contains("2 keyframes"), "{}", c.message); + let hand = transform_of(&s, 0, HAND); + let v = run(&mut s, "bone.remove", json!({"bone": b2})); + assert_eq!(v["armature_removed"], false); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 3); + assert_eq!(tl.layers[1].keyframes[0].elements[0].id.0, HAND, "the hand is on a layer of its own"); + assert!(tl.layers[0].keyframes.iter().all(|k| k.pose.0.iter().all(|j| j.bone.0 != b2))); + assert_eq!(transform_of(&s, 0, HAND), hand, "where it was"); + // The last bone takes the armature with it; the instances stay as they look. + let arm = transform_of(&s, 0, ARM); + let v = run(&mut s, "bone.remove", json!({"bone": b1})); + assert_eq!(v["armature_removed"], true); + assert!(s.doc.timeline(0).layers.iter().all(|l| l.kind != LayerKind::Armature)); + assert_eq!(transform_of(&s, 0, ARM), arm); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(s.doc.timeline(0).layers[0].armature.as_ref().unwrap().bones.len(), 2); +} + +#[test] +fn armatures_survive_a_file_round_trip_and_render_the_pose() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -45, "max": 45})); + run(&mut s, "bone.pin", json!({"bone": b1, "pinned": true})); + run(&mut s, "bone.pin", json!({"bone": b1, "pinned": false})); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90, "frame": 10})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + for f in [0, 5, 10] { + assert_eq!(render_frame(&back, f, 1.0).unwrap().data, render_frame(&s.doc, f, 1.0).unwrap().data); + } + // At frame 10 the arm hangs from the shoulder: the bar covers (200, 150), not (250, 100). + let pm = render_frame(&s.doc, 10, 1.0).unwrap(); + assert!(pm.pixel(200, 150).unwrap()[0] < 0.1, "the arm points down"); + assert!(pm.pixel(250, 100).unwrap()[0] > 0.9, "and is no longer along the line"); + // Older files (no armature) load as before; a file's armature on another kind of layer is + // dropped. + let old = crate::format::from_json(&crate::format::to_json(&Document::default()).unwrap()).unwrap(); + assert!(old.timeline(0).layers.iter().all(|l| l.armature.is_none())); + let mut odd = s.doc.clone(); + Arc::make_mut(&mut odd.timeline_mut(0).layers[0]).kind = LayerKind::Normal; + let odd = crate::format::from_json(&crate::format::to_json(&odd).unwrap()).unwrap(); + assert!(odd.timeline(0).layers[0].armature.is_none()); +} + +#[test] +fn plug_ins_may_pose_armatures() { + for id in ["bone.add", "bone.remove", "bone.set_limits", "bone.pin", "bone.pose", "bone.solve", "bone.info"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/tests_script.rs b/crates/engine/src/tests_script.rs index bb9efdc2..e8827631 100644 --- a/crates/engine/src/tests_script.rs +++ b/crates/engine/src/tests_script.rs @@ -132,21 +132,53 @@ fn kept_scripts_survive_the_file_and_hostile_ones_are_dropped_whole() { } #[test] -fn nothing_runs_a_kept_script() { +fn scripts_in_the_subset_run_and_the_rest_are_kept_and_said_so() { let mut s = Session::new(sample::interactive()); let layer = s.doc.timeline(0).layers[0].id.0; - // A script that would stop the movie and trace, on the show keyframe instead of its actions. - s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "trace(\"xyzzy-kept\"); stop();"})).unwrap(); + // A script that stops the movie and traces, on the show keyframe instead of its actions. + let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "trace(\"xyzzy-\" + 1); stop();"})).unwrap(); + assert_eq!((v["runs"].as_bool(), v["problems"].as_array().map(Vec::len)), (Some(true), Some(0)), "{v}"); let v = s.execute("control.test_movie", &json!({"frames": 20, "events": [{"tick": 2, "type": "click", "x": 640, "y": 400}]})).unwrap(); let lines: Vec<&str> = v["output"].as_array().unwrap().iter().filter_map(|l| l["line"].as_str()).collect(); - assert!(lines.is_empty(), "{lines:?}"); + assert_eq!(lines.first().copied(), Some("Frame script runs: Scene 1 › Actions, frame 2"), "{lines:?}"); + assert!(lines.contains(&"xyzzy-1"), "{lines:?}"); + assert!(v["state"]["frame"].as_u64().unwrap() < 10 && v["state"]["playing"] == false, "it stopped: {}", v["state"]); + // The HTML export runs it too, as the same actions. + let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap(); + assert!(out.html.contains("xyzzy-1") && !out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report); + // One outside the subset doesn't run at all, and Test Movie says where and why. + let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "stop(); +var n:int = 1;"})).unwrap(); + assert_eq!(v["runs"], false); + assert_eq!(v["problems"][0], json!({"line": 2, "column": 1, "message": "variables (`var`) aren't supported yet"})); + let v = s.execute("control.test_movie", &json!({"frames": 20, "events": [{"tick": 2, "type": "click", "x": 640, "y": 400}]})).unwrap(); + assert_eq!(v["output"][0]["line"], "Frame script not run: Scene 1 › Actions, frame 2: line 2, column 1: variables (`var`) aren't supported yet"); assert!(v["state"]["frame"].as_u64().unwrap() > 10, "it played on: {}", v["state"]); - // The HTML export draws the movie and says the script isn't in it. let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap(); assert!(out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report); - assert!(!out.html.contains("xyzzy-kept"), "the script's text isn't exported"); + assert!(!out.html.contains("var n:int"), "a kept script's text isn't exported"); + let list = s.execute("script.list", &json!({"text": false})).unwrap(); + assert_eq!((list["frames"][0]["runs"].as_bool(), list["frames"][0]["problems"][0]["line"].as_u64()), (Some(false), Some(2))); // Plug-ins may read and write kept scripts, as they may actions. - for id in ["script.set", "script.clear", "script.list", "script.set_class"] { + for id in ["script.set", "script.clear", "script.list", "script.set_class", "script.check"] { assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); } } + +#[test] +fn script_check_says_what_a_text_would_do_and_changes_nothing() { + let mut s = Session::new(sample::interactive()); + let before = s.doc.clone(); + let v = s.execute("script.check", &json!({"text": "stop(); +btn.addEventListener(MouseEvent.CLICK, go); +function go(e:MouseEvent):void { gotoAndPlay(\"run\"); } +navigateToURL(new URLRequest(\"x\"));"})).unwrap(); + assert_eq!(v["runs"], true); + assert_eq!(v["describe"], json!(["Stop", "On click (btn): Go to “run” and play"])); + assert_eq!(v["steps"][1]["listen"]["target"], "btn"); + assert_eq!(v["notes"][0]["line"], 4); + let v = s.execute("script.check", &json!({"text": "stop();", "language": "actionscript1or2"})).unwrap(); + assert_eq!((v["runs"].as_bool(), v["problems"][0]["line"].as_u64()), (Some(false), Some(0))); + assert!(s.execute("script.check", &json!({})).is_err()); + assert!(s.doc == before && s.undo_label().is_none()); +} diff --git a/crates/engine/tests/golden/mod.rs b/crates/engine/tests/golden/mod.rs index 4c12430d..0ddee4d3 100644 --- a/crates/engine/tests/golden/mod.rs +++ b/crates/engine/tests/golden/mod.rs @@ -62,8 +62,9 @@ pub fn check(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], to compare(golden, name, width, height, rgba, tol) } -/// The comparison [`check`] makes when it isn't updating. -fn compare(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], tol: Tolerance) -> Result<(), String> { +/// The comparison [`check`] makes when it isn't updating (a test whose renders must match +/// another test's goldens compares only, never writing them). +pub fn compare(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], tol: Tolerance) -> Result<(), String> { assert_eq!(rgba.len(), (width * height * 4) as usize); let keep = |why: String| -> String { let actual = out_dir().join(format!("{name}.actual.png")); diff --git a/crates/engine/tests/wasm.rs b/crates/engine/tests/wasm.rs index cff25485..4e6b28df 100644 --- a/crates/engine/tests/wasm.rs +++ b/crates/engine/tests/wasm.rs @@ -47,7 +47,7 @@ fn the_stage_renders_without_a_thread() { let svc = RenderService::new(64 << 20, None); let view = anicraft_engine::render::View::stage(&s.doc, 0.5); // No worker thread can start, so a request renders right away. - let img = svc.request(svc.job(s.state, &s.doc, 3, view, false)).expect("rendered on this thread"); + let img = svc.request(svc.job(s.state, &s.doc, 3, view, None)).expect("rendered on this thread"); assert!(img.error.is_none() && img.width > 0 && img.rgba_premul.iter().any(|&b| b != 0)); } diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index 5158083b..26fa9b41 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -27,6 +27,7 @@ const FRAMES: &[(&str, &[u32])] = &[ ("filters", &[0]), ("gradients", &[0]), ("guides", &[0, 6, 12]), + ("interactive", &[0, 9]), ("masks", &[0]), ("primitives", &[0]), ("scenes", &[0, 3, 7, 8, 10]), @@ -42,6 +43,9 @@ const SCALE: f32 = 0.5; /// What a frame must show at a stage point: (package, frame, x, y, colour). const PROBES: &[(&str, u32, f32, f32, u32)] = &[ + // The door movie clip and the button, on the authored timeline (scripts never change it). + ("interactive", 0, 90.0, 90.0, 0x8D5524), + ("interactive", 9, 240.0, 90.0, 0x2A9D8F), // Both sides of a shared edge, the hole, the hex-coordinate triangle. ("shapes", 0, 45.0, 50.0, 0xD9452B), ("shapes", 0, 80.0, 30.0, 0x2B6CD9), @@ -172,3 +176,31 @@ fn every_package_opens_with_file_open_and_round_trips_through_the_file_format() assert!(s.doc == t.doc, "{case}: the saved document opens differently"); } } + +/// Animate's raw shapes open as raw shapes, each keyframe's merged into one drawing (ADR 0042), +/// and look as they did: the goldens still match. A raw outline is one stroke per side (ADR +/// 0031), so at a corner two round caps overlap where one round join was and their antialiased +/// edges add up: a few corner pixels may be darker (47 of the shapes frame's 14,400). +#[test] +fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() { + let mut failures = Vec::new(); + let (mut raw_total, mut merged_total) = (0, 0); + for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text")) { + let mut s = Session::default(); + let info = s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); + let raw = s.doc.scenes.iter().flat_map(|sc| sc.timeline.layers.iter()).chain(s.doc.library.iter().flat_map(|sym| sym.timeline.layers.iter())).flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()).filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).count(); + raw_total += raw; + // (Keyframes a tween joins keep their shapes as they came.) + merged_total += info["merged_keyframes"].as_u64().unwrap_or(0); + for &f in *frames { + let (w, h, rgba) = render(&s.doc, f); + let golden = corpus().join(case).join("golden").join(format!("frame-{f:03}.png")); + let corners = golden::Tolerance { pixels: 0.005, ..golden::DEFAULT }; + if let Err(e) = golden::compare(&golden, &format!("{case}-merged-frame-{f:03}"), w, h, &rgba, corners) { + failures.push(e); + } + } + } + assert!(raw_total > 0 && merged_total > 0, "the corpus has raw shapes, merged: {raw_total} shapes, {merged_total} keyframes"); + assert!(failures.is_empty(), "merged raw shapes look different:\n{}", failures.join("\n")); +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 6f76f7e3..e0b75dd1 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -10,6 +10,7 @@ pub mod clip; pub mod edit; pub mod morph; pub mod planar; +pub mod raw; mod fit; mod path; pub mod svg; @@ -18,7 +19,7 @@ pub mod walk; pub use affine::{Affine, Decomposed}; pub use fit::fit_curve; -pub use path::{FillRule, Path, PathCmd, Polyline}; +pub use path::{FillRule, Path, PathCmd, Polyline, segment_distance}; use serde::{Deserialize, Serialize}; use std::ops::{Add, Mul, Neg, Sub}; diff --git a/crates/geom/src/planar.rs b/crates/geom/src/planar.rs index f08e4fdb..d21de9d1 100644 --- a/crates/geom/src/planar.rs +++ b/crates/geom/src/planar.rs @@ -2,8 +2,9 @@ //! //! The shapes, bottom to top, are cut into a planar map: //! - every segment is cut where it meets another (exact sub-curves by de Casteljau); -//! - points closer than [`SNAP`] become one vertex, and pieces that run along each other become -//! one edge; +//! - points closer than [`SNAP`] become one vertex (anchors meet at their midpoint; a point that +//! lands on a line goes onto it, and the line stays), and pieces that run along each other +//! become one edge; //! - each face of the map takes the fill of the topmost shape covering it (winding at a point //! inside the face). //! @@ -52,6 +53,8 @@ pub struct Piece { pub style: u32, pub path: Path, pub item: usize, + /// Inside the cutter ([`merge_cut`]); always false from [`merge`]. + pub inside: bool, } #[derive(Clone, Debug, Default, PartialEq)] @@ -62,7 +65,28 @@ pub struct Merged { /// Merges `items` (bottom to top). `None` when there is too much to merge at once. pub fn merge(items: &[Item]) -> Option { - let segs = collect(items)?; + merge_with(items, None) +} + +/// [`merge`], also cutting everything along `cutter` (a closed outline that only cuts, such as +/// the Selection tool's marquee, ADR 0041): fills are split at its edges and stroke runs end +/// there, nothing of the cutter itself comes out, and each piece says whether it lies inside it. +pub fn merge_cut(items: &[Item], cutter: &Path) -> Option { + merge_with(items, Some(cutter)) +} + +/// The item number the cutter's segments carry. +const CUTTER: usize = usize::MAX; + +fn merge_with(items: &[Item], cutter: Option<&Path>) -> Option { + let mut segs = collect(items)?; + if let Some(path) = cutter { + let edge = Item { path, fill: None, fill_rule: FillRule::EvenOdd, stroke: Some(0) }; + segs.extend(collect(&[edge])?.into_iter().map(|s| Seg { item: CUTTER, ..s })); + if segs.len() > MAX_SEGMENTS { + return None; + } + } let splits = cut(&segs)?; let map = Map::build(&segs, &splits); Some(map.output(items, &segs)) @@ -448,12 +472,44 @@ struct Map { slot: Vec, } -/// Greedy clustering: a point joins the first vertex within [`TOL`], so none moves farther. +/// Greedy clustering: a point joins the nearest vertex whose first point is within [`TOL`]. struct Verts { pts: Vec

, grid: HashMap<(i64, i64), Vec>, } +/// What fell into one vertex, to decide where it goes (issue #42: anchor points closer than +/// [`SNAP`] meet at their midpoint; a point that lands on a line goes onto it, and the line stays). +#[derive(Default)] +struct Cluster { + /// A point inside a segment, away from its ends (where an end lies on a line, or lines + /// cross): the vertex stays there. + on_line: Option

, + /// Segment ends, each position once. + ends: Vec

, +} + +impl Cluster { + fn add(&mut self, p: P, end: bool, on_line: bool) { + if on_line { + self.on_line.get_or_insert(p); + } else if end && !self.ends.iter().any(|q| q.dist(p) < 1e-9) && self.ends.len() < 64 { + self.ends.push(p); + } + } + fn place(&self, seed: P) -> P { + if let Some(p) = self.on_line { + return p; + } + if self.ends.is_empty() { + return seed; + } + let n = self.ends.len() as f64; + let sum = self.ends.iter().fold(P::default(), |s, p| s.add(*p)); + sum.mul(1.0 / n) + } +} + impl Verts { fn cell(p: P) -> (i64, i64) { ((p.x / TOL).floor() as i64, (p.y / TOL).floor() as i64) @@ -491,13 +547,35 @@ fn pinned(c: &Cubic, line: bool, a: P, b: P) -> Cubic { impl Map { fn build(segs: &[Seg], splits: &[Vec]) -> Map { let mut vs = Verts { pts: Vec::new(), grid: HashMap::new() }; + // Every cut point into a vertex first, then each vertex placed (see `Cluster`), so the + // pieces are pinned to where their vertices end up. + let mut clusters: Vec = Vec::new(); + let mut ids: Vec> = Vec::with_capacity(segs.len()); + for (s, ts) in segs.iter().zip(splits) { + let mut row = Vec::with_capacity(ts.len()); + for &t in ts { + let end = t <= 0.0 || t >= 1.0; + let p = if t <= 0.0 { s.c[0] } else if t >= 1.0 { s.c[3] } else { eval(&s.c, t) }; + let v = vs.at(p); + if clusters.len() <= v { + clusters.resize_with(v + 1, Cluster::default); + } + let on_line = !end && p.dist(s.c[0]) >= TOL && p.dist(s.c[3]) >= TOL; + clusters[v].add(p, end, on_line); + row.push(v); + } + ids.push(row); + } + for (p, c) in vs.pts.iter_mut().zip(&clusters) { + *p = c.place(*p); + } let mut edges: Vec = Vec::new(); let mut by_ends: HashMap<(usize, usize), Vec> = HashMap::new(); - for (si, (s, ts)) in segs.iter().zip(splits).enumerate() { - for w in ts.windows(2) { + for (si, ((s, ts), row)) in segs.iter().zip(splits).zip(&ids).enumerate() { + for (w, v) in ts.windows(2).zip(row.windows(2)) { let (t0, t1) = (w[0], w[1]); let c = sub(&s.c, t0, t1); - let (a, b) = (vs.at(c[0]), vs.at(c[3])); + let (a, b) = (v[0], v[1]); if a == b { continue; // shorter than SNAP (longer loops were halved when collected) } @@ -655,16 +733,19 @@ impl Map { .iter() .enumerate() .map(|(e, edge)| { - let z = edge.strokes.iter().copied().max()?; + let z = edge.strokes.iter().copied().filter(|&i| i < items.len()).max()?; let (l, r) = (face(2 * e), face(2 * e + 1)); let hidden = l.zip(r).is_some_and(|(l, r)| covers[l].iter().any(|&i| i > z && covers[r].contains(&i))); (!hidden).then_some(z) }) .collect(); + // The cutter's edges divide like a stroke that never shows. + let cut_edge: Vec = self.edges.iter().map(|e| e.strokes.contains(&CUTTER)).collect(); + let cutter = Region::new(segs, CUTTER, cut_edge.contains(&true)); // Faces of one fill with no stroke between them are one region. let mut group = Dsu::new(samples.len()); for (e, stroke) in stroke_of.iter().enumerate() { - if let (None, Some(l), Some(r)) = (stroke, face(2 * e), face(2 * e + 1)) + if let (None, false, Some(l), Some(r)) = (stroke, cut_edge[e], face(2 * e), face(2 * e + 1)) && l != r && fill_of(l).map(|f| f.0) == fill_of(r).map(|f| f.0) && fill_of(l).is_some() @@ -674,11 +755,13 @@ impl Map { } let roots = group.roots(); let gid = |f: Option| f.filter(|&f| fill_of(f).is_some()).and_then(|f| roots.get(f).copied()); - // Each region's style and topmost item. - let mut top: HashMap = HashMap::new(); - for f in 0..samples.len() { + // Each region's style and topmost item, and whether it is inside the cutter (the + // cutter's edges bound every region, so one sample tells). + let mut top: HashMap = HashMap::new(); + for (f, sample) in samples.iter().enumerate() { if let (Some(g), Some((style, item))) = (gid(Some(f)), fill_of(f)) { - let t = top.entry(g).or_insert((style, item)); + let inside = sample.is_some_and(|p| cutter.covers(p, FillRule::EvenOdd)); + let t = top.entry(g).or_insert((style, item, inside)); t.1 = t.1.max(item); } } @@ -708,25 +791,27 @@ impl Map { match piece_of.get(&g) { Some(&i) => out.fills[i].path.cmds.extend(path.cmds), None => { - let (style, item) = top.get(&g).copied().unwrap_or((0, 0)); + let (style, item, inside) = top.get(&g).copied().unwrap_or((0, 0, false)); piece_of.insert(g, out.fills.len()); - out.fills.push(Piece { style, path, item }); + out.fills.push(Piece { style, path, item, inside }); } } } - self.strokes(items, &stroke_of, segs, &mut out); + self.strokes(items, &stroke_of, &cut_edge, &cutter, segs, &mut out); out } - /// Visible strokes, chained through vertices where exactly two of one style meet smoothly. - fn strokes(&self, items: &[Item], stroke_of: &[Option], segs: &[Seg], out: &mut Merged) { + /// Visible strokes, chained through vertices where exactly two of one style meet smoothly + /// (and never across the cutter). + fn strokes(&self, items: &[Item], stroke_of: &[Option], cut_edge: &[bool], cutter: &Region, segs: &[Seg], out: &mut Merged) { let style = |e: usize| stroke_of[e].and_then(|z| items[z].stroke); let shown: Vec> = self.around.iter().map(|l| l.iter().copied().filter(|&h| style(h / 2).is_some()).collect()).collect(); + let on_cut: Vec = self.around.iter().map(|l| l.iter().any(|&h| cut_edge[h / 2])).collect(); // The half that carries on from `h` at its end, if the run goes on. let carry = |h: Half| -> Option { let v = self.dest(h); let list = &shown[v]; - if list.len() != 2 { + if list.len() != 2 || on_cut[v] { return None; } let n = list.iter().copied().find(|&o| o != (h ^ 1))?; @@ -763,7 +848,9 @@ impl Map { h = n; } let item = halves.iter().filter_map(|&h| stroke_of[h / 2]).max().unwrap_or(0); - out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item }); + // A run along the cutter's edge counts as inside it. + let inside = halves.iter().any(|&h| cut_edge[h / 2]) || halves.get(halves.len() / 2).is_some_and(|&h| cutter.covers(eval(&self.curve(h), 0.5), FillRule::EvenOdd)); + out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item, inside }); } } diff --git a/crates/geom/src/planar_tests.rs b/crates/geom/src/planar_tests.rs index 66be2e50..6ee8526e 100644 --- a/crates/geom/src/planar_tests.rs +++ b/crates/geom/src/planar_tests.rs @@ -256,3 +256,77 @@ fn a_search_that_runs_out_of_steps_declines_the_merge() { let (a, b) = (arc(100.0), arc(100.3)); assert_eq!(merge(&[stroked(&a, None, 1), stroked(&b, None, 1)]).map(|m| m.strokes.len()), Some(2)); } + +// ----- snapping within SNAP and cutting (ADR 0041) ----------------------------------------------- + +fn ends(p: &Path) -> Vec { + p.anchors().into_iter().map(|(_, v)| v).collect() +} + +#[test] +fn anchors_within_snap_meet_at_their_midpoint() { + // Issue #42 §4: two ends 0.1 apart (a keyboard nudge's reach) become one point halfway. + let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(50.0, 0.0)); + let b = Path::line(Vec2::new(50.1, 0.1), Vec2::new(50.1, 50.0)); + let m = run(&[stroked(&a, None, 1), stroked(&b, None, 1)]); + assert_eq!(m.strokes.len(), 2, "{m:?}"); + let mid = Vec2::new(50.05, 0.05); + for s in &m.strokes { + assert!(ends(&s.path).iter().any(|p| p.distance(mid) < 1e-4), "{:?}", s.path); + } + // A fill corner and a line end too: the corner moves halfway, so the outline stays closed. + let r = rect(0.0, 0.0, 10.0, 10.0); + let l = Path::line(Vec2::new(10.12, 10.0), Vec2::new(30.0, 30.0)); + let m = run(&[fill(&r, 1), stroked(&l, None, 2)]); + let corner = Vec2::new(10.06, 10.0); + assert!(m.fills.iter().any(|f| ends(&f.path).iter().any(|p| p.distance(corner) < 1e-4)), "{m:?}"); + assert!(m.strokes.iter().any(|s| ends(&s.path).iter().any(|p| p.distance(corner) < 1e-4)), "{m:?}"); +} + +#[test] +fn an_end_near_a_line_goes_onto_it_and_the_line_stays_straight() { + // Issue #42 §4: "an anchor point snaps to a line without modifying it". + let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)); + let b = Path::line(Vec2::new(40.0, 0.15), Vec2::new(40.0, 60.0)); + let m = run(&[stroked(&a, None, 1), stroked(&b, None, 1)]); + // The long line is cut where the other meets it (a T), and every piece stays on y = 0. + let flat: Vec<&Piece> = m.strokes.iter().filter(|s| ends(&s.path).iter().all(|p| p.y.abs() < 1e-4)).collect(); + assert_eq!(flat.len(), 2, "{m:?}"); + assert!(m.strokes.iter().any(|s| ends(&s.path).iter().any(|p| p.distance(Vec2::new(40.0, 0.0)) < 1e-4) && ends(&s.path).iter().any(|p| p.y > 59.0)), "the end moved onto the line: {m:?}"); +} + +#[test] +fn a_cutter_splits_fills_and_strokes_and_the_parts_add_up() { + let r = rect(0.0, 0.0, 100.0, 80.0); + let marquee = rect(60.0, -10.0, 100.0, 50.0); + let m = merge_cut(&[stroked(&r, Some(1), 2)], &marquee).unwrap_or_default(); + // The fill in two: 40 × 40 inside (the marquee is x 60–160, y −10–40), the rest outside, + // adding up to the whole. + let inside: f32 = m.fills.iter().filter(|p| p.inside).map(|p| area(&p.path)).sum(); + let outside: f32 = m.fills.iter().filter(|p| !p.inside).map(|p| area(&p.path)).sum(); + assert!(near(inside, 40.0 * 40.0, 0.5), "{inside}"); + assert!(near(inside + outside, 8000.0, 0.5), "{}", inside + outside); + assert!(m.fills.iter().all(|p| p.style == 1)); + // Nothing of the marquee comes out: only the rectangle's own sides, cut where it crosses + // them (the top and the right side are cut there). + let len = |p: &Path| p.flatten(&crate::Affine::IDENTITY, 0.01).iter().map(|pl| pl.points.windows(2).map(|w| w[0].distance(w[1])).sum::()).sum::(); + let total: f32 = m.strokes.iter().map(|s| len(&s.path)).sum(); + assert!(near(total, 360.0, 0.05), "{total}"); + let inner: f32 = m.strokes.iter().filter(|s| s.inside).map(|s| len(&s.path)).sum(); + assert!(near(inner, 40.0 + 40.0, 0.05), "the top's right 40 and the right side's upper 40: {inner}"); + assert!(m.strokes.iter().all(|s| s.style == 2)); + // Without a cutter nothing is inside. + assert!(run(&[stroked(&r, Some(1), 2)]).fills.iter().all(|p| !p.inside)); +} + +#[test] +fn a_cutter_over_a_curve_cuts_exact_pieces() { + let c = Path::ellipse(0.0, 0.0, 50.0, 50.0); + let marquee = rect(-100.0, -100.0, 100.0, 100.0); + let m = merge_cut(&[fill(&c, 1)], &marquee).unwrap_or_default(); + let inside: f32 = m.fills.iter().filter(|p| p.inside).map(|p| area(&p.path)).sum(); + let all: f32 = m.fills.iter().map(|p| area(&p.path)).sum(); + // A quarter of the disc, to within the ellipse's Bézier approximation. + assert!(near(inside * 4.0, all, 1.0), "{inside} of {all}"); + assert_eq!(m.fills.len(), 2); +} diff --git a/crates/geom/src/raw.rs b/crates/geom/src/raw.rs new file mode 100644 index 00000000..e5f66f93 --- /dev/null +++ b/crates/geom/src/raw.rs @@ -0,0 +1,244 @@ +//! Editing raw shapes that share edges and points (ADR 0041). A layer's merged drawing is one +//! element per fill region and per stroke run (ADR 0031), so a corner or an edge they share is +//! stored once in each of them. Bending an edge or moving a point with the Selection tool has to +//! change every copy the same way, so the drawing stays joined. These are the pure parts: finding +//! the copies of an edge in a path and replacing them, making sure a path has an anchor where +//! another shape ends, and the nearest point on a curve (for snapping). + +use crate::walk::cubic_point; +use crate::{Affine, Path, PathCmd, Vec2}; + +/// A cubic Bézier segment: start, two control points, end. +pub type Cubic = [Vec2; 4]; + +/// Most commands one pass looks at (keeps an edit's cost bounded). +const MAX_CMDS: usize = 100_000; + +/// Segment `cmd` of `path` as a cubic from where it starts (lines and quadratics raised exactly). +/// `None` for anything that is not a segment. +pub fn segment_cubic(path: &Path, cmd: usize) -> Option { + let s = path.segment_start(cmd)?; + Some(match *path.cmds.get(cmd)? { + PathCmd::LineTo(p) => [s, s.lerp(p, 1.0 / 3.0), s.lerp(p, 2.0 / 3.0), p], + PathCmd::QuadTo(c, p) => [s, s.lerp(c, 2.0 / 3.0), p.lerp(c, 2.0 / 3.0), p], + PathCmd::CubicTo(a, b, p) => [s, a, b, p], + _ => return None, + }) +} + +/// `c` mapped by `m` (an affine map takes control points to control points exactly). +pub fn transform(c: &Cubic, m: &Affine) -> Cubic { + c.map(|p| m.apply(p)) +} + +/// `c` with its point at `t` moved by `d` and its ends kept: the smallest moves of the two +/// control points that carry that point exactly, as [`Path::bend_segment`] does. +pub fn bend(c: &Cubic, t: f32, d: Vec2) -> Option { + let mut p = Path::new(); + p.move_to(c[0]).cubic_to(c[1], c[2], c[3]); + if !p.bend_segment(1, t, d) { + return None; + } + segment_cubic(&p, 1).filter(|b| b.iter().all(|q| q.is_finite())) +} + +fn split(c: &Cubic, t: f32) -> (Cubic, Cubic) { + let (a, b, d) = (c[0].lerp(c[1], t), c[1].lerp(c[2], t), c[2].lerp(c[3], t)); + let (e, f) = (a.lerp(b, t), b.lerp(d, t)); + let m = e.lerp(f, t); + ([c[0], a, e, m], [m, f, d, c[3]]) +} + +/// The part of `c` from `t0` to `t1` (reversed when `t1 < t0`). +pub fn sub(c: &Cubic, t0: f32, t1: f32) -> Cubic { + if t1 < t0 { + let r = sub(c, t1, t0); + return [r[3], r[2], r[1], r[0]]; + } + let left = if t1 >= 1.0 { *c } else { split(c, t1.max(0.0)).0 }; + if t0 <= 0.0 || t1 <= 0.0 { + return left; + } + split(&left, (t0 / t1).clamp(0.0, 1.0)).1 +} + +/// The parameter on `c` nearest `p`, and the distance. +pub fn nearest(c: &Cubic, p: Vec2) -> (f32, f32) { + const N: usize = 32; + let mut best = (0.0f32, f32::INFINITY); + for i in 0..=N { + let t = i as f32 / N as f32; + let d = cubic_point(c, t).distance(p); + if d < best.1 { + best = (t, d); + } + } + // Golden-section search around the best sample. + let (mut lo, mut hi) = ((best.0 - 1.0 / N as f32).max(0.0), (best.0 + 1.0 / N as f32).min(1.0)); + const G: f32 = 0.618_034; + for _ in 0..30 { + let (m1, m2) = (hi - (hi - lo) * G, lo + (hi - lo) * G); + if cubic_point(c, m1).distance(p) < cubic_point(c, m2).distance(p) { + hi = m2; + } else { + lo = m1; + } + } + let t = 0.5 * (lo + hi); + let d = cubic_point(c, t).distance(p); + if d < best.1 { (t, d) } else { best } +} + +fn bounds_meet(a: &Cubic, b: &Cubic, pad: f32) -> bool { + let lo = |c: &Cubic| c.iter().fold(Vec2::new(f32::INFINITY, f32::INFINITY), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y))); + let hi = |c: &Cubic| c.iter().fold(Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY), |m, p| Vec2::new(m.x.max(p.x), m.y.max(p.y))); + let (al, ah, bl, bh) = (lo(a), hi(a), lo(b), hi(b)); + al.x <= bh.x + pad && bl.x <= ah.x + pad && al.y <= bh.y + pad && bl.y <= ah.y + pad +} + +/// Where `c` runs along `of`: the parameters on `of` of its two ends, when both ends and three +/// points between lie within `tol` of it and it is not a single point there. +fn along(c: &Cubic, of: &Cubic, tol: f32) -> Option<(f32, f32)> { + let (u0, d0) = nearest(of, c[0]); + let (u1, d1) = nearest(of, c[3]); + if d0 > tol || d1 > tol || (u1 - u0).abs() < 1e-4 { + return None; + } + [0.25, 0.5, 0.75].iter().all(|&t| nearest(of, cubic_point(c, t)).1 <= tol).then_some((u0, u1)) +} + +/// `piece` with its ends moved onto `a` and `b`, the handles moving with them (the anchors of a +/// path stay exactly where they were, so it stays joined to its neighbours). +fn pinned(piece: &Cubic, a: Vec2, b: Vec2) -> PathCmd { + PathCmd::CubicTo(piece[1] + (a - piece[0]), piece[2] + (b - piece[3]), b) +} + +/// Replaces every stretch of `path` that runs along `old` with the same stretch of `new` (the +/// edge `old` bent into `new`; their ends are the same). A segment lying along part of `old` +/// takes that part of `new`; a segment that `old` lies along part of is split at `old`'s ends +/// first. Returns how many segments changed. +pub fn follow(path: &mut Path, old: &Cubic, new: &Cubic, tol: f32) -> usize { + if !(tol.is_finite() && tol > 0.0) || !old.iter().chain(new).all(|p| p.is_finite()) { + return 0; + } + let mut changed = 0; + let mut k = 0; + while k < path.cmds.len().min(MAX_CMDS) { + let Some(s) = segment_cubic(path, k) else { + k += 1; + continue; + }; + if !bounds_meet(&s, old, tol) { + k += 1; + continue; + } + if let Some((u0, u1)) = along(&s, old, tol) { + // All of this segment is a stretch of the edge. + if let Some(c) = path.cmds.get_mut(k) { + *c = pinned(&sub(new, u0, u1), s[0], s[3]); + changed += 1; + } + k += 1; + continue; + } + let Some((s0, s1)) = along(old, &s, tol) else { + k += 1; + continue; + }; + // The edge is a stretch of this (longer) segment: cut it out and replace it. + let (lo, hi) = (s0.min(s1), s0.max(s1)); + const END: f32 = 1e-4; + if hi < 1.0 - END && !path.split_segment(k, hi) { + k += 1; + continue; + } + let mid = if lo > END && path.split_segment(k, lo / hi.max(END)) { k + 1 } else { k }; + if let (Some(m), Some(start)) = (segment_cubic(path, mid), path.segment_start(mid)) { + let piece = if s0 <= s1 { *new } else { [new[3], new[2], new[1], new[0]] }; + if let Some(c) = path.cmds.get_mut(mid) { + *c = pinned(&piece, start, m[3]); + changed += 1; + } + } + k = mid + 1; + } + changed +} + +/// The anchors of `path` at `p` (within `tol`), as the commands that name them. When none is +/// there but a segment passes within `tol` (another shape ends on this one's edge), the segment +/// is split there first, so the point can move with the shapes that end on it. +pub fn anchors_at(path: &mut Path, p: Vec2, tol: f32) -> Vec { + let near = |path: &Path| path.editable_anchors().into_iter().filter(|(_, q)| q.distance(p) <= tol).map(|(i, _)| i).collect::>(); + let found = near(path); + if !found.is_empty() || path.cmds.len() >= MAX_CMDS { + return found; + } + match path.nearest_segment(p, &Affine::IDENTITY) { + Some((cmd, t, d)) if d <= tol && t > 0.0 && t < 1.0 && path.split_segment(cmd, t) => vec![cmd], + _ => Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn line(a: (f32, f32), b: (f32, f32)) -> Cubic { + let (a, b) = (Vec2::new(a.0, a.1), Vec2::new(b.0, b.1)); + [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b] + } + + #[test] + fn a_bent_edge_passes_through_the_dragged_point_and_keeps_its_ends() { + let c = line((0.0, 0.0), (90.0, 0.0)); + let Some(b) = bend(&c, 0.5, Vec2::new(0.0, 30.0)) else { panic!("no bend") }; + assert_eq!((b[0], b[3]), (c[0], c[3])); + assert!(cubic_point(&b, 0.5).distance(Vec2::new(45.0, 30.0)) < 1e-3, "{:?}", cubic_point(&b, 0.5)); + // Off centre too: the grabbed point goes exactly where the pointer took it. + let Some(b) = bend(&c, 0.2, Vec2::new(5.0, -12.0)) else { panic!("no bend") }; + assert!(cubic_point(&b, 0.2).distance(Vec2::new(23.0, -12.0)) < 1e-3); + } + + #[test] + fn every_copy_of_an_edge_follows_a_bend() { + // A fill's outline (a rectangle) shares its top edge with a stroke drawn the other way. + let mut fill = Path::rect(0.0, 0.0, 90.0, 60.0); + fill.close_explicitly(); + let old = line((90.0, 0.0), (0.0, 0.0)); + let Some(new) = bend(&old, 0.5, Vec2::new(0.0, -20.0)) else { panic!("no bend") }; + assert_eq!(follow(&mut fill, &old, &new, 0.2), 1); + // The top now bulges up through (45, −20); the other sides are untouched. + let top = fill.cmds.iter().position(|c| matches!(c, PathCmd::CubicTo(..))).and_then(|k| segment_cubic(&fill, k)); + let Some(top) = top else { panic!("no curve: {:?}", fill.cmds) }; + assert!(cubic_point(&top, 0.5).distance(Vec2::new(45.0, -20.0)) < 1e-3); + assert_eq!(fill.cmds.iter().filter(|c| matches!(c, PathCmd::LineTo(_))).count(), 3); + // A longer segment that the edge is part of is cut at the edge's ends. + let mut long = Path::line(Vec2::new(-30.0, 0.0), Vec2::new(120.0, 0.0)); + assert_eq!(follow(&mut long, &old, &new, 0.2), 1); + assert_eq!(long.cmds.len(), 4, "{:?}", long.cmds); + let a = long.anchors().into_iter().map(|(_, p)| p).collect::>(); + assert!(a.iter().any(|p| p.distance(Vec2::ZERO) < 1e-3) && a.iter().any(|p| p.distance(Vec2::new(90.0, 0.0)) < 1e-3), "{a:?}"); + let Some(mid) = segment_cubic(&long, 2) else { panic!() }; + assert!(cubic_point(&mid, 0.5).distance(Vec2::new(45.0, -20.0)) < 1e-2, "{:?}", cubic_point(&mid, 0.5)); + // Something merely nearby is left alone. + let mut other = Path::line(Vec2::new(0.0, 5.0), Vec2::new(90.0, 5.0)); + assert_eq!(follow(&mut other, &old, &new, 0.2), 0); + } + + #[test] + fn a_shape_gets_an_anchor_where_another_ends_on_it() { + let mut p = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)); + assert_eq!(anchors_at(&mut p, Vec2::new(100.05, 0.0), 0.2), vec![1], "an end that is there"); + assert_eq!(anchors_at(&mut p, Vec2::new(40.0, 0.1), 0.2), vec![1], "split there"); + assert_eq!(p.cmds.len(), 3); + assert!(anchors_at(&mut p, Vec2::new(40.0, 5.0), 0.2).is_empty()); + } + + #[test] + fn nearest_finds_the_closest_point_on_a_curve() { + let c = [Vec2::new(0.0, 0.0), Vec2::new(0.0, 50.0), Vec2::new(100.0, 50.0), Vec2::new(100.0, 0.0)]; + let (t, d) = nearest(&c, Vec2::new(50.0, 60.0)); + assert!((t - 0.5).abs() < 1e-3 && (d - 22.5).abs() < 1e-2, "{t} {d}"); + } +} diff --git a/crates/geom/src/walk.rs b/crates/geom/src/walk.rs index 2c86818f..c310ec23 100644 --- a/crates/geom/src/walk.rs +++ b/crates/geom/src/walk.rs @@ -108,6 +108,19 @@ impl CurveWalk { (b.seg as usize, ta + (b.t - ta) * f) } + /// The distance along the path to the anchor that ends path command `cmd`, or 0 for the + /// start (a command before the first segment). `None` when `cmd` ends no segment the walk + /// measured. + pub fn anchor_distance(&self, cmd: usize) -> Option { + if self.segs.first().is_some_and(|(c, _)| cmd < *c) { + return Some(0.0); + } + let k = self.segs.binary_search_by_key(&cmd, |(c, _)| *c).ok()?; + // Segment k's samples end with its anchor (t = 1). + let j = self.samples.partition_point(|x| x.seg as usize <= k); + self.samples.get(j.checked_sub(1)?).map(|x| x.s) + } + /// The path command and curve parameter at distance `s`: where to split or bend the path. pub fn locate(&self, s: f32) -> (usize, f32) { let (k, t) = self.find(s); @@ -298,6 +311,12 @@ mod tests { assert!(w.at(125.0).distance(Vec2::new(110.0, 45.0)) < 1e-3); assert!(w.tangent(125.0).distance(Vec2::new(0.0, 1.0)) < 1e-5); assert_eq!(w.locate(125.0).0, 2, "the second line is command 2"); + // Anchors by distance: the start, the corner, the end; the walk lands on them exactly. + assert_eq!(w.anchor_distance(0), Some(0.0)); + let corner = w.anchor_distance(1).unwrap(); + assert!((corner - 100.0).abs() < 1e-3 && w.at(corner) == Vec2::new(110.0, 20.0), "{corner}"); + assert_eq!(w.anchor_distance(2), Some(w.length())); + assert_eq!(w.anchor_distance(3), None); assert!((w.project(Vec2::new(130.0, 60.0)) - 140.0).abs() < 1e-2); let tail = w.tail(50.0).unwrap(); let tw = CurveWalk::new(&tail).unwrap(); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index cff0ca59..005fcf68 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -95,9 +95,9 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { // Strokes: wide, thin (sub-pixel, faded), on open and closed paths. let mut wide = item(Path::line(Vec2::new(10.0, 20.0), Vec2::new(150.0, 70.0)), Paint::Solid(red)); wide.fill = None; - wide.stroke = Some(Stroke { color: Rgba::BLACK, width: 9.0, profile: None }); + wide.stroke = Some(Stroke::new(Rgba::BLACK, 9.0)); let mut thin = item(Path::ellipse(80.0, 50.0, 60.0, 30.0), Paint::Solid(Rgba::new(1.0, 0.9, 0.2, 1.0))); - thin.stroke = Some(Stroke { color: Rgba::new(0.1, 0.1, 0.4, 1.0), width: 0.4, profile: None }); + thin.stroke = Some(Stroke::new(Rgba::new(0.1, 0.1, 0.4, 1.0), 0.4)); out.push(("strokes", list(vec![thin, wide]), view(160, 100, Some(Rgba::WHITE)))); // Variable-width strokes (ADR 0018) come prepared by the oracle, so the GPU draws them alike. let mut taper = item(Path::line(Vec2::new(10.0, 80.0), Vec2::new(150.0, 15.0)), Paint::Solid(red)); @@ -106,6 +106,22 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { let mut bulge = item(Path::ellipse(80.0, 50.0, 55.0, 28.0), Paint::Solid(Rgba::new(0.3, 0.8, 0.5, 1.0))); bulge.stroke = Some(Stroke::new(Rgba::new(0.1, 0.1, 0.4, 1.0), 8.0).with_profile(anicraft_doc::ProfilePreset::Bulge.profile())); out.push(("variable-width strokes", list(vec![bulge, taper]), view(160, 100, Some(Rgba::WHITE)))); + // Caps, joins and dashes (ADR 0046) also come prepared by the oracle. + use anicraft_doc::{Cap, Dash, Join, StrokeStyle}; + let mut zag = Path::new(); + zag.move_to(Vec2::new(12.0, 80.0)); + for p in [Vec2::new(45.0, 20.0), Vec2::new(78.0, 80.0), Vec2::new(111.0, 20.0)] { + zag.line_to(p); + } + let mut zig = item(zag, Paint::Solid(red)); + zig.fill = None; + zig.stroke = Some(Stroke::new(Rgba::BLACK, 10.0).with_style(StrokeStyle { cap: Cap::Square, join: Join::Miter, miter_limit: 4.0, dash: None })); + let mut dashed = item(Path::ellipse(90.0, 50.0, 55.0, 30.0), Paint::Solid(Rgba::new(1.0, 0.9, 0.2, 1.0))); + dashed.stroke = Some(Stroke::new(Rgba::new(0.1, 0.1, 0.4, 1.0), 4.0).with_style(StrokeStyle { cap: Cap::Butt, join: Join::Bevel, dash: Dash::dashed(9.0, 5.0), ..StrokeStyle::default() })); + let mut dots = item(Path::line(Vec2::new(10.0, 92.0), Vec2::new(150.0, 92.0)), Paint::Solid(red)); + dots.fill = None; + dots.stroke = Some(Stroke::new(red, 5.0).with_profile(anicraft_doc::ProfilePreset::TaperEnd.profile()).with_style(StrokeStyle { dash: Dash::dotted(3.0), ..StrokeStyle::default() })); + out.push(("styled strokes", list(vec![dashed, zig, dots]), view(160, 100, Some(Rgba::WHITE)))); // Larger than the surface on every side; colour effects (onion-skin style tint and alpha). let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red)); huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 }; diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 6ee0a61f..d8716d93 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -14,10 +14,13 @@ //! frames are stored once, so a still keyframe over many frames costs one entry. //! //! What doesn't carry across is counted in the report: filters, Subtract and Invert blending, -//! tints on bitmaps, and plug-in frame scripts (they need the plug-in host). +//! tints on bitmaps, plug-in frame scripts (they need the plug-in host) and kept scripts +//! outside the ActionScript subset. Scripts in the subset (ADR 0013 tier 2) come across as the +//! same actions and listeners the Rust player runs. -use crate::stroke::variable_outline; -use anicraft_doc::actions::{Action, FrameRef, Seg}; +use crate::stroke::stroke_outline; +use anicraft_doc::actions::as3::ScriptOp; +use anicraft_doc::actions::{Action, FrameRef, Seg, Target}; use anicraft_doc::{BlendMode, ColorEffect, Document, Element, ElementKind, FrameScript, Layer, LayerKind, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start}; use anicraft_geom::{Affine, FillRule, Path, PathCmd}; use serde_json::{Map, Value, json}; @@ -90,7 +93,8 @@ const BLENDS: &str = "Subtract and Invert blending (drawn normally)"; const BITMAP_TINT: &str = "tints on bitmap fills (drawn untinted)"; const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)"; const BUTTON_SOUNDS: &str = "sounds on button frames (not played yet)"; -const KEPT_SCRIPTS: &str = "kept frame scripts (not run; kept in the document only)"; +const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)"; +const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)"; /// A number rounded to `1/scale`, written as an integer when it is one. fn num(v: f32, scale: f64) -> Value { @@ -104,6 +108,20 @@ fn num(v: f32, scale: f64) -> Value { } } +/// A stroke's style for the page (ADR 0046): `c` cap, `j` join, `ml` miter limit, and for a +/// broken line `d` its on/off lengths and `o` the offset into them (local units, scaled by +/// the page like the width; dots are zero-length round-capped dashes). +fn line_style(st: &anicraft_doc::Stroke) -> Value { + let style = &st.style; + let mut k = json!({"c": style.effective_cap().key(), "j": style.join.key(), "ml": num(style.miter_limit, 1e3)}); + if let Some(d) = &style.dash { + let (lengths, offset) = d.pattern(st.width); + k["d"] = Value::Array(lengths.into_iter().map(|l| num(l, 1e3)).collect()); + k["o"] = num(offset, 1e3); + } + k +} + fn coord(v: f32) -> Value { num(v, 1000.0) } @@ -176,13 +194,10 @@ fn path_data(p: &Path) -> String { if finite { s } else { String::new() } } -/// An action as the player reads it: `op`, the target as steps (`^` the main timeline, `..` up -/// a level, else an instance name; `e` when it isn't a valid path), and `d`, its description -/// (for messages). -fn action(a: &Action) -> Value { - let mut o = Map::new(); - o.insert("op".into(), json!(a.op())); - if let Some(t) = a.target() { +/// A target as the player reads it: `t`, its steps (`^` the main timeline, `..` up a level, +/// else an instance name), or `e` when it isn't a valid path. +fn target(o: &mut Map, t: &Target) { + { match t.segments() { Ok(segs) => { if !segs.is_empty() { @@ -202,6 +217,16 @@ fn action(a: &Action) -> Value { } } } +} + +/// An action as the player reads it: `op`, its target (see [`target`]), and `d`, its +/// description (for messages). +fn action(a: &Action) -> Value { + let mut o = Map::new(); + o.insert("op".into(), json!(a.op())); + if let Some(t) = a.target() { + target(&mut o, t); + } match a { Action::Trace { message } => { o.insert("msg".into(), json!(message)); @@ -232,6 +257,28 @@ fn actions(list: &[Action]) -> Value { Value::Array(list.iter().map(action).collect()) } +/// A compiled script's steps (ADR 0013 tier 2): actions, and `listen` steps with the target, +/// the event `ev`, the function `k` and the actions `h` it runs. +fn script_ops(ops: &[ScriptOp]) -> Value { + Value::Array( + ops.iter() + .map(|op| match op { + ScriptOp::Action(a) => action(a), + ScriptOp::Listen(l) => { + let mut o = Map::new(); + o.insert("op".into(), json!("listen")); + target(&mut o, &l.target); + o.insert("ev".into(), json!(l.event.key())); + o.insert("k".into(), json!(l.function)); + o.insert("h".into(), actions(&l.actions)); + o.insert("d".into(), json!(format!("Listen for {} ({})", l.event.key(), l.target))); + Value::Object(o) + } + }) + .collect(), + ) +} + /// Whether timeline layer `index` takes part in playback (what the player walks and draws): /// shown, not a folder or guide, not in a hidden folder. fn plays(tl: &Timeline, index: usize) -> bool { @@ -325,18 +372,22 @@ impl<'a> Bake<'a> { i } - /// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `eo` even-odd, - /// `m` transform, `c` colour effect. - fn shape(&mut self, path: &Arc, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<(Rgba, f32)>, rule: FillRule) -> Value { + /// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `k` its style when + /// not round and solid (`c` cap, `j` join, `ml` miter limit, `d` dash lengths and `o` their + /// offset, in local units like the width), `eo` even-odd, `m` transform, `c` colour effect. + fn shape(&mut self, path: &Arc, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<&anicraft_doc::Stroke>, rule: FillRule) -> Value { let mut o = Map::new(); o.insert("p".into(), json!(self.path(path))); if let Some((p, el)) = fill { o.insert("f".into(), json!(self.paint(p, el))); } - if let Some((c, w)) = stroke { - let mut s = color(c); - s.push(num(w, 1e3)); + if let Some(st) = stroke { + let mut s = color(st.color); + s.push(num(st.width, 1e3)); o.insert("s".into(), Value::Array(s)); + if !st.style.is_default() { + o.insert("k".into(), line_style(st)); + } } if rule == FillRule::EvenOdd { o.insert("eo".into(), json!(1)); @@ -358,19 +409,20 @@ impl<'a> Bake<'a> { match &el.kind { ElementKind::Shape(s) => { let stroke = s.stroke.as_ref().filter(|st| st.width.is_finite() && st.width > 0.0); - match stroke.and_then(|st| st.profile.as_ref().map(|p| (st, p))) { - // A variable-width stroke is the filled outline the renderer fills. - Some((st, profile)) => { + match stroke.filter(|st| st.profile.is_some()) { + // A variable-width stroke is the filled outline the renderer fills (its + // caps, joins and dashes included). + Some(st) => { if let Some(p) = &s.fill { out.push(self.shape(&s.path, &el.transform, &el.color, Some((p, el)), None, s.fill_rule)); } - let outline = variable_outline(&s.path, &el.transform, st.width, profile, crate::TOLERANCE); + let outline = stroke_outline(&s.path, &el.transform, st, crate::TOLERANCE); if !outline.is_empty() { let fill = Paint::Solid(st.color); out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color, Some((&fill, el)), None, FillRule::NonZero)); } } - None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke.map(|st| (st.color, st.width)), s.fill_rule)), + None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke, s.fill_rule)), } } // The camera is the view, not artwork (ADR 0027): it is baked into the layers. @@ -515,9 +567,21 @@ impl<'a> Bake<'a> { self.notes.entry(PLUGIN_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0)); a.push(json!({"plugin": format!("{} · {}", p.id, p.entry)})); } - // Kept scripts don't run anywhere yet (ADR 0013 tier 1). - Some(FrameScript::Source(_)) => { - self.notes.entry(KEPT_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0)); + // ActionScript in the subset runs as the player runs it; the rest is only + // kept (ADR 0013). + Some(FrameScript::Source(src)) => { + let key = u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0); + match src.compiled() { + Ok(c) => { + a.push(json!({"as": script_ops(&c.ops)})); + if !c.notes.is_empty() { + self.notes.entry(OUTSIDE_CALLS).or_default().insert(key); + } + } + Err(_) => { + self.notes.entry(KEPT_SCRIPTS).or_default().insert(key); + } + } } None => {} } diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 0199a275..7858c20f 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -158,14 +158,28 @@ } } if (it.s) { - const w = it.s[4] * AniCraft.meanScale(it.m) * k; + const scale = AniCraft.meanScale(it.m); + const w = it.s[4] * scale * k; if (w > 0 && Number.isFinite(w)) { g.setTransform(k, 0, 0, k, 0, 0); g.lineWidth = w / k; - g.lineJoin = "round"; - g.lineCap = "round"; + // Caps, joins and dashes (stage units: local lengths × the mean scale, like the width). + const st = it.k; + g.lineJoin = st ? st.j : "round"; + g.lineCap = st ? st.c : "round"; + if (st) g.miterLimit = st.ml; + const dashed = st && st.d && st.d.length > 0; + if (dashed) { + g.setLineDash(st.d.map((x) => x * scale)); + g.lineDashOffset = (st.o || 0) * scale; + } g.strokeStyle = css(AniCraft.applyEffect(it.c, it.s)); g.stroke(stagePath(path, it.m)); + if (dashed) { + g.setLineDash([]); + g.lineDashOffset = 0; + } + if (st) g.miterLimit = 10; } } }, @@ -332,5 +346,5 @@ report(player.start()); resize(); requestAnimationFrame(tick); - }); + }).catch((e) => console.error("AniCraft: the movie couldn't start", e)); })(); diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index c4ef520d..ceb92473 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -1,7 +1,8 @@ // AniCraft HTML canvas player: the core (ADR 0028). SPDX-License-Identifier: MIT OR Apache-2.0 // // Plays a movie exported by File > Export > HTML Canvas: the instance tree, movie clip -// playheads, frame actions and button events. It is a line-by-line port of the Rust player +// playheads, frame actions, button events, and frame scripts in the ActionScript subset +// (compiled by AniCraft to the same actions, with the mouse listeners they add). It is a line-by-line port of the Rust player // (crates/doc/src/player.rs, the reference) over the exported data, and the tests run it in a // JavaScript engine against that player. Nothing here touches the page: canvas.js draws and // listens to the pointer; this file only computes. @@ -20,6 +21,7 @@ var AniCraft = (function () { const MAX_EVENTS_PER_STEP = 256; const MAX_SOUNDS_PER_STEP = 256; const MAX_SYMBOL_DEPTH = 32; + const MAX_LISTENERS_PER_INSTANCE = 16; const ROOT = 0, GRAPHIC = 1, CLIP = 2, BUTTON = 3; const KINDS = { graphic: GRAPHIC, movieclip: CLIP, button: BUTTON }; const I = [1, 0, 0, 1, 0, 0]; @@ -141,9 +143,10 @@ var AniCraft = (function () { // ----- the player state ------------------------------------------------------------------------ function newState() { - return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), pointer: null, down: false, hover: null, pressed: null, tick: 0 }; + return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), listeners: new Dict(), pointer: null, down: false, hover: null, pressed: null, tick: 0 }; } - // Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }. + // Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }; each + // listeners entry: [{ ev, owner, k, h, path }] in the order added. function clipFrame(st, key, len) { const c = st.clips.get(key); return Math.min(c ? c.frame : 0, Math.max(len, 1) - 1); @@ -296,7 +299,7 @@ var AniCraft = (function () { } const xf = mul(cx.xf, m); if (e.y === undefined) { - const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, eo: !!e.eo, c: concat(cx.c, fx), clip: clip, masks: masks, group: cx.group }; + const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, k: e.k || null, eo: !!e.eo, c: concat(cx.c, fx), clip: clip, masks: masks, group: cx.group }; dl.items.push(it); if (v) v.item(it); return; @@ -331,7 +334,7 @@ var AniCraft = (function () { function hitIn(M, st, nodes, host, x, y) { for (let i = nodes.length - 1; i >= 0; i--) { const n = nodes[i]; - const interactive = n.kind === BUTTON || (n.kind === CLIP && n.events); + const interactive = n.kind === BUTTON || (n.kind === CLIP && (n.events || st.listeners.has(n.key))); if (!n.hittable || !interactive) continue; const sym = M.symbols[n.sym]; if (!sym) continue; @@ -408,7 +411,8 @@ var AniCraft = (function () { for (const k of Object.keys(p)) if (k !== "path") o[k] = p[k]; return [p.path, o]; }); - return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, hover: st.hover, pressed: st.pressed, down: st.down }; + const listeners = Array.from(st.listeners.values()).filter((l) => l.length > 0).sort((a, b) => comparePaths(a[0].path, b[0].path)).map((l) => [l[0].path, l.map((x) => [x.ev, x.owner, x.k])]); + return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, listeners: listeners, hover: st.hover, pressed: st.pressed, down: st.down }; }; function Run(player) { @@ -477,6 +481,12 @@ var AniCraft = (function () { this.queue(path); } for (const k of Array.from(st.props.keys())) if (!all.has(k)) st.props.delete(k); + // A listener goes with its instance, and with the timeline whose script added it. + for (const [k, list] of st.listeners.entries()) { + const kept = list.filter((l) => all.has(keyOf(l.owner))); + if (!all.has(k) || kept.length === 0) st.listeners.delete(k); + else st.listeners.set(k, kept); + } if (st.hover !== null && !all.has(keyOf(st.hover))) st.hover = null; if (st.pressed !== null && !all.has(keyOf(st.pressed))) st.pressed = null; }; @@ -559,20 +569,57 @@ var AniCraft = (function () { const frame = this.nodes[i].frame; this.soundsAt(tl, frame, this.nodes[i].gain); for (const script of (tl.a && tl.a[frame]) || []) { - if (Array.isArray(script)) this.runList(path, script); + if (Array.isArray(script)) this.runList(path, script, false); + else if (script.as) this.runOps(path, script.as); else this.out("Frame script " + script.plugin + " not run: frame scripts are not exported"); } }; - Run.prototype.runList = function (owner, list) { - for (const a of list) { - if (this.halted) return; - this.actions += 1; - if (this.actions > MAX_ACTIONS_PER_STEP) { - this.halt("more than " + MAX_ACTIONS_PER_STEP + " actions"); - return; - } - this.exec(owner, a); + // Counts one action against the step's budget; false when nothing more may run. + Run.prototype.budget = function () { + if (this.halted) return false; + this.actions += 1; + if (this.actions > MAX_ACTIONS_PER_STEP) { + this.halt("more than " + MAX_ACTIONS_PER_STEP + " actions"); + return false; } + return true; + }; + // `script`: the actions come from ActionScript. + Run.prototype.runList = function (owner, list, script) { + for (const a of list) { + if (!this.budget()) return; + this.exec(owner, a, script); + } + }; + // A compiled script's steps: actions, and `listen` (addEventListener). + Run.prototype.runOps = function (owner, ops) { + for (const a of ops) { + if (!this.budget()) return; + if (a.op === "listen") this.listen(owner, a); + else this.exec(owner, a, true); + } + }; + // The instance the listener's target names gets it (once per function and event). + Run.prototype.listen = function (owner, a) { + this.refresh(); + const from = this.indexOf(owner); + if (from < 0) return; + const [i, err] = this.resolve(from, a); + if (i < 0) return this.out(a.d + ": " + err); + const node = this.nodes[i]; + if (!node) return; + if (node.kind !== BUTTON && node.kind !== CLIP) { + const why = node.kind === ROOT ? "the main timeline doesn't get pointer events here" : "“" + node.name + "” is a graphic; only buttons and movie clips get pointer events"; + return this.out(a.d + ": " + why); + } + let list = this.st.listeners.get(node.key); + if (list && list.some((x) => x.ev === a.ev && samePath(x.owner, owner) && x.k === a.k)) return; + if (list && list.length >= MAX_LISTENERS_PER_INSTANCE) return this.out(a.d + ": “" + node.name + "” already has " + MAX_LISTENERS_PER_INSTANCE + " listeners"); + if (!list) { + list = []; + this.st.listeners.set(node.key, list); + } + list.push({ ev: a.ev, owner: owner, k: a.k, h: a.h, path: node.path }); }; // The node `a`'s target names, seen from timeline node `from`: [index] or [-1, why]. Run.prototype.resolve = function (from, a) { @@ -593,7 +640,7 @@ var AniCraft = (function () { } return [cur]; }; - Run.prototype.exec = function (owner, a) { + Run.prototype.exec = function (owner, a, script) { this.refresh(); const from = this.indexOf(owner); if (from < 0) return; @@ -604,6 +651,8 @@ var AniCraft = (function () { return; case "next_scene": case "prev_scene": { + // In ActionScript a movie clip's timeline has one scene. + if (script && owner.length > 0) return this.out(a.d + ": a movie clip's timeline has one scene; call it in the main timeline's script"); const s = a.op === "next_scene" ? st.scene + 1 : st.scene - 1; if (s >= 0 && s < this.M.scenes.length) this.gotoRoot(s, 0); return; @@ -757,17 +806,19 @@ var AniCraft = (function () { if (now !== null) this.fire(now, "over"); } }; - // Runs an instance's handler for `event`, in the timeline the instance is on. + // Runs an instance's handler for `event`, in the timeline the instance is on, then the + // listeners scripts added for it (each in its script's timeline), in the order added. Run.prototype.fire = function (path, event) { this.refresh(); const i = this.indexOf(path); if (i < 0) return; const n = this.nodes[i]; const h = (n.events || []).find((x) => x[0] === event); - if (!h) return; + const ls = (this.st.listeners.get(n.key) || []).filter((l) => l.ev === event); + if (!h && ls.length === 0) return; const owner = this.nodes[n.owner]; - if (!owner) return; - this.runList(owner.path, h[1]); + if (h && owner) this.runList(owner.path, h[1], false); + for (const l of ls) this.runList(l.owner, l.h, true); this.settle(); }; Run.prototype.finish = function () { diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 204f30ba..015a5f76 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -200,6 +200,7 @@ fn snapshot(st: &PlayerState) -> Value { json!({ "scene": st.scene, "frame": st.root.frame, "playing": st.root.playing, "clips": st.clips.iter().map(|(p, c)| json!([ids(p), c.frame, c.playing])).collect::>(), + "listeners": st.listeners.iter().filter(|(_, l)| !l.is_empty()).map(|(p, l)| json!([ids(p), l.iter().map(|x| json!([x.event.key(), ids(&x.owner), x.function])).collect::>()])).collect::>(), "hover": st.hover.as_deref().map(ids), "pressed": st.pressed.as_deref().map(ids), "down": st.down, }) } @@ -464,6 +465,33 @@ fn variable_width_strokes_become_filled_outlines() { assert!(items[0]["m"].is_null(), "the outline is already in place"); } +#[test] +fn stroke_caps_joins_and_dashes_reach_the_page() { + use anicraft_doc::{Cap, Dash, Join, Stroke, StrokeStyle}; + let mut doc = Document::default(); + let style = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 6.0, dash: Some(Dash::Dashed { lengths: vec![4.0, 1.5].into(), offset: 1.0 }) }; + let line = |y: f32, st: Stroke| Shape { path: Arc::new(Path::line(Vec2::new(10.0, y), Vec2::new(200.0, y))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false }; + let shapes = [line(10.0, Stroke::new(Rgba::BLACK, 3.0)), line(30.0, Stroke::new(Rgba::BLACK, 3.0).with_style(style)), line(50.0, Stroke::new(Rgba::BLACK, 3.0).with_style(StrokeStyle { dash: Dash::dotted(2.0), ..StrokeStyle::default() }))]; + for (i, sh) in shapes.into_iter().enumerate() { + let el = Element { id: ElementId(70 + i as u64), name: String::new(), transform: Affine::scale(2.0, 2.0), color: Default::default(), kind: ElementKind::Shape(sh) }; + Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements.push(Arc::new(el)); + } + let m = movie(&doc, &HtmlOptions::default()); + let items = &m.json["contents"][0]["l"][0]["e"]; + // Round and solid: no style entry, as before. + assert!(items[0]["s"].is_array() && items[0].get("k").is_none(), "{items}"); + // Lengths stay in local units; the page scales them like the width. + assert_eq!(items[1]["k"], json!({"c": "butt", "j": "miter", "ml": 6, "d": [4, 1.5], "o": 1})); + assert_eq!(items[2]["k"], json!({"c": "round", "j": "round", "ml": 3, "d": [0, 5], "o": 0}), "dots are round zero-length dashes"); + // The player hands the style to the page with each item. + let mut js = Js::new(&m); + js.eval("P.start()"); + let ours = js.eval("P.evaluate()"); + let theirs = ours["items"].as_array().unwrap(); + assert!(theirs[0]["k"].is_null()); + assert_eq!(theirs[1]["k"], items[1]["k"]); +} + #[test] fn what_does_not_carry_across_is_reported() { let mut doc = fixture(); @@ -585,3 +613,84 @@ fn hostile_documents_export_without_panicking() { let m = movie(&Document::default(), &HtmlOptions::default()); assert_eq!(m.json["timelines"][0]["n"], 1); } + +/// `k` with a kept ActionScript 3.0 script in place of its actions. +fn as3(k: &mut Arc, src: &str) { + Arc::make_mut(k).script = Some(FrameScript::Source(Arc::new(anicraft_doc::actions::SourceScript::new(anicraft_doc::actions::Language::ActionScript3, src)))); +} + +/// The fixture with its frame actions and the knob's handlers written as ActionScript: the +/// main timeline's first frame adds the knob's listeners (named and inline functions, +/// `currentTarget`), a listener makes the panel clip clickable, one names an instance that +/// isn't there, the door's last frame calls `nextScene()` in its own script, and a script +/// outside the subset stays kept and unrun. +fn scripted() -> Document { + let mut d = fixture(); + let main = "import flash.events.MouseEvent;\n\ + trace(\"start\");\n\ + knob.addEventListener(MouseEvent.CLICK, openDoor);\n\ + knob.addEventListener(MouseEvent.ROLL_OVER, function (e:MouseEvent):void { door.alpha = 0.5; });\n\ + knob.addEventListener(MouseEvent.ROLL_OUT, function (e:MouseEvent):void { door.alpha = 1; });\n\ + knob.addEventListener(MouseEvent.MOUSE_DOWN, pressed);\n\ + knob.addEventListener(MouseEvent.MOUSE_UP, released);\n\ + panel.addEventListener(MouseEvent.CLICK, function (e:MouseEvent):void { trace(\"panel \" + 1); MovieClip(e.currentTarget).gotoAndStop(1); e.currentTarget.alpha = 0.75; });\n\ + ghost.addEventListener(MouseEvent.CLICK, pressed);\n\ + navigateToURL(new URLRequest(\"https://example.com\"));\n\ + function openDoor(e:MouseEvent):void { door.gotoAndPlay(\"opening\"); panel.door.play(); }\n\ + function pressed(e:MouseEvent):void { trace(\"pressed\"); }\n\ + function released(e:MouseEvent):void { MovieClip(root).panel.gotoAndStop(100); }"; + let tl = d.timeline_mut(0); + let l1 = Arc::make_mut(&mut tl.layers[0]); + as3(&mut l1.keyframes[0], main); + as3(&mut l1.keyframes[1], "ghost.stop()\npanel.stop()"); + as3(&mut l1.keyframes[2], "var n:int = 3; stop();"); + let l2 = Arc::make_mut(&mut tl.layers[1]); + if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut Arc::make_mut(&mut l2.keyframes[0]).elements[0]).kind { + events.clear(); + } + let door = Arc::make_mut(&mut d.library[0]); + let dl = Arc::make_mut(&mut door.timeline.layers[0]); + as3(&mut dl.keyframes[2], "stop();\ntrace('door open');\nnextScene();"); + d +} + +#[test] +fn the_js_player_runs_actionscript_like_the_rust_player() { + let doc = scripted(); + let m = movie(&doc, &HtmlOptions::default()); + assert_eq!(m.report.get(KEPT_SCRIPTS), Some(&1), "{:?}", m.report); + assert_eq!(m.report.get(OUTSIDE_CALLS), Some(&1), "{:?}", m.report); + let none = || (vec![], vec![]); + let mut script: Vec<(Vec, Vec)> = (0..2).map(|_| none()).collect(); + script.push((vec![Event::Move(at(100.0, 100.0))], vec![])); + script.push((vec![Event::Down(at(101.0, 99.0))], vec![])); + script.push((vec![], vec![Event::Up(at(102.0, 101.0))])); + script.extend((0..6).map(|_| none())); + // Click the panel (a movie clip that a listener made clickable). + script.push((vec![Event::Move(at(380.0, 300.0))], vec![Event::Down(at(380.0, 300.0)), Event::Up(at(380.0, 300.0))])); + script.push((vec![Event::Move(at(10.0, 10.0)), Event::Leave], vec![])); + script.extend((0..30).map(|_| none())); + let lines = compare(&doc, &script); + for want in ["start", "pressed", "door open", "panel 1", "Listen for click (ghost): no instance named “ghost” here", "Stop (ghost): no instance named “ghost” here", "Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"] { + assert!(lines.iter().any(|l| l == want), "the scripted fixture never wrote {want:?}: {lines:?}"); + } +} + +#[test] +fn actionscript_plays_the_movie_its_hand_made_actions_play() { + // The scripted fixture and the fixture write the same lines and reach the same states, but + // for the lines only scripts write and the listeners they hold. + let (a, b) = (fixture(), scripted()); + let events = [vec![], vec![], vec![Event::Move(at(100.0, 100.0))], vec![Event::Down(at(101.0, 99.0))], vec![Event::Up(at(102.0, 101.0))], vec![], vec![], vec![], vec![Event::Move(at(10.0, 10.0))]]; + let (mut x, mut y) = (start(&a, &mut NoScripts), start(&b, &mut NoScripts)); + let only_scripts = |l: &String| l.starts_with("Listen for") || l.starts_with("Next scene:"); + for (i, ev) in events.iter().enumerate() { + x = step(&a, &x.state, ev, &mut NoScripts); + y = step(&b, &y.state, ev, &mut NoScripts); + let ys: Vec<&String> = y.output.iter().filter(|l| !only_scripts(l)).collect(); + assert_eq!(x.output.iter().collect::>(), ys, "step {}: output", i + 1); + let mut st = y.state.clone(); + st.listeners.clear(); + assert_eq!(x.state, st, "step {}: state", i + 1); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8f2a5674..b79f4e11 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -800,31 +800,11 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { // The stroke is outlined from the flattened lines first, so the fill can then take them // without a copy; it is still drawn after the fill. let stroke = item.stroke.as_ref().and_then(|st| { - let mut fx: ColorEffect = item.color; - let mut pw = st.width * m.mean_scale(); - if !(pw.is_finite() && pw > 0.0) { - return None; - } - let shader = |fx: &ColorEffect| Shader::new(&Paint::Solid(st.color), &m, fx, None); - if let Some(profile) = &st.profile { - // Variable width (ADR 0018). Thin strokes fade by their widest part instead. - let widest = pw * profile.max_factor(); - if !(widest.is_finite() && widest > 0.0) { - return None; - } - if widest < 1.0 { - fx.alpha *= widest; - pw /= widest; - } - let polys = stroke::variable_polygons(&lines, pw * 0.5, profile, m.inverse().as_ref(), m.determinant() < 0.0); - return Some((polys, shader(&fx))); - } - if pw < 1.0 { - // Thin strokes: keep a 1 px footprint and fade by width (avoids dropouts). - fx.alpha *= pw; - pw = 1.0; - } - Some((stroke::stroke_polygons(&lines, pw * 0.5), shader(&fx))) + // Caps, joins, dashes (ADR 0046) and width profiles (ADR 0018); thin strokes and + // sub-pixel dash patterns fade instead of dropping out. + let (polys, alpha) = stroke::stroke_geometry(&lines, st, &m, true)?; + let fx = ColorEffect { alpha: item.color.alpha * alpha, ..item.color }; + Some((polys, Shader::new(&Paint::Solid(st.color), &m, &fx, None))) }); if let Some(fill) = &item.fill { let polys: Vec> = lines.into_iter().map(|l| l.points).collect(); @@ -995,7 +975,7 @@ mod tests { fn prepared_scenes_match_the_renderers_preparation_and_name_what_needs_more() { // A filled, stroked square and an off-screen circle: fill then stroke, one culled. let mut sq = item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)); - sq.stroke = Some(anicraft_doc::Stroke { color: Rgba::WHITE, width: 2.0, profile: None }); + sq.stroke = Some(anicraft_doc::Stroke::new(Rgba::WHITE, 2.0)); let off = item(Path::ellipse(500.0, 500.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK)); let dl = list(vec![sq.clone(), off]); let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap(); @@ -1188,18 +1168,34 @@ mod tests { #[test] #[ignore = "measurement"] fn variable_stroke_cost() { - let strokes = |profile: Option| { + use anicraft_doc::{Cap, Dash, Join, StrokeStyle}; + let strokes = |profile: Option, style: StrokeStyle| { let items = (0..300) .map(|i| { let (x, y) = ((i % 20) as f32 * 64.0, (i / 20) as f32 * 48.0); let mut p = Path::new(); p.move_to(Vec2::new(x, y + 40.0)).cubic_to(Vec2::new(x + 10.0, y - 20.0), Vec2::new(x + 50.0, y + 80.0), Vec2::new(x + 60.0, y + 10.0)); - stroked(p, 6.0, profile.clone()) + let mut it = stroked(p, 6.0, profile.clone()); + it.stroke = it.stroke.map(|st| st.with_style(style.clone())); + it }) .collect(); list(items) }; - for (name, dl) in [("uniform", strokes(None)), ("taper_both", strokes(anicraft_doc::ProfilePreset::TaperBoth.profile())), ("bulge", strokes(anicraft_doc::ProfilePreset::Bulge.profile()))] { + let round = StrokeStyle::default(); + let miter = StrokeStyle { cap: Cap::Square, join: Join::Miter, ..StrokeStyle::default() }; + let dashed = StrokeStyle { cap: Cap::Butt, dash: Dash::dashed(8.0, 4.0), ..StrokeStyle::default() }; + let dotted = StrokeStyle { dash: Dash::dotted(4.0), ..StrokeStyle::default() }; + let taper = || anicraft_doc::ProfilePreset::TaperBoth.profile(); + for (name, dl) in [ + ("uniform", strokes(None, round.clone())), + ("taper_both", strokes(taper(), round)), + ("bulge", strokes(anicraft_doc::ProfilePreset::Bulge.profile(), StrokeStyle::default())), + ("square + miter", strokes(None, miter)), + ("dashed 8/4", strokes(None, dashed.clone())), + ("dotted 4", strokes(None, dotted)), + ("taper_both dashed", strokes(taper(), dashed)), + ] { let mut ms: Vec = (0..9) .map(|_| { let t = std::time::Instant::now(); diff --git a/crates/render/src/lottie.rs b/crates/render/src/lottie.rs index f3e2631a..654d4716 100644 --- a/crates/render/src/lottie.rs +++ b/crates/render/src/lottie.rs @@ -5,9 +5,10 @@ //! that persists from frame to frame (same layer, element and path structure) becomes one //! shape layer, its outline baked into stage space. Whatever changes (outline, colours, //! gradient points, stroke width, opacity, masks) is written as hold keyframes at the frames -//! where it changes, so any Lottie player shows exactly AniCraft's frames. Strokes use round -//! joins and caps, like the renderer; variable-width strokes are filled outlines (the -//! polygons the renderer fills). +//! where it changes, so any Lottie player shows exactly AniCraft's frames. Strokes keep their +//! caps, joins, miter limit and dashes (dash lengths scaled like the width, dots as zero-length +//! round dashes; ADR 0046); variable-width strokes are filled outlines (the polygons the +//! renderer fills, dashes included). //! //! Not carried across (counted in the report): bitmap fills; nested masks keep only the //! innermost mask; a symbol fading as one group is faded shape by shape; stretched radial @@ -135,13 +136,54 @@ enum Fill { struct Sample { paths: Vec, fill: Option, - stroke: Option<(Rgba, f32)>, + stroke: Option, /// Group opacity (a fading symbol), applied to the shape as a whole. opacity: f32, /// Mask outlines this artwork shows through (their union). masks: Vec, } +/// A stroke in one frame, in stage space. +#[derive(Clone, PartialEq)] +struct Line { + color: Rgba, + width: f32, + /// Lottie's line cap and join numbers (1 butt / miter, 2 round, 3 square / bevel). + cap: u8, + join: u8, + miter: f32, + /// On and off lengths (stage units), and the offset into them. + dash: Vec, + offset: f32, +} + +impl Line { + /// A round, solid line (outline mode's hairline). + fn round(color: Rgba, width: f32) -> Line { + Line { color, width, cap: 2, join: 2, miter: 4.0, dash: Vec::new(), offset: 0.0 } + } + + fn of(st: &anicraft_doc::Stroke, color: Rgba, k: f32) -> Line { + use anicraft_doc::{Cap, Join}; + let style = &st.style; + let cap = match style.effective_cap() { + Cap::Butt => 1, + Cap::Round => 2, + Cap::Square => 3, + }; + let join = match style.join { + Join::Miter => 1, + Join::Round => 2, + Join::Bevel => 3, + }; + let (dash, offset) = style.dash.as_ref().map_or((Vec::new(), 0.0), |d| { + let (l, o) = d.pattern(st.width); + (l.into_iter().map(|x| x * k).collect(), o * k) + }); + Line { color, width: st.width * k, cap, join, miter: style.miter_limit, dash, offset } + } +} + /// Subpaths as (closed, vertex count): what must match for values to be keyframed. type Structure = Vec<(bool, usize)>; @@ -155,7 +197,8 @@ struct Key { shape: Structure, fill: u8, stops: usize, - stroke: bool, + /// The stroke's cap, join and dash entry count (its lengths may change from frame to frame). + stroke: Option<(u8, u8, usize)>, masks: Structure, /// Lottie layer blend mode (`bm`). blend: u8, @@ -222,7 +265,7 @@ fn sample(item: &DisplayItem, opacity: f32, masks: Vec, report: &mut HashSe let fx = &item.color; let (fill, stroke) = if let Some(c) = item.outline { // Outline mode: a 1 px hairline in the layer colour, as on the stage. - (None, Some((c, 1.0))) + (None, Some(Line::round(c, 1.0))) } else { let fill = match &item.fill { Some(Paint::Solid(c)) => Some(Fill::Solid { color: fx.apply(*c), rule: item.fill_rule }), @@ -247,7 +290,7 @@ fn sample(item: &DisplayItem, opacity: f32, masks: Vec, report: &mut HashSe }; let stroke = item.stroke.as_ref().and_then(|s| { let w = s.width * m.mean_scale(); - (w.is_finite() && w > 0.0).then(|| (fx.apply(s.color), w)) + (w.is_finite() && w > 0.0).then(|| Line::of(s, fx.apply(s.color), m.mean_scale())) }); (fill, stroke) }; @@ -354,7 +397,7 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo Some(Fill::Gradient { stops, .. }) => stops.len(), _ => 0, }, - stroke: s.stroke.is_some(), + stroke: s.stroke.as_ref().map(|l| (l.cap, l.join, l.dash.len())), masks: s.masks.iter().map(|b| (b.closed, b.v.len())).collect(), blend, }; @@ -485,11 +528,28 @@ fn layer(tr: &Track, ind: usize) -> Value { let values: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.paths.get(k).map(|b| (*t, b.to_value()))).collect(); items.push(json!({"ty": "sh", "nm": format!("Path {}", k + 1), "ks": shape_prop(&values)})); } - if tr.key.stroke { - let color: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.stroke.map(|(c, _)| (*t, rgb(c)))).collect(); - let opacity: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.stroke.map(|(c, _)| (*t, n(c.sanitized().a * 100.0)))).collect(); - let width: Vec<(u32, Value)> = f.iter().filter_map(|(t, s)| s.stroke.map(|(_, w)| (*t, n(w)))).collect(); - items.push(json!({"ty": "st", "nm": "Stroke", "c": prop(&color), "o": prop(&opacity), "w": prop(&width), "lc": 2, "lj": 2, "ml": 4})); + if let Some((cap, join, dashes)) = tr.key.stroke { + let lines: Vec<(u32, &Line)> = f.iter().filter_map(|(t, s)| s.stroke.as_ref().map(|l| (*t, l))).collect(); + let values = |g: &dyn Fn(&Line) -> Value| lines.iter().map(|(t, l)| (*t, g(l))).collect::>(); + let color = values(&|l| rgb(l.color)); + let opacity = values(&|l| n(l.color.sanitized().a * 100.0)); + let width = values(&|l| n(l.width)); + // The miter limit is a plain number in Lottie: the first frame's. + // (Round and bevel joins don't use it: Lottie's usual 4, as before styles.) + let miter = if join == 1 { lines.first().map_or(json!(4), |(_, l)| n(l.miter)) } else { json!(4) }; + let mut st = json!({"ty": "st", "nm": "Stroke", "c": prop(&color), "o": prop(&opacity), "w": prop(&width), "lc": cap, "lj": join, "ml": miter}); + if dashes > 0 { + // Dash, gap, dash, gap…, then the offset; each animates like any value. + let mut d: Vec = (0..dashes) + .map(|k| { + let (code, name) = if k % 2 == 0 { ("d", "dash") } else { ("g", "gap") }; + json!({"n": code, "nm": name, "v": prop(&values(&|l| n(l.dash.get(k).copied().unwrap_or(0.0))))}) + }) + .collect(); + d.push(json!({"n": "o", "nm": "offset", "v": prop(&values(&|l| n(l.offset)))})); + st["d"] = Value::Array(d); + } + items.push(st); } match f.first().and_then(|(_, s)| s.fill.as_ref()) { Some(Fill::Solid { rule: r, .. }) => { @@ -629,4 +689,32 @@ mod tests { assert!(!it.iter().any(|i| i["ty"] == "st"), "no Lottie stroke"); assert!(e.report.is_empty(), "nothing lost: {:?}", e.report); } + + #[test] + fn stroke_caps_joins_and_dashes_carry_across() { + use anicraft_doc::{Cap, Dash, Document, Element, ElementId, ElementKind, Join, Shape, Stroke, StrokeStyle}; + let export = |st: Stroke| { + let mut doc = Document::default(); + let shape = Shape { path: std::sync::Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false }; + let el = Element { id: ElementId(77), name: String::new(), transform: Affine::scale(2.0, 2.0), color: Default::default(), kind: ElementKind::Shape(shape) }; + let layer = std::sync::Arc::make_mut(&mut doc.timeline_mut(0).layers[0]); + layer.keyframe_mut(0).unwrap().elements.push(std::sync::Arc::new(el)); + let v = parse(&to_lottie(&doc, "s", 0, 0, false)); + v["layers"][0]["shapes"][0]["it"].as_array().unwrap().iter().find(|i| i["ty"] == "st").cloned().unwrap() + }; + // Round and solid as before. + let st = export(Stroke::new(Rgba::BLACK, 3.0)); + assert_eq!((st["lc"].clone(), st["lj"].clone(), st["ml"].clone(), st.get("d").is_none()), (json!(2), json!(2), json!(4), true)); + // Butt caps, miter joins with their limit, dashes scaled like the width. + let style = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 6.0, dash: Some(Dash::Dashed { lengths: vec![4.0, 1.5].into(), offset: 1.0 }) }; + let st = export(Stroke::new(Rgba::BLACK, 3.0).with_style(style)); + assert_eq!((st["lc"].clone(), st["lj"].clone(), st["ml"].clone(), st["w"]["k"].clone()), (json!(1), json!(1), json!(6.0), json!(6.0))); + let d = st["d"].as_array().unwrap(); + let got: Vec<(&str, f64)> = d.iter().map(|e| (e["n"].as_str().unwrap(), e["v"]["k"].as_f64().unwrap())).collect(); + assert_eq!(got, [("d", 8.0), ("g", 3.0), ("o", 2.0)]); + // Dots: zero-length dashes with round caps, whatever the cap. + let st = export(Stroke::new(Rgba::BLACK, 3.0).with_style(StrokeStyle { cap: Cap::Square, join: Join::Bevel, dash: Dash::dotted(2.0), ..StrokeStyle::default() })); + assert_eq!((st["lc"].clone(), st["lj"].clone()), (json!(2), json!(3))); + assert_eq!((st["d"][0]["v"]["k"].as_f64(), st["d"][1]["v"]["k"].as_f64()), (Some(0.0), Some(10.0))); + } } diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 82c1feb2..96b790d9 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -5,7 +5,7 @@ //! non-zero rule gives a seamless union without computing an outline offset. use anicraft_doc::width::left_normal; -use anicraft_doc::{DisplayItem, DisplayList, WidthProfile}; +use anicraft_doc::{Cap, DisplayItem, DisplayList, Join, Stroke, WidthProfile}; use anicraft_geom::{Affine, Path, Polyline, Vec2}; fn signed_area(p: &[Vec2]) -> f32 { @@ -211,6 +211,324 @@ pub fn variable_polygons(lines: &[Polyline], hw: f32, profile: &WidthProfile, to out } +/// How a stroke's outline is shaped, in output units (the stroker's view of a +/// [`anicraft_doc::StrokeStyle`]). +#[derive(Clone, Copy, Debug)] +pub struct Outline<'a> { + pub cap: Cap, + pub join: Join, + pub miter_limit: f32, + /// On/off lengths along each subpath (output units, starting with a dash) and how far into + /// them each subpath starts; `None`: solid. + pub dash: Option<(&'a [f32], f32)>, +} + +impl Outline<'_> { + /// Round caps and joins, solid: the stroke every shape had before styles. + pub const ROUND: Outline<'static> = Outline { cap: Cap::Round, join: Join::Round, miter_limit: anicraft_doc::stroke_style::DEFAULT_MITER_LIMIT, dash: None }; + + fn is_round(&self) -> bool { + self.cap == Cap::Round && self.join == Join::Round && self.dash.is_none() + } +} + +/// Most dashes one stroke is cut into; past that, the rest of each subpath draws solid (only +/// reached by very long, very finely dashed lines zoomed far in). +const MAX_DASHES: usize = 200_000; + +/// Polygons covering a stroke with any caps, joins and dashes, uniform (`profile` `None`) or +/// variable, all positively wound like [`stroke_polygons`] so non-zero filling gives their +/// union. Round, solid strokes take [`stroke_polygons`] and [`variable_polygons`] exactly. +/// +/// `hw`, `profile`, `to_local` and `flip` are as in [`variable_polygons`]. Dashes are measured +/// along the flattened lines in output units and restart at every subpath, as in SVG; each +/// dash is an open piece with the stroke's caps, its widths those of its place on the whole +/// subpath. A zero-length dash is a dot: its caps alone. +pub fn styled_polygons(lines: &[Polyline], hw: f32, outline: &Outline, profile: Option<&WidthProfile>, to_local: Option<&Affine>, flip: bool) -> Vec> { + if outline.is_round() { + return match profile { + Some(pr) => variable_polygons(lines, hw, pr, to_local, flip), + None => stroke_polygons(lines, hw), + }; + } + let mut out = Vec::new(); + if !(hw.is_finite() && hw > 0.0) { + return out; + } + let dash = outline.dash.filter(|(l, _)| l.len() >= 2 && l.iter().all(|x| x.is_finite() && *x >= 0.0) && l.iter().sum::() > 1e-6); + let mut budget = MAX_DASHES; + for pl in lines { + let pts = if profile.is_some() { resample(pl) } else { cleaned(pl) }; + let n = pts.len(); + if n < 2 { + continue; + } + let closed = pl.closed && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.distance(*b) < 1e-4); + // Arc length along the output lines (dashes), and in the shape's space (the profile). + let cum = cumulative(&pts); + let widths: Vec<(f32, f32)> = match profile { + Some(pr) => { + let local: Vec = match to_local { + Some(m) => pts.iter().map(|p| m.apply(*p)).collect(), + None => pts.clone(), + }; + let lc = cumulative(&local); + let total = lc.last().copied().filter(|d| d.is_finite() && *d > 0.0).unwrap_or(1.0); + lc.iter().map(|c| side_widths(pr, c / total, hw, flip)).collect() + } + None => vec![(hw, hw); n], + }; + let Some((pattern, offset)) = dash else { + stroke_piece(&pts, &widths, closed, outline, &mut out); + continue; + }; + let total = cum.last().copied().unwrap_or(0.0); + let mut cut = Cutter { pts: &pts, cum: &cum, widths: &widths, seg: 0 }; + for (a, b) in dash_intervals(pattern, offset, total, &mut budget) { + if b - a <= 1e-6 { + // A dot: the caps of a piece with no length. + let (p, d, w) = cut.at(a); + out.extend(cap(p, -d, left_normal(d), w, outline.cap, false)); + out.extend(cap(p, d, left_normal(d), w, outline.cap, true)); + continue; + } + let (piece, pw) = cut.piece(a, b); + stroke_piece(&piece, &pw, false, outline, &mut out); + } + } + out +} + +/// The half-widths on each side at `t` of the way along, in output units. +fn side_widths(pr: &WidthProfile, t: f32, hw: f32, flip: bool) -> (f32, f32) { + let (l, r) = pr.at(t); + if flip { (r * hw, l * hw) } else { (l * hw, r * hw) } +} + +fn cumulative(pts: &[Vec2]) -> Vec { + let mut cum = Vec::with_capacity(pts.len()); + let mut d = 0.0f32; + cum.push(0.0); + for w in pts.windows(2) { + d += w[0].distance(w[1]); + cum.push(d); + } + cum +} + +/// The on stretches `[a, b]` of a dash pattern along a subpath `total` long, in order (a dot +/// is a stretch with `a == b`). Uses up `budget`; when it runs out, the rest of the subpath is +/// one stretch. +fn dash_intervals(pattern: &[f32], offset: f32, total: f32, budget: &mut usize) -> Vec<(f32, f32)> { + let mut out = Vec::new(); + let period: f32 = pattern.iter().sum(); + if !(total.is_finite() && total > 0.0 && period.is_finite() && period > 0.0) { + return out; + } + // Entry `i` of period `k` starts at `base + k · period + starts[i]`: the subpath begins the + // offset into the pattern. (Positions are computed, not summed, so they don't drift.) + let base = -(if offset.is_finite() { offset.rem_euclid(period) } else { 0.0 }); + let mut starts = Vec::with_capacity(pattern.len()); + let mut acc = 0.0f32; + for &len in pattern { + starts.push(acc); + acc += len; + } + // Every period holds a dash (entry 0), so the budget bounds the walk. + 'periods: for k in 0u32.. { + let p0 = base + k as f32 * period; + for (i, (&len, &st)) in pattern.iter().zip(&starts).enumerate() { + let s = p0 + st; + if s > total { + break 'periods; + } + let e = s + len; + if i % 2 == 0 && (if len > 0.0 { e > 0.0 && s < total } else { s >= 0.0 }) { + if *budget == 0 { + out.push((s.max(0.0), total)); + break 'periods; + } + *budget -= 1; + out.push((s.max(0.0), e.min(total))); + } + } + if k == u32::MAX { + break; + } + } + out +} + +/// Cuts pieces out of a subpath by arc length, walking forwards. +struct Cutter<'a> { + pts: &'a [Vec2], + cum: &'a [f32], + widths: &'a [(f32, f32)], + /// The segment the last cut was in. + seg: usize, +} + +impl Cutter<'_> { + /// The segment index holding arc length `s` (moving forwards from the last one). + fn find(&mut self, s: f32) -> usize { + let last = self.pts.len().saturating_sub(2); + while self.seg < last && self.cum.get(self.seg + 1).is_some_and(|&c| c < s) { + self.seg += 1; + } + self.seg + } + + /// The point, direction and widths at arc length `s`. + fn at(&mut self, s: f32) -> (Vec2, Vec2, (f32, f32)) { + let i = self.find(s); + let (a, b) = (self.pts.get(i).copied().unwrap_or(Vec2::ZERO), self.pts.get(i + 1).copied().unwrap_or(Vec2::ZERO)); + let (c0, c1) = (self.cum.get(i).copied().unwrap_or(0.0), self.cum.get(i + 1).copied().unwrap_or(0.0)); + let k = if c1 > c0 { ((s - c0) / (c1 - c0)).clamp(0.0, 1.0) } else { 0.0 }; + let (w0, w1) = (self.widths.get(i).copied().unwrap_or((0.0, 0.0)), self.widths.get(i + 1).copied().unwrap_or((0.0, 0.0))); + let w = (w0.0 + (w1.0 - w0.0) * k, w0.1 + (w1.1 - w0.1) * k); + (a.lerp(b, k), (b - a).normalized(), w) + } + + /// The points and widths from arc length `a` to `b` (no repeated points). + fn piece(&mut self, a: f32, b: f32) -> (Vec, Vec<(f32, f32)>) { + let (p0, _, w0) = self.at(a); + let mut pts = vec![p0]; + let mut ws = vec![w0]; + let mut push = |p: Vec2, w: (f32, f32)| { + if pts.last().is_none_or(|q| q.distance(p) > 1e-6) { + pts.push(p); + ws.push(w); + } + }; + let mut j = self.seg + 1; + while let (Some(&c), Some(&p)) = (self.cum.get(j), self.pts.get(j)) { + if c >= b { + break; + } + if c > a { + push(p, self.widths.get(j).copied().unwrap_or((0.0, 0.0))); + } + j += 1; + } + let (p1, _, w1) = self.at(b); + push(p1, w1); + (pts, ws) + } +} + +/// One open or closed run of points with its half-widths per point: a trapezoid per segment, +/// a join at every bend and caps at open ends. +fn stroke_piece(pts: &[Vec2], widths: &[(f32, f32)], closed: bool, outline: &Outline, out: &mut Vec>) { + let n = pts.len(); + if n < 2 { + return; + } + let w = |i: usize| widths.get(i).copied().unwrap_or((0.0, 0.0)); + let p = |i: usize| pts.get(i).copied().unwrap_or(Vec2::ZERO); + let dir = |i: usize| (p(i + 1) - p(i)).normalized(); + for i in 0..n - 1 { + let (a, b) = (p(i), p(i + 1)); + if a.distance(b) < 1e-6 { + continue; + } + let ((la, ra), (lb, rb)) = (w(i), w(i + 1)); + if la.max(ra).max(lb).max(rb) <= NO_WIDTH { + continue; + } + let nrm = left_normal(dir(i)); + out.push(oriented(vec![a + nrm * la, b + nrm * lb, b - nrm * rb, a - nrm * ra])); + } + let joints = (1..n - 1).map(|i| (i, i - 1, i)).chain(closed.then_some((0, n - 2, 0))); + for (at, before, after) in joints { + out.extend(join(p(at), dir(before), dir(after), w(at), outline)); + } + if !closed { + let (d0, d1) = (dir(0), dir(n - 2)); + out.extend(cap(p(0), -d0, left_normal(d0), w(0), outline.cap, false)); + out.extend(cap(p(n - 1), d1, left_normal(d1), w(n - 1), outline.cap, true)); + } +} + +/// What fills the outer side of a bend at `p` from direction `u` to `v` (unit vectors), with +/// half-widths `(left, right)` there; `None` on (nearly) straight runs, where the segments' +/// trapezoids already meet. +fn join(p: Vec2, u: Vec2, v: Vec2, (l, r): (f32, f32), outline: &Outline) -> Option> { + if u.dot(v) > 0.0 && u.cross(v).abs() * l.max(r) < 0.05 { + return None; + } + // The gap opens on the outside of the bend, around the direction u − v. + let mid = (u - v).normalized(); + let (n0, n1) = (left_normal(u), left_normal(v)); + let (s, radius) = if mid.dot(n0) >= 0.0 { (1.0, l) } else { (-1.0, r) }; + if radius <= NO_WIDTH { + return None; + } + let (o0, o1) = (n0 * s, n1 * s); + let (a, b) = (p + o0 * radius, p + o1 * radius); + match outline.join { + Join::Round => { + let (a0, a1, am) = (angle(o0), angle(o1), angle(mid)); + let wrap = |x: f32| (x + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; + let mut sweep = wrap(a1 - a0); + let to_mid = wrap(am - a0); + if to_mid * sweep < 0.0 || to_mid.abs() > sweep.abs() { + sweep -= std::f32::consts::TAU.copysign(sweep); + } + fan(p, a0, sweep, radius, radius) + } + Join::Miter | Join::Bevel => { + // The outer edges meet at p + (o0 + o1) / (1 + o0·o1) · radius, 1 / cos(θ/2) half- + // widths out (θ the turn); SVG's miter ratio is that over the half-width. + let c = 1.0 + o0.dot(o1); + let limit = outline.miter_limit.clamp(1.0, anicraft_doc::stroke_style::MAX_MITER_LIMIT); + if outline.join == Join::Miter && c > 1e-6 && c * limit * limit >= 2.0 { + let tip = p + (o0 + o1) * (radius / c); + Some(oriented(vec![p, a, tip, b])) + } else { + Some(oriented(vec![p, a, b])) + } + } + } +} + +/// The cap at end `at` of a piece, facing `out` (unit, away from the piece), across the cross- +/// section with left normal `nrm` and half-widths `(left, right)`. `end`: the piece's last +/// point (so the half disc turns the other way). +fn cap(at: Vec2, out: Vec2, nrm: Vec2, (l, r): (f32, f32), kind: Cap, end: bool) -> Option> { + let half = (l + r) * 0.5; + if half <= NO_WIDTH || !out.is_finite() { + return None; + } + match kind { + Cap::Butt => None, + // Half a disc across the cross-section (so a one-sided width stays on its side). + Cap::Round => fan(at + nrm * ((l - r) * 0.5), angle(nrm), if end { std::f32::consts::PI } else { -std::f32::consts::PI }, half, half), + // The cross-section carried half its thickness past the end. + Cap::Square => { + let (pl, pr) = (at + nrm * l, at - nrm * r); + Some(oriented(vec![pl, pl + out * half, pr + out * half, pr])) + } + } +} + +/// A polyline's finite points with repeats dropped and the start repeated at the end when it +/// is closed (no subdivision: one width needs none). +fn cleaned(pl: &Polyline) -> Vec { + let mut out: Vec = Vec::with_capacity(pl.points.len() + 1); + for &p in pl.points.iter().filter(|p| p.is_finite()) { + if out.last().is_none_or(|q| q.distance(p) > 1e-6) { + out.push(p); + } + } + if pl.closed + && let (Some(&first), Some(&last)) = (out.first(), out.last()) + && first.distance(last) > 1e-6 + { + out.push(first); + } + out +} + /// A polyline's points with long segments subdivided (so widths can follow a profile), the /// start repeated at the end when it is closed, and repeated points dropped. fn resample(pl: &Polyline) -> Vec { @@ -243,14 +561,65 @@ fn resample(pl: &Polyline) -> Vec { out } -/// A variable-width stroke as a filled outline in `m`'s output space, for vector exports: the -/// same polygons the renderer fills, as closed subpaths (fill them non-zero). -pub fn variable_outline(path: &Path, m: &Affine, width: f32, profile: &WidthProfile, tolerance: f32) -> Path { +/// The polygons stroke `st` fills along `lines` (its path flattened through `m`), and how much +/// to fade them; `None` when it draws nothing. +/// +/// `raster` is what the renderer does for strokes too fine for pixels: a stroke thinner than +/// one output unit keeps that footprint and fades by its width instead (no dropouts), and a +/// dash pattern repeating in less than one output unit draws solid, faded by how much of it is +/// on. Vector outlines leave it off and get the exact geometry. Dash lengths are measured along +/// the output lines, scaled like the width (by the mean scale of `m`), so vector exports, which +/// write `stroke-dasharray` the same way, draw the same dashes. +pub fn stroke_geometry(lines: &[Polyline], st: &Stroke, m: &Affine, raster: bool) -> Option<(Vec>, f32)> { + let scale = m.mean_scale(); + let mut pw = st.width * scale; + if !(pw.is_finite() && pw > 0.0) { + return None; + } + let mut alpha = 1.0f32; + let widest = pw * st.profile.as_ref().map_or(1.0, WidthProfile::max_factor); + if !(widest.is_finite() && widest > 0.0) { + return None; + } + if raster && widest < 1.0 { + alpha *= widest; + pw /= widest; + } + let style = &st.style; + let cap = style.effective_cap(); + let pattern = style.dash.as_ref().map(|d| { + let (l, o) = d.pattern(st.width); + (l.into_iter().map(|x| x * scale).collect::>(), o * scale) + }); + let mut dash = pattern.as_ref().map(|(l, o)| (l.as_slice(), *o)); + if let Some((l, _)) = dash { + let period: f32 = l.iter().sum(); + if !(period.is_finite() && period > 0.0) { + dash = None; + } else if raster && period < 1.0 { + // Finer than a pixel: solid, as light as the pattern's ink. + let dashes = l.len().div_ceil(2) as f32; + let on: f32 = l.iter().step_by(2).sum::() + if cap == Cap::Butt { 0.0 } else { dashes * pw }; + alpha *= (on / period).clamp(0.0, 1.0); + dash = None; + } + } + let outline = Outline { cap, join: style.join, miter_limit: style.miter_limit, dash }; + let (to_local, flip) = match &st.profile { + Some(_) => (m.inverse(), m.determinant() < 0.0), + None => (None, false), + }; + let polys = styled_polygons(lines, pw * 0.5, &outline, st.profile.as_ref(), to_local.as_ref(), flip); + Some((polys, alpha)) +} + +/// A stroke as a filled outline in `m`'s output space, for vector exports: the same polygons +/// the renderer fills, as closed subpaths (fill them non-zero). +pub fn stroke_outline(path: &Path, m: &Affine, st: &Stroke, tolerance: f32) -> Path { let lines = path.flatten(m, tolerance); - let to_local = m.inverse(); - let flip = m.determinant() < 0.0; let mut out = Path::new(); - for poly in variable_polygons(&lines, width * 0.5 * m.mean_scale(), profile, to_local.as_ref(), flip) { + let Some((polys, _)) = stroke_geometry(&lines, st, m, false) else { return out }; + for poly in polys { let mut it = poly.into_iter(); let Some(first) = it.next() else { continue }; out.move_to(first); @@ -272,7 +641,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa } let mut items = Vec::with_capacity(dl.items.len() + 8); for it in &dl.items { - let Some((st, profile)) = it.stroke.as_ref().and_then(|s| s.profile.as_ref().map(|p| (s, p))).filter(|_| varies(it)) else { + let Some(st) = it.stroke.as_ref().filter(|_| varies(it)) else { items.push(it.clone()); continue; }; @@ -282,7 +651,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa if !it.transform.is_finite() { continue; } - let outline = variable_outline(&it.path, &it.transform, st.width, profile, crate::TOLERANCE); + let outline = stroke_outline(&it.path, &it.transform, st, crate::TOLERANCE); if !outline.is_empty() { items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() }); } @@ -290,6 +659,10 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa std::borrow::Cow::Owned(DisplayList { items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() }) } +#[cfg(test)] +#[path = "stroke_style_tests.rs"] +mod style_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/render/src/stroke_style_tests.rs b/crates/render/src/stroke_style_tests.rs new file mode 100644 index 00000000..cf52fb5e --- /dev/null +++ b/crates/render/src/stroke_style_tests.rs @@ -0,0 +1,228 @@ +//! Analytic tests of caps, joins, the miter limit and dashes (ADR 0046). + +use super::*; + +fn area(polys: &[Vec]) -> f32 { + polys.iter().map(|p| signed_area(p)).sum() +} + +fn styled(points: &[(f32, f32)], closed: bool, hw: f32, o: &Outline) -> Vec> { + let pl = Polyline { points: points.iter().map(|&(x, y)| Vec2::new(x, y)).collect(), closed }; + let polys = styled_polygons(&[pl], hw, o, None, None, false); + assert!(polys.iter().all(|p| signed_area(p) >= 0.0 && p.iter().all(|q| q.is_finite())), "positive and finite"); + polys +} + +fn outline(cap: Cap, join: Join) -> Outline<'static> { + Outline { cap, join, ..Outline::ROUND } +} + +/// Whether `q` is inside the union (non-zero winding over every polygon). +fn covered(polys: &[Vec], q: Vec2) -> bool { + let mut wn = 0i32; + for p in polys { + for (i, &a) in p.iter().enumerate() { + let b = p[(i + 1) % p.len()]; + let side = (b - a).cross(q - a); + if a.y <= q.y && b.y > q.y && side > 0.0 { + wn += 1; + } else if a.y > q.y && b.y <= q.y && side < 0.0 { + wn -= 1; + } + } + } + wn != 0 +} + +/// The union's area by sampling a grid `step` apart over `[x0, x1] × [y0, y1]`. +fn union_area(polys: &[Vec], (x0, y0, x1, y1): (f32, f32, f32, f32), step: f32) -> f32 { + let mut n = 0usize; + let (nx, ny) = (((x1 - x0) / step) as usize, ((y1 - y0) / step) as usize); + for j in 0..ny { + for i in 0..nx { + if covered(polys, Vec2::new(x0 + (i as f32 + 0.5) * step, y0 + (j as f32 + 0.5) * step)) { + n += 1; + } + } + } + n as f32 * step * step +} + +#[test] +fn butt_square_and_round_caps_differ_by_their_ends() { + let line = [(0.0, 0.0), (100.0, 0.0)]; + // A butt-capped line is exactly its rectangle; square caps add half a width at each end. + let butt = styled(&line, false, 5.0, &outline(Cap::Butt, Join::Miter)); + assert_eq!(butt.len(), 1); + assert!((area(&butt) - 1000.0).abs() < 1e-3, "{}", area(&butt)); + let square = styled(&line, false, 5.0, &outline(Cap::Square, Join::Miter)); + assert!((area(&square) - 1100.0).abs() < 1e-3, "{}", area(&square)); + let xs = |p: &[Vec]| p.iter().flatten().fold((f32::MAX, f32::MIN), |(lo, hi), q| (lo.min(q.x), hi.max(q.x))); + assert_eq!(xs(&butt), (0.0, 100.0)); + assert_eq!(xs(&square), (-5.0, 105.0)); + // Round: the rectangle plus a disc (half at each end), within the arc tolerance. + let round = styled(&line, false, 5.0, &outline(Cap::Round, Join::Bevel)); + let want = 1000.0 + std::f32::consts::PI * 25.0; + assert!((area(&round) - want).abs() < 0.01 * want, "{} vs {want}", area(&round)); +} + +#[test] +fn miter_bevel_and_round_corners() { + // Right 50 then down 50 (y-down): the outer corner is up and to the right of (50, 0). + let l = [(0.0, 0.0), (50.0, 0.0), (50.0, 50.0)]; + let corner = |join| { + let polys = styled(&l, false, 5.0, &outline(Cap::Butt, join)); + // The corner piece alone: everything but the two segment rectangles. + area(&polys) - 2.0 * 500.0 + }; + assert!((corner(Join::Miter) - 25.0).abs() < 1e-3, "a 5 × 5 square: {}", corner(Join::Miter)); + assert!((corner(Join::Bevel) - 12.5).abs() < 1e-3, "half of it: {}", corner(Join::Bevel)); + let round = corner(Join::Round); + assert!((round - std::f32::consts::PI * 25.0 / 4.0).abs() < 0.6, "a quarter disc, within the arc tolerance: {round}"); + // The miter reaches the corner (55, -5); the bevel stops at the diagonal. + let miter = styled(&l, false, 5.0, &outline(Cap::Butt, Join::Miter)); + let bevel = styled(&l, false, 5.0, &outline(Cap::Butt, Join::Bevel)); + assert!(covered(&miter, Vec2::new(54.5, -4.5)) && !covered(&bevel, Vec2::new(54.5, -4.5))); + assert!(covered(&bevel, Vec2::new(52.0, -2.0))); + // A closed square with miters is a full frame: the outer square less the inner one. + let sq = styled(&[(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (0.0, 40.0)], true, 2.0, &outline(Cap::Round, Join::Miter)); + let a = union_area(&sq, (-4.0, -4.0, 44.0, 44.0), 0.25); + assert!((a - (44.0 * 44.0 - 36.0 * 36.0)).abs() < 4.0, "{a}"); + assert!(covered(&sq, Vec2::new(-1.9, -1.9)), "sharp outer corner, also where the path closes"); +} + +#[test] +fn the_miter_limit_bevels_sharp_corners() { + // A 160° turn (a 20° corner): the miter is 1 / sin(10°) ≈ 5.76 half-widths long. + let back = 20f32.to_radians(); + let l = [(0.0, 0.0), (50.0, 0.0), (50.0 - 30.0 * back.cos(), 30.0 * back.sin())]; + let ratio = 1.0 / 10f32.to_radians().sin(); + let reach = |limit: f32| { + let o = Outline { miter_limit: limit, ..outline(Cap::Butt, Join::Miter) }; + styled(&l, false, 2.0, &o).iter().flatten().map(|q| q.distance(Vec2::new(50.0, 0.0))).filter(|d| *d < 20.0).fold(0.0f32, f32::max) + }; + assert!((reach(6.0) - ratio * 2.0).abs() < 1e-3, "under the limit: a point {} px out", reach(6.0)); + assert!(reach(5.5) < 2.0 + 1e-3, "over the limit: bevelled, {} px out", reach(5.5)); + // Animate's default (3) and SVG's (4) both bevel it. + assert!(reach(3.0) < 2.0 + 1e-3 && reach(4.0) < 2.0 + 1e-3); +} + +#[test] +fn dashes_follow_curves_by_arc_length() { + // A circle of radius 50 flattened finely, dashed 10 on, 10 off from its start. + let r = 50.0f32; + let ring: Vec<(f32, f32)> = (0..720) + .map(|i| { + let a = i as f32 / 720.0 * std::f32::consts::TAU; + (r * a.cos(), r * a.sin()) + }) + .collect(); + let pattern = [10.0, 10.0]; + let o = Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Butt, Join::Round) }; + let polys = styled(&ring, true, 1.5, &o); + let on_ring = |s: f32| Vec2::new(r * (s / r).cos(), r * (s / r).sin()); + for k in 0..15 { + let s = k as f32 * 20.0; + assert!(covered(&polys, on_ring(s + 5.0)), "dash {k} is drawn at arc length {}", s + 5.0); + assert!(!covered(&polys, on_ring(s + 15.0)), "gap {k} is empty at arc length {}", s + 15.0); + assert!(covered(&polys, on_ring(s + 0.3)) && !covered(&polys, on_ring(s + 10.3)), "dash {k} runs from {s} to {}", s + 10.0); + } + // The offset moves the pattern along: 5 in, the first dash is half gone. + let o = Outline { dash: Some((&pattern, 5.0)), ..o }; + let shifted = styled(&ring, true, 1.5, &o); + assert!(covered(&shifted, on_ring(2.0)) && !covered(&shifted, on_ring(7.0)) && covered(&shifted, on_ring(17.0))); + // Butt-capped dashes: about the on share of the ring's area (π((r+w)² − (r−w)²)). + let ring_area = std::f32::consts::PI * ((r + 1.5).powi(2) - (r - 1.5).powi(2)); + assert!((area(&polys) - ring_area * 0.5).abs() < 0.03 * ring_area, "{} vs {}", area(&polys), ring_area * 0.5); +} + +#[test] +fn dash_intervals_walk_the_pattern() { + let mut budget = 100; + assert_eq!(dash_intervals(&[3.0, 2.0], 0.0, 12.0, &mut budget), vec![(0.0, 3.0), (5.0, 8.0), (10.0, 12.0)]); + assert_eq!(dash_intervals(&[3.0, 2.0], 4.0, 6.0, &mut budget), vec![(1.0, 4.0)]); + assert_eq!(dash_intervals(&[3.0, 2.0], -1.0, 6.0, &mut budget), vec![(1.0, 4.0)], "a negative offset counts back from the end of the period"); + // Dots: zero-length dashes, the last one on the very end. + assert_eq!(dash_intervals(&[0.0, 5.0], 0.0, 10.0, &mut budget), vec![(0.0, 0.0), (5.0, 5.0), (10.0, 10.0)]); + // The budget bounds the walk; the rest is one stretch. + let mut small = 2; + assert_eq!(dash_intervals(&[1.0, 1.0], 0.0, 1e9, &mut small), vec![(0.0, 1.0), (2.0, 3.0), (4.0, 1e9)]); + assert!(dash_intervals(&[1.0, 1.0], f32::NAN, f32::INFINITY, &mut budget).is_empty()); + assert!(dash_intervals(&[0.0, 0.0], 0.0, 5.0, &mut budget).is_empty()); +} + +#[test] +fn dashes_keep_the_width_profile_of_their_place() { + let line = Polyline { points: vec![Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)], closed: false }; + let taper = anicraft_doc::ProfilePreset::TaperBoth.profile().unwrap(); + let pattern = [10.0, 10.0]; + let o = Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Butt, Join::Round) }; + let polys = styled_polygons(std::slice::from_ref(&line), 5.0, &o, Some(&taper), None, false); + assert!(polys.iter().all(|p| signed_area(p) >= 0.0)); + // In the dash from 40 to 50 the half-width is the profile's there; 50..60 is a gap. + for x in [42.0f32, 45.0, 48.0] { + let want = taper.at(x / 100.0).0 * 5.0; + assert!(covered(&polys, Vec2::new(x, -(want - 0.1))) && !covered(&polys, Vec2::new(x, -(want + 0.1))), "half-width {want} at {x}"); + } + assert!(!covered(&polys, Vec2::new(55.0, 0.0))); +} + +#[test] +fn dots_are_discs_one_width_across() { + let pattern = [0.0, 10.0]; + let o = Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Round, Join::Round) }; + let line = [(0.0, 0.0), (100.0, 0.0)]; + let polys = styled(&line, false, 2.0, &o); + // Eleven dots (0, 10, … 100), each two half discs of radius 2. + assert_eq!(polys.len(), 22); + let want = 11.0 * std::f32::consts::PI * 4.0; + assert!((area(&polys) - want).abs() < 0.08 * want, "within the arc tolerance: {} vs {want}", area(&polys)); + assert!(covered(&polys, Vec2::new(30.0, 1.5)) && !covered(&polys, Vec2::new(35.0, 0.0))); + // Butt-capped dots draw nothing; square ones are squares. + let o = Outline { cap: Cap::Butt, ..o }; + assert!(styled(&line, false, 2.0, &o).is_empty()); + let o = Outline { cap: Cap::Square, ..o }; + assert!((area(&styled(&line, false, 2.0, &o)) - 11.0 * 16.0).abs() < 1e-2); +} + +#[test] +fn round_solid_strokes_take_the_old_paths_exactly() { + 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 }; + assert_eq!(styled_polygons(std::slice::from_ref(&pl), 2.0, &Outline::ROUND, None, None, false), stroke_polygons(std::slice::from_ref(&pl), 2.0)); + let taper = anicraft_doc::ProfilePreset::TaperEnd.profile().unwrap(); + assert_eq!(styled_polygons(std::slice::from_ref(&pl), 2.0, &Outline::ROUND, Some(&taper), None, false), variable_polygons(&[pl], 2.0, &taper, None, false)); +} + +#[test] +fn styled_degenerate_inputs_are_safe() { + let pattern = [1.0, 1.0]; + for o in [outline(Cap::Square, Join::Miter), Outline { dash: Some((&pattern, 0.0)), ..outline(Cap::Butt, Join::Bevel) }] { + assert!(styled_polygons(&[], 1.0, &o, None, None, false).is_empty()); + for pts in [vec![Vec2::ZERO; 3], vec![Vec2::ZERO, Vec2::new(f32::NAN, 1.0), Vec2::new(5.0, 0.0), Vec2::new(5.0, 0.0), Vec2::ZERO], vec![Vec2::ZERO, Vec2::new(1e30, 0.0), Vec2::new(-1e30, 0.0)]] { + for closed in [false, true] { + let polys = styled_polygons(&[Polyline { points: pts.clone(), closed }], 1.0, &o, None, None, false); + assert!(polys.iter().flatten().all(|q| q.is_finite())); + } + } + assert!(styled_polygons(&[Polyline { points: vec![Vec2::ZERO, Vec2::new(5.0, 0.0)], closed: false }], f32::NAN, &o, None, None, false).is_empty()); + } + // A U-turn with a miter join: bevelled, never a point at infinity. + let polys = styled(&[(0.0, 0.0), (10.0, 0.0), (0.0, 0.0)], false, 1.0, &outline(Cap::Butt, Join::Miter)); + assert!(polys.iter().flatten().all(|q| q.length() < 20.0)); +} + +#[test] +fn fine_patterns_draw_solid_and_lighter_on_raster() { + // A 0.2-unit pattern at 1:1 is finer than a pixel: solid, at the share that is on. + let st = anicraft_doc::Stroke::new(anicraft_doc::Rgba::BLACK, 4.0).with_style(anicraft_doc::StrokeStyle { cap: Cap::Butt, dash: anicraft_doc::Dash::dashed(0.05, 0.15), ..Default::default() }); + let lines = [Polyline { points: vec![Vec2::ZERO, Vec2::new(50.0, 0.0)], closed: false }]; + let (polys, alpha) = stroke_geometry(&lines, &st, &Affine::IDENTITY, true).unwrap(); + assert_eq!(polys.len(), 1); + assert!((alpha - 0.25).abs() < 1e-4, "{alpha}"); + // Vector outlines keep every dash. + let (exact, a) = stroke_geometry(&lines, &st, &Affine::IDENTITY, false).unwrap(); + assert_eq!((exact.len(), a), (250, 1.0)); + // Zoomed in 10×, the pattern is two pixels: real dashes, and their lengths scale. + let (zoomed, a) = stroke_geometry(&[Polyline { points: vec![Vec2::ZERO, Vec2::new(500.0, 0.0)], closed: false }], &st, &Affine::scale(10.0, 10.0), true).unwrap(); + assert_eq!((zoomed.len(), a), (250, 1.0)); +} diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 406377f3..4859cb31 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -2,7 +2,9 @@ //! //! It draws what the CPU renderer draws, from the same evaluated frame: //! * paths are written in stage space, and strokes get the same stage-space width -//! (`width × mean scale`, round joins and caps); +//! (`width × mean scale`) with their caps, joins and miter limit, and dashes scaled the same +//! way (`stroke-dasharray`, `stroke-dashoffset`; dots are zero-length round-capped dashes), +//! as the renderer measures them (ADR 0046); //! * gradients keep their local geometry under a `gradientTransform`, padded at the ends; //! * colour effects (alpha, tint) are baked into every colour and stop; //! * masks become `clipPath`s (fill areas only, nested through `clip-path` on the clip), and an @@ -90,9 +92,10 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { let c = item.color.apply(st.color); let _ = write!( body, - "", + "", color_attrs("stroke", c), - num(width) + num(width), + style_attrs(st, item.transform.mean_scale()) ); } } @@ -142,6 +145,25 @@ fn num(v: f32) -> String { if r == 0.0 { "0".into() } else { format!("{r}") } } +/// A stroke's join, cap, miter limit and dashes as SVG attributes (dash lengths scaled by `k`, +/// like the width). The default style writes `stroke-linejoin="round" stroke-linecap="round"`. +fn style_attrs(st: &anicraft_doc::Stroke, k: f32) -> String { + let style = &st.style; + let mut out = format!(" stroke-linejoin=\"{}\" stroke-linecap=\"{}\"", style.join.key(), style.effective_cap().key()); + if style.join == anicraft_doc::Join::Miter { + let _ = write!(out, " stroke-miterlimit=\"{}\"", num(style.miter_limit)); + } + if let Some(dash) = &style.dash { + let (lengths, offset) = dash.pattern(st.width); + let list: Vec = lengths.iter().map(|l| num(l * k)).collect(); + let _ = write!(out, " stroke-dasharray=\"{}\"", list.join(" ")); + if num(offset * k) != "0" { + let _ = write!(out, " stroke-dashoffset=\"{}\"", num(offset * k)); + } + } + out +} + fn hex(c: Rgba) -> String { c.sanitized().to_hex() } @@ -435,6 +457,29 @@ mod tests { assert!(svg.trim_end().ends_with("")); } + #[test] + fn stroke_caps_joins_and_dashes_are_written_scaled() { + use anicraft_doc::{Cap, Dash, Join, StrokeStyle}; + let svg_of = |st: Stroke| { + let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None); + a.transform = Affine::scale(2.0, 2.0); + a.stroke = Some(st); + to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()) + }; + // The default style is written as before: round, no dashes. + let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0)); + assert!(svg.contains("stroke-width=\"6\" stroke-linejoin=\"round\" stroke-linecap=\"round\"/>"), "{svg}"); + assert!(!svg.contains("dasharray") && !svg.contains("miterlimit")); + // Dashes, offset and the miter limit; lengths scale with the shape, like the width. + let dashed = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 6.0, dash: Some(Dash::Dashed { lengths: vec![4.0, 1.5].into(), offset: 1.0 }) }; + let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0).with_style(dashed)); + assert!(svg.contains("stroke-linejoin=\"miter\" stroke-linecap=\"butt\" stroke-miterlimit=\"6\" stroke-dasharray=\"8 3\" stroke-dashoffset=\"2\"/>"), "{svg}"); + // Dots: zero-length round dashes one width plus the spacing apart. + let dotted = StrokeStyle { cap: Cap::Square, join: Join::Bevel, dash: Dash::dotted(2.0), ..StrokeStyle::default() }; + let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0).with_style(dotted)); + assert!(svg.contains("stroke-linejoin=\"bevel\" stroke-linecap=\"round\" stroke-dasharray=\"0 10\"/>"), "{svg}"); + } + #[test] fn variable_width_strokes_are_written_as_filled_outlines() { let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000)))); diff --git a/crates/svg/src/clip.rs b/crates/svg/src/clip.rs index 81c1037f..211f13b1 100644 --- a/crates/svg/src/clip.rs +++ b/crates/svg/src/clip.rs @@ -11,7 +11,7 @@ //! * consecutive items with the same mask share one masked layer under one mask layer. use crate::{Builder, ImportedElement, ImportedLayer, ImportedMask, Item, PaintSpec, Report, Style, declarations, get, hidden, length, local, name_of, paint_spec, transform}; -use anicraft_doc::{ElementKind, Paint, Rgba, Shape}; +use anicraft_doc::{ElementKind, Paint, Rgba, Shape, Stroke}; use anicraft_geom::clip::{clip_convex, convex_polygon}; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; use anicraft_xml::Element as X; @@ -40,7 +40,7 @@ pub(crate) struct Region { /// Conservative drawing-space bounds of an element's artwork. fn element_bounds(e: &ImportedElement) -> Rect { match &e.kind { - ElementKind::Shape(s) => s.path.bounds().inflate(s.stroke.as_ref().map_or(0.0, |st| st.width * 0.5)).transformed(&e.transform), + ElementKind::Shape(s) => s.path.bounds().inflate(s.stroke.as_ref().map_or(0.0, Stroke::reach)).transformed(&e.transform), ElementKind::Text(t) => t.outline.bounds().union(&Rect::new(0.0, 0.0, t.box_width.max(0.0), t.box_height.max(0.0))).transformed(&e.transform), ElementKind::Symbol { .. } | ElementKind::Camera => Rect::EMPTY, } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index f6599562..d19291ba 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -5,7 +5,9 @@ //! and `polygon`, read in document order. Styling comes from presentation attributes and //! `style=""` declarations, with inheritance. Colours can be hex, `rgb()`/`rgba()`, CSS names, //! `none`, `transparent` or `currentColor`. Also supported: `opacity`, `fill-opacity` and -//! `stroke-opacity`, `fill-rule`, `stroke-width` with units, the transform list (`matrix`, +//! `stroke-opacity`, `fill-rule`, `stroke-width` with units, `stroke-linecap`, +//! `stroke-linejoin`, `stroke-miterlimit`, `stroke-dasharray` and `stroke-dashoffset` (ADR 0046; +//! SVG's defaults: butt caps, miter joins, limit 4), the transform list (`matrix`, //! `translate`, `scale`, `rotate`, `skewX`, `skewY`), `viewBox` with `preserveAspectRatio`, and //! linear and radial gradients (both unit systems, `gradientTransform`, stops inherited through //! `href`). @@ -20,11 +22,11 @@ //! (ADR 0014). //! //! What AniCraft cannot represent yet is reported, never guessed silently: images, filters, -//! soft masks, patterns, dashes, style sheets, text on a path, reflected/repeated gradients and +//! soft masks, patterns, style sheets, text on a path, reflected/repeated gradients and //! skewed gradient transforms (approximated). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use anicraft_doc::{ElementKind, GradientStop, Paint, Rgba, Shape, Stroke}; +use anicraft_doc::{Cap, Dash, ElementKind, GradientStop, Join, Paint, Rgba, Shape, Stroke, StrokeStyle}; use anicraft_geom::svg::parse_path_data; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; use anicraft_text::{FaceMatch, Fonts}; @@ -467,6 +469,12 @@ struct Style { stroke: PaintSpec, stroke_opacity: f32, stroke_width: f32, + cap: Cap, + join: Join, + miter_limit: f32, + /// `stroke-dasharray` lengths (user units); `None`: solid. + dash: Option>, + dash_offset: f32, current: Rgba, /// The CSS `font-family` list, as written. font_family: String, @@ -489,6 +497,12 @@ impl Default for Style { stroke: PaintSpec::None, stroke_opacity: 1.0, stroke_width: 1.0, + // SVG's initial values, not AniCraft's (round) defaults. + cap: Cap::Butt, + join: Join::Miter, + miter_limit: 4.0, + dash: None, + dash_offset: 0.0, current: Rgba::BLACK, font_family: String::new(), font_size: 16.0, @@ -511,7 +525,11 @@ fn declarations(el: &X) -> Vec<(String, String)> { "stroke", "stroke-opacity", "stroke-width", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", "stroke-dasharray", + "stroke-dashoffset", "color", "opacity", "display", @@ -544,6 +562,23 @@ fn declarations(el: &X) -> Vec<(String, String)> { out } +/// A `stroke-dasharray`: lengths separated by commas or spaces. `none`, an empty list, a +/// negative or unreadable length all draw solid (SVG renders an invalid array as none). +fn dash_array(v: &str) -> Option> { + if v.trim() == "none" { + return None; + } + let mut out = Vec::new(); + for part in v.split(|c: char| c == ',' || c.is_whitespace()).filter(|p| !p.trim().is_empty()).take(1024) { + let x = length(part, 100.0)?; + if x < 0.0 { + return None; + } + out.push(x); + } + (!out.is_empty()).then_some(out) +} + fn get<'a>(d: &'a [(String, String)], key: &str) -> Option<&'a str> { d.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v.as_str()) } @@ -649,8 +684,29 @@ impl Style { Some("default") => s.preserve = false, _ => {} } - if get(&d, "stroke-dasharray").is_some_and(|v| v != "none") { - report.skip("dashed strokes (drawn solid)"); + match get(&d, "stroke-linecap") { + Some("butt") => s.cap = Cap::Butt, + Some("round") => s.cap = Cap::Round, + Some("square") => s.cap = Cap::Square, + _ => {} + } + match get(&d, "stroke-linejoin") { + Some("miter" | "miter-clip") => s.join = Join::Miter, + Some("round" | "arcs") => s.join = Join::Round, + Some("bevel") => s.join = Join::Bevel, + _ => {} + } + if let Some(m) = get(&d, "stroke-miterlimit").and_then(|v| v.trim().parse::().ok()).filter(|m| m.is_finite() && *m >= 1.0) { + s.miter_limit = m; + } + if let Some(v) = get(&d, "stroke-dasharray").filter(|v| *v != "inherit") { + s.dash = dash_array(v); + if s.dash.as_ref().is_some_and(|l| l.len() > anicraft_doc::stroke_style::MAX_DASH_ENTRIES) { + report.skip("dash patterns of more than 16 lengths (shortened)"); + } + } + if let Some(o) = get(&d, "stroke-dashoffset").and_then(|v| length(v, 100.0)) { + s.dash_offset = o; } if get(&d, "filter").is_some_and(|v| v != "none") { report.skip("filters"); @@ -879,7 +935,8 @@ impl<'a> Builder<'a> { other.primary_color() } }; - Some(Stroke::new(color, style.stroke_width)) + let dash = style.dash.as_ref().and_then(|l| Dash::Dashed { lengths: l.iter().copied().collect(), offset: style.dash_offset }.sanitized()); + Some(Stroke::new(color, style.stroke_width).with_style(StrokeStyle { cap: style.cap, join: style.join, miter_limit: style.miter_limit, dash })) } /// A fill or stroke paint, with `opacity` folded in; `None` draws nothing. diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index f95dd3f6..a26e934a 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -57,7 +57,9 @@ fn shapes_styles_and_inheritance() { let r = &i.shapes[0]; assert_eq!(r.name, "box"); assert_eq!(solid(r), Rgba::hex(0xff0000)); - assert_eq!(r.shape.stroke, Some(Stroke::new(Rgba::hex(0x0000ff), 4.0))); + // SVG's initial stroke style: butt caps, miter joins, a miter limit of 4. + let svg_style = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 4.0, dash: None }; + assert_eq!(r.shape.stroke, Some(Stroke::new(Rgba::hex(0x0000ff), 4.0).with_style(svg_style))); assert_eq!(r.alpha, 0.5, "group opacity reaches every child"); assert_eq!(r.shape.path.bounds(), Rect::new(10.0, 10.0, 60.0, 40.0)); let c = &i.shapes[1]; @@ -147,12 +149,52 @@ fn use_references_and_reported_leftovers() { assert_eq!(first.transform.apply(Vec2::new(0.0, 0.0)), Vec2::new(10.0, 20.0)); assert_eq!(solid(first), Rgba::hex(0x123456)); assert_eq!(i.shapes.len(), 4, "the dot, the symbol's two rects and the plain rect"); - for k in ["text (no fonts on this computer)", "images", "references to missing elements", "dashed strokes (drawn solid)", "filters", "references to missing clip paths (drawn unclipped)", "style sheets (inline styles are read)"] { + for k in ["text (no fonts on this computer)", "images", "references to missing elements", "filters", "references to missing clip paths (drawn unclipped)", "style sheets (inline styles are read)"] { assert_eq!(i.report.skipped.get(k), Some(&1), "{k}: {:?}", i.report); } assert!(i.report.summary().starts_with("Imported. Not yet supported: ")); } +#[test] +fn stroke_caps_joins_and_dashes() { + let i = imp(r##" + + + + + + + + + + "##); + let st = |name: &str| i.shapes.iter().find(|s| s.name == name).and_then(|s| s.shape.stroke.clone()).map(|s| s.style).unwrap(); + assert_eq!(st("inherits"), StrokeStyle { cap: Cap::Round, join: Join::Bevel, miter_limit: 4.0, dash: Some(Dash::Dashed { lengths: vec![6.0, 3.0].into(), offset: 2.0 }) }); + // style= wins; an odd list repeats; units convert; the offset is inherited. + let own = st("own"); + assert_eq!((own.cap, own.join, own.miter_limit), (Cap::Square, Join::Miter, 8.0)); + let pt = 96.0 / 72.0; + assert_eq!(own.dash, Some(Dash::Dashed { lengths: vec![pt, 2.0, 3.0, pt, 2.0, 3.0].into(), offset: 2.0 })); + assert_eq!((st("none").dash, st("none").join), (None, Join::Round)); + // Invalid arrays draw solid (as SVG renders them); unknown values keep the inherited ones. + assert_eq!(st("negative").dash, None); + let junk = st("junk"); + assert_eq!((junk.dash, junk.miter_limit, junk.cap), (None, 4.0, Cap::Round)); + assert_eq!(st("no-gaps").dash, None); + assert_eq!(st("plain"), StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 4.0, dash: None }); + assert!(i.report.skipped.is_empty(), "{:?}", i.report); +} + +#[test] +fn dash_lists() { + assert_eq!(dash_array("5,3 2"), Some(vec![5.0, 3.0, 2.0])); + assert_eq!(dash_array(" 10% , 1in "), Some(vec![10.0, 96.0])); + assert_eq!(dash_array("none"), None); + assert_eq!(dash_array(""), None); + assert_eq!(dash_array("1 -2"), None); + assert_eq!(dash_array("1 nan"), None); +} + #[test] fn colours() { assert_eq!(color("#f00"), Some(Rgba::hex(0xff0000))); diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 16f60a4e..e97c96c5 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -3,23 +3,25 @@ //! 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 +//! linear and radial fills, solid, dashed and dotted strokes with their caps, joints and +//! miter limit), groups (flattened), rectangle and oval //! primitives; symbol instances with their matrix, alpha and tint, loop mode and first frame; //! library symbols (graphic, movie clip, button) with their own timelines, nested to any //! depth; bitmaps (library items, instances and bitmap fills) whose image is stored as PNG or //! JPEG in the package; text fields, laid out with this computer's fonts (`text`, ADR 0014); -//! frame scripts, symbol linkage classes and the document class, kept verbatim and not run -//! (ADR 0013 tier 1; the report lists them as kept). +//! frame scripts, symbol linkage classes and the document class, kept verbatim (ADR 0013 tier +//! 1); frame scripts in the ActionScript 3.0 subset run in Test Movie (tier 2), and the report +//! lists which run and which are only kept. //! Everything else (sound, motion tweens with property curves, unknown filters, //! bitmaps kept only in Animate's own storage) is counted in the report instead of guessed at, -//! and so is whatever is drawn the nearest way AniCraft can (square caps, reflecting -//! gradients, advanced colour effects, …). The self-authored corpus in `tests/corpus/` covers +//! and so is whatever is drawn the nearest way AniCraft can (ragged, stipple and hatched +//! strokes, reflecting gradients, advanced colour effects, …). The self-authored corpus in `tests/corpus/` covers //! every feature listed here, with golden renders (ADR 0035). use crate::edges::{self, Edge}; use crate::xml::{self, Element as X}; use anicraft_doc::{ - Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, + Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, Language, Linkage, SourceScript, }; use anicraft_geom::{Affine, FillRule, Path, Vec2}; @@ -47,13 +49,16 @@ pub enum XflError { NotXfl(String), } -/// What the import couldn't bring across, by kind ("3 bitmaps"), what it kept without -/// running (scripts), and the fonts it couldn't find. +/// What the import couldn't bring across, by kind ("3 bitmaps"), the scripts it brought that +/// run and those it kept without running, and the fonts it couldn't find. #[derive(Debug, Default, Clone, PartialEq)] pub struct Report { pub skipped: BTreeMap, - /// Kept in the document but not run, by kind ("2 frame scripts in ActionScript 3.0"; ADR - /// 0013 tier 1). + /// Frame scripts in the ActionScript 3.0 subset, which run in Test Movie and the HTML + /// canvas export ("2 frame scripts in ActionScript 3.0"; ADR 0013 tier 2). + pub runs: BTreeMap, + /// Kept in the document but not run, by kind ("2 frame scripts in ActionScript 3.0", for + /// those outside the subset; ADR 0013 tier 1). pub kept: BTreeMap, pub notes: Vec, /// Font families the document's text asks for that aren't on this computer. @@ -69,16 +74,21 @@ impl Report { pub(crate) fn keep(&mut self, what: &str) { *self.kept.entry(what.to_string()).or_default() += 1; } - /// One line for a status bar: "Imported. Kept, not run: 3 frame scripts in ActionScript - /// 3.0. Not yet supported: 2 sounds. Fonts not on this computer, drawn in Inter: Futura, - /// Gotham." + pub(crate) fn run(&mut self, what: &str) { + *self.runs.entry(what.to_string()).or_default() += 1; + } + /// One line for a status bar: "Imported. Runs in Test Movie: 2 frame scripts in + /// ActionScript 3.0. Kept, not run: 1 frame scripts in ActionScript 3.0. Not yet supported: + /// 2 sounds. Fonts not on this computer, drawn in Inter: Futura, Gotham." pub fn summary(&self) -> String { - let kept = if self.kept.is_empty() { - String::new() - } else { - let parts: Vec = self.kept.iter().map(|(k, n)| format!("{n} {k}")).collect(); - format!(" Kept, not run: {}.", parts.join(", ")) - }; + let list = |m: &BTreeMap| m.iter().map(|(k, n)| format!("{n} {k}")).collect::>().join(", "); + let mut kept = String::new(); + if !self.runs.is_empty() { + kept.push_str(&format!(" Runs in Test Movie: {}.", list(&self.runs))); + } + if !self.kept.is_empty() { + kept.push_str(&format!(" Kept, not run: {}.", list(&self.kept))); + } if self.skipped.is_empty() && self.notes.is_empty() && self.missing_fonts.is_empty() { return format!("Imported everything in the file.{kept}"); } @@ -215,19 +225,35 @@ fn paint(def: &X, bitmaps: &HashMap, report: &mut Report) -> O } } -/// A stroke definition (`SolidStroke` and friends) as a stroke: weight and its fill colour. -fn stroke(def: &X, bitmaps: &HashMap, report: &mut Report) -> Option { +/// A stroke definition (`SolidStroke` and friends) as a stroke: weight, its fill colour, caps, +/// joints and miter limit, and the dashes of `DashedStroke` and dots of `DottedStroke` +/// (ADR 0046). Ragged, stipple and hatched strokes are drawn solid. +pub(crate) fn stroke(def: &X, bitmaps: &HashMap, 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"); - } - // AniCraft strokes have round caps and joins (the format's default). - let round = |k: &str| def.attr(k).is_none_or(|v| v.trim() == "round"); - if !round("caps") || !round("joints") { - report.skip("stroke caps and joins other than round (drawn round)"); - } + // Round caps and joints are the format's default, and a miter limit of 3. + let cap = match def.attr("caps").map(str::trim) { + Some("none") => Cap::Butt, + Some("square") => Cap::Square, + _ => Cap::Round, + }; + let join = match def.attr("joints").map(str::trim) { + Some("miter") => Join::Miter, + Some("bevel") => Join::Bevel, + _ => Join::Round, + }; + let miter_limit = def.f32("miterLimit").unwrap_or(anicraft_doc::stroke_style::DEFAULT_MITER_LIMIT); + let dash = match def.name.as_str() { + "DashedStroke" => Dash::dashed(def.f32("dash1").unwrap_or(6.0), def.f32("dash2").unwrap_or(3.0)), + "DottedStroke" => Dash::dotted(def.f32("dotSpace").unwrap_or(3.0)), + "SolidStroke" => None, + _ => { + report.skip("ragged, stipple and hatched strokes (drawn solid)"); + None + } + }; + let style = StrokeStyle { cap, join, miter_limit, dash }; 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| { @@ -238,7 +264,7 @@ fn stroke(def: &X, bitmaps: &HashMap, report: &mut Report) -> paint(f, bitmaps, report).map_or(Rgba::BLACK, |p| p.primary_color()) } }); - Some(Stroke::new(c, width)) + Some(Stroke::new(c, width).with_style(style)) } impl<'a> Builder<'a> { @@ -247,9 +273,12 @@ impl<'a> Builder<'a> { } /// 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>) { + /// shape per stroke style, as Animate draws them. A shape loose on a frame (not in a group, + /// not a drawing object) is raw artwork: its shapes are marked to merge (ADR 0042), and the + /// engine merges each keyframe's raw shapes into one drawing when it opens the file. + fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec>, loose: bool) { let m = parent.mul(&matrix(el)); + let merge = loose && !el.bool("isDrawingObject").unwrap_or(false); 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, &self.bitmaps, &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, &self.bitmaps, &mut self.report)))).collect(); let edges: Vec = el @@ -262,14 +291,14 @@ impl<'a> Builder<'a> { 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, merge: false }), m, ColorEffect::default())); + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge }), 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, merge: false }), m, ColorEffect::default())); + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero, merge }), m, ColorEffect::default())); } } } @@ -443,7 +472,7 @@ impl<'a> Builder<'a> { } for el in list { match el.name.as_str() { - "DOMShape" => self.shape(el, parent, out), + "DOMShape" => self.shape(el, parent, out, depth == 0), "DOMGroup" => { let m = parent.mul(&matrix(el)); self.elements(el.list("members"), &m, out, depth + 1); @@ -518,7 +547,7 @@ impl<'a> Builder<'a> { if let Some(h) = f.child("shapeHints").filter(|h| !h.children.is_empty()) { raw_hints.insert(start, self.raw_hints(h)); } - // Frame scripts are kept verbatim and not run (ADR 0013 tier 1). + // Frame scripts are kept verbatim (ADR 0013 tier 1); those in the subset run. if let Some(a) = f.child("Actionscript") { k.script = self.frame_script(a); } @@ -558,7 +587,9 @@ impl<'a> Builder<'a> { self.report.skip("frame scripts over 1 MiB (left out)"); return None; } - self.report.keep(&format!("frame scripts in {}", self.language.label())); + // Compiling here also fills the script's cache for Test Movie (ADR 0013 tier 2). + let what = format!("frame scripts in {}", self.language.label()); + if script.runs() { self.report.run(&what) } else { self.report.keep(&what) } Some(FrameScript::Source(Arc::new(script))) } diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 6099ccaf..0cfb1d90 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -98,14 +98,15 @@ fn stage_layers_frames_and_tweens() { assert_eq!(report.skipped.get("instances of missing bitmaps"), Some(&1)); assert_eq!(report.skipped.get("missing library files"), Some(&1)); assert_eq!(report.skipped.get("unknown filters"), Some(&1)); - // Frame scripts, on the scene's frames and inside symbols, are kept verbatim, not run - // (ADR 0013 tier 1). - assert_eq!(report.kept.get("frame scripts in ActionScript 3.0"), Some(&2)); + // Frame scripts, on the scene's frames and inside symbols, are kept verbatim (ADR 0013 + // tier 1); these are in the subset that runs (tier 2). + assert_eq!(report.runs.get("frame scripts in ActionScript 3.0"), Some(&2)); + assert!(report.kept.is_empty(), "{report:?}"); assert!(report.skipped.keys().all(|k| !k.contains("script")), "{report:?}"); assert_eq!(ball.keyframes[1].script.as_ref().and_then(|s| s.source()).map(|s| s.text.as_str()), Some("stop();")); let inner = &doc.library[0].timeline.layers[0].keyframes[0]; assert!(matches!(inner.script.as_ref().and_then(|s| s.source()), Some(s) if s.text == "gotoAndPlay(2);" && s.language == anicraft_doc::Language::ActionScript3)); - assert!(report.summary().contains("Kept, not run: 2 frame scripts in ActionScript 3.0."), "{}", report.summary()); + assert!(report.summary().contains("Runs in Test Movie: 2 frame scripts in ActionScript 3.0."), "{}", report.summary()); // Every scene comes across, in order. assert_eq!(doc.scenes.iter().map(|s| s.name.as_str()).collect::>(), ["Scene 1", "Scene 2"]); assert_eq!(doc.timeline(1).layers.len(), 1, "an empty scene gets a layer to draw on"); @@ -435,3 +436,56 @@ trace(n);]]> + "##, + x + 2000, + x + 2000 + ) + }; + let doc = format!( + r#"{}{}{}"#, + square("", 0), + square(r#"isDrawingObject="true""#, 4000), + square("", 8000), + ); + let doc: &'static str = Box::leak(doc.into_boxed_str()); + let (d, _) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap(); + let merge: Vec = d.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| matches!(&e.kind, ElementKind::Shape(s) if s.merge)).collect(); + // Each square is a fill and a stroke. + assert_eq!(merge, [true, true, false, false, false, false]); +} + +#[test] +fn stroke_caps_joints_dashes_and_dots_come_across() { + use anicraft_doc::{Cap, Dash, Join, StrokeStyle}; + let read = |xml: &str| { + let el = crate::xml::parse(xml.as_bytes()).unwrap(); + let mut report = crate::Report::default(); + let st = crate::import::stroke(&el, &HashMap::new(), &mut report).unwrap(); + (st, report) + }; + let (st, report) = read(r##""##); + assert_eq!((st.width, st.color), (4.0, Rgba::hex(0x112233))); + assert_eq!(st.style, StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 7.0, dash: None }); + assert!(report.skipped.is_empty()); + // Round caps and joints and a miter limit of 3 are the format's defaults. + assert_eq!(read(r#""#).0.style, StrokeStyle::default()); + assert_eq!(read(r#""#).0.style, StrokeStyle { cap: Cap::Square, join: Join::Bevel, miter_limit: 100.0, dash: None }); + let (dashed, _) = read(r#""#); + assert_eq!(dashed.style, StrokeStyle { cap: Cap::Square, dash: Dash::dashed(8.0, 2.5), ..StrokeStyle::default() }); + // No gap draws solid. + assert_eq!(read(r#""#).0.style.dash, None); + assert_eq!(read(r#""#).0.style.dash, Dash::dotted(5.0)); + for kind in ["RaggedStroke", "StippleStroke", "HatchedStroke"] { + let (st, report) = read(&format!("<{kind} weight=\"2\"/>")); + assert_eq!(st.style.dash, None); + assert_eq!(report.skipped.get("ragged, stipple and hatched strokes (drawn solid)"), Some(&1)); + } +} diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index 821762bc..44e019d6 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -67,11 +67,12 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ ], ), ("guides", &[]), + ("interactive", &[]), ("masks", &[]), ("primitives", &[]), ("scenes", &[("frame comments", 1)]), ("scripts", &[]), - ("shapes", &[("stroke caps and joins other than round (drawn round)", 2)]), + ("shapes", &[]), ( "symbols", &[("advanced colour effects (only alpha kept)", 1), ("instances of missing symbols", 1), ("missing library files", 1), ("reverse loop modes (played forward)", 1)], @@ -80,11 +81,15 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ ("tweens", &[("motion tweens (kept as keyframes)", 1), ("tween spins (turned the shortest way)", 1)]), ]; -/// What each package keeps without running (ADR 0013 tier 1); packages not listed keep -/// nothing. -const KEPT: &[(&str, &[(&str, usize)])] = &[ +/// What each package keeps without running (ADR 0013 tier 1: scripts outside the subset, and +/// class names); packages not listed keep nothing. +const KEPT: &[(&str, &[(&str, usize)])] = &[("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)])]; + +/// The frame scripts each package brings that run (ADR 0013 tier 2: in the subset). +const RUNS: &[(&str, &[(&str, usize)])] = &[ + ("interactive", &[("frame scripts in ActionScript 3.0", 4)]), ("scenes", &[("frame scripts in ActionScript 3.0", 2)]), - ("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 3), ("linkage classes", 1)]), + ("scripts", &[("frame scripts in ActionScript 3.0", 2)]), ]; #[test] @@ -101,6 +106,8 @@ fn each_package_reports_exactly_what_it_uses_that_does_not_come_across() { assert_eq!(report.skipped, want, "{case}"); let kept: BTreeMap = KEPT.iter().find(|(c, _)| c == case).map(|(_, k)| k.iter().map(|(k, n)| (k.to_string(), *n)).collect()).unwrap_or_default(); assert_eq!(report.kept, kept, "{case}: kept, not run"); + let runs: BTreeMap = RUNS.iter().find(|(c, _)| c == case).map(|(_, k)| k.iter().map(|(k, n)| (k.to_string(), *n)).collect()).unwrap_or_default(); + assert_eq!(report.runs, runs, "{case}: frame scripts that run"); assert!(report.notes.is_empty() && report.missing_fonts.is_empty(), "{case}: {report:?}"); } } @@ -138,11 +145,22 @@ fn shapes_rebuild_every_fill_and_stroke() { assert!(shapes[4].stroke.is_some() && shapes[4].fill.is_none()); // The strokes layer: the zigzag split over two edges is one run. let strokes = &doc.timeline(0).layers[0].keyframes[0].elements; - assert_eq!(strokes.len(), 4); + assert_eq!(strokes.len(), 6); let ElementKind::Shape(zig) = &strokes[0].kind else { panic!() }; assert_eq!(zig.path.flatten(&anicraft_geom::Affine::IDENTITY, 0.1).len(), 1, "an edge starting where the last ended continues it"); let ElementKind::Shape(gap) = &strokes[3].kind else { panic!() }; assert_eq!(gap.path.flatten(&anicraft_geom::Affine::IDENTITY, 0.1).len(), 2, "a move away leaves a gap"); + // Caps, joints, the miter limit, dashes and dots come across (ADR 0046). + use anicraft_doc::{Cap, Dash, Join, StrokeStyle}; + let style = |i: usize| match &strokes[i].kind { + ElementKind::Shape(s) => s.stroke.as_ref().map(|st| st.style.clone()).unwrap(), + _ => panic!(), + }; + assert_eq!(style(0), StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 4.0, dash: None }); + assert_eq!(style(1), StrokeStyle { cap: Cap::Square, join: Join::Bevel, miter_limit: 3.0, dash: None }); + assert_eq!(style(2), StrokeStyle::default()); + assert_eq!(style(4), StrokeStyle { cap: Cap::Butt, dash: Dash::dashed(10.0, 5.0), ..StrokeStyle::default() }); + assert_eq!(style(5), StrokeStyle { dash: Dash::dotted(4.0), ..StrokeStyle::default() }); } #[test] @@ -389,3 +407,39 @@ fn hostile_variants_of_every_package_never_panic() { assert!(variants > 1000, "{variants}"); eprintln!("{variants} hostile variants in {:?}", start.elapsed()); } + +#[test] +fn interactive_scripts_run_in_the_player() { + use anicraft_doc::player::{Event, NoScripts, start, step}; + use anicraft_geom::Vec2; + let (doc, report) = import("interactive"); + assert!(report.summary().contains("Runs in Test Movie: 4 frame scripts in ActionScript 3.0."), "{}", report.summary()); + let door = doc.timeline(0).layers[2].keyframes[0].elements[0].id; + // The first frame stops the movie and the door, and adds the listeners. + let s = start(&doc, &mut NoScripts); + assert!(s.output.is_empty(), "{:?}", s.output); + assert_eq!((s.state.root.frame, s.state.root.playing), (0, false)); + assert_eq!(s.state.listeners.values().map(Vec::len).sum::(), 4); + let mut st = step(&doc, &s.state, &[], &mut NoScripts).state; + assert_eq!(st.root.frame, 0, "stopped"); + // Click the door: it opens (its own script traces), and the call outside the movie is + // ignored. + let at = Vec2::new(90.0, 90.0); + let r = step(&doc, &st, &[Event::Move(at), Event::Down(at), Event::Up(at)], &mut NoScripts); + assert_eq!(r.output, ["knock knock", "door open"]); + assert_eq!(r.state.clips.get(&vec![door]).map(|c| (c.frame, c.playing)), Some((2, false))); + st = r.state; + // Over the button the door fades; off it, it comes back; a click goes to "end". + let b = Vec2::new(240.0, 90.0); + let r = step(&doc, &st, &[Event::Move(b)], &mut NoScripts); + assert_eq!(r.state.props.get(&vec![door]).and_then(|o| o.alpha), Some(0.5)); + let r = step(&doc, &r.state, &[Event::Down(b), Event::Up(b)], &mut NoScripts); + assert_eq!(r.output, ["The end: 10"]); + assert_eq!((r.state.root.frame, r.state.root.playing), (9, false)); + let r = step(&doc, &r.state, &[Event::Move(Vec2::new(10.0, 10.0))], &mut NoScripts); + assert_eq!(r.state.props.get(&vec![door]).and_then(|o| o.alpha), Some(1.0)); + // The scripts package: the frame with `if` is kept and doesn't run; the others run. + let (doc, _) = import("scripts"); + let runs: Vec = doc.timeline(0).layers[0].keyframes.iter().filter_map(|k| k.script.as_ref().and_then(|s| s.source())).map(|s| s.runs()).collect(); + assert_eq!(runs, [false, true]); +} diff --git a/crates/xfl/tests/corpus/interactive/DOMDocument.xml b/crates/xfl/tests/corpus/interactive/DOMDocument.xml new file mode 100644 index 00000000..a0e74265 --- /dev/null +++ b/crates/xfl/tests/corpus/interactive/DOMDocument.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/interactive/LIBRARY/Door.xml b/crates/xfl/tests/corpus/interactive/LIBRARY/Door.xml new file mode 100644 index 00000000..2023821e --- /dev/null +++ b/crates/xfl/tests/corpus/interactive/LIBRARY/Door.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/interactive/LIBRARY/Next Button.xml b/crates/xfl/tests/corpus/interactive/LIBRARY/Next Button.xml new file mode 100644 index 00000000..c99889c2 --- /dev/null +++ b/crates/xfl/tests/corpus/interactive/LIBRARY/Next Button.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/crates/xfl/tests/corpus/interactive/golden/frame-000.png b/crates/xfl/tests/corpus/interactive/golden/frame-000.png new file mode 100644 index 00000000..0085bdcb Binary files /dev/null and b/crates/xfl/tests/corpus/interactive/golden/frame-000.png differ diff --git a/crates/xfl/tests/corpus/interactive/golden/frame-009.png b/crates/xfl/tests/corpus/interactive/golden/frame-009.png new file mode 100644 index 00000000..0085bdcb Binary files /dev/null and b/crates/xfl/tests/corpus/interactive/golden/frame-009.png differ diff --git a/crates/xfl/tests/corpus/interactive/interactive.xfl b/crates/xfl/tests/corpus/interactive/interactive.xfl new file mode 100644 index 00000000..860a820e --- /dev/null +++ b/crates/xfl/tests/corpus/interactive/interactive.xfl @@ -0,0 +1 @@ +PROXY-CS5 \ No newline at end of file diff --git a/crates/xfl/tests/corpus/shapes/DOMDocument.xml b/crates/xfl/tests/corpus/shapes/DOMDocument.xml index f427a66b..683cd40e 100644 --- a/crates/xfl/tests/corpus/shapes/DOMDocument.xml +++ b/crates/xfl/tests/corpus/shapes/DOMDocument.xml @@ -2,7 +2,8 @@ + with every cap and join, a stroke continuing across edges and one with a gap, a dashed + and a dotted stroke. --> @@ -33,6 +34,16 @@ + + + + + + + + + + @@ -42,6 +53,9 @@ + + + diff --git a/crates/xfl/tests/corpus/shapes/golden/frame-000.png b/crates/xfl/tests/corpus/shapes/golden/frame-000.png index ff1c170f..bb9209ae 100644 Binary files a/crates/xfl/tests/corpus/shapes/golden/frame-000.png and b/crates/xfl/tests/corpus/shapes/golden/frame-000.png differ diff --git a/docs/accessibility.md b/docs/accessibility.md index ae98c41d..b6cb6ce0 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -121,5 +121,8 @@ cargo test --bin anicraft palette # the contrast checks right-hand panels, timeline, stage). Ctrl+F6 gives the panel order listed above. * **Scroll bars inside lists** have no name (egui doesn't offer one). * **Slider tracks** are dim in high contrast; their handles and number fields are outlined. +* **Names follow the interface language** (ADR 0040): the audit runs the window in the + pseudo-locale too and fails on a name that stayed English. Document text (layer and symbol + names) is announced as written. * **Manual passes with Narrator, VoiceOver and Orca** are still to do on real machines for each platform. The automated audit checks names and roles, not how each reader phrases them. diff --git a/docs/adr/0002-render-pipeline.md b/docs/adr/0002-render-pipeline.md index 70cb4557..946bb13d 100644 --- a/docs/adr/0002-render-pipeline.md +++ b/docs/adr/0002-render-pipeline.md @@ -15,7 +15,7 @@ would freeze for that long on every edit. 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 +2. **Frame cache keyed by content.** `frame_key(state id, frame, view, onion)` (the onion settings' key since ADR 0047), 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 diff --git a/docs/adr/0007-tiled-stage-rendering.md b/docs/adr/0007-tiled-stage-rendering.md index 9424fb82..cd28bfb5 100644 --- a/docs/adr/0007-tiled-stage-rendering.md +++ b/docs/adr/0007-tiled-stage-rendering.md @@ -22,7 +22,7 @@ renderer that draws only the viewport shows this. * 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). + onion settings; ADR 0047). * **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 diff --git a/docs/adr/0013-actionscript.md b/docs/adr/0013-actionscript.md index 97ce71b7..b200b416 100644 --- a/docs/adr/0013-actionscript.md +++ b/docs/adr/0013-actionscript.md @@ -1,7 +1,7 @@ # ADR 0013: ActionScript compatibility * Status: accepted (2026-11-08) as scope and placement. **Tier 1 built** (2026-11-09, see - "Tier 1 as built" below); tier 2 is a later PR (roadmap M6) + "Tier 1 as built" below). **Tier 2 built** (2026-11-10, see "Tier 2 as built") * Relates to: requirements U2 (scripting surface), roadmap M6, ADR 0009 (XFL import), `docs/legal/compliance.md` @@ -163,3 +163,80 @@ Tier 1 follows the decision above. Where the build refines it: the HTML canvas export lists them in its report. * **Not in tier 1:** scripts on instances, linkage on bitmaps and sounds, a document-wide default language, syntax colouring, and exporting scripts back to XFL. + +## Tier 2 as built (2026-11-10) + +Tier 2 follows the decision above. Where the build refines it: + +* **Where the language lives: a module, not a crate.** The parser is `anicraft_actions::as3` + (`lex.rs`, `parse.rs`, `lower.rs`), inside the L0 crate that holds the action IR, rather than + a new `anicraft-script` crate. Two reasons. The layering rule (`src/architecture_tests.rs`) + lets a crate use only *lower* layers, so an L0 `anicraft-script` could not name the L0 IR it + lowers to; ADR 0024 put the IR at L0 for exactly the front ends that lower to it. And a kept + script's compiled form is a pure function of its text, so it is cached on the script itself: + `SourceScript::compiled()` fills a `OnceLock` the first time it is asked (never saved, never + compared, emptied by a clone). The document shares scripts by `Arc`, so undo snapshots, the + render thread, Test Movie, the HTML export and the importer all reuse one compile. A separate + crate would have needed a cache keyed outside the script, or a compile on every frame + entered. The module knows the language and the IR only; the crate stays serde-only. +* **The subset.** `stop()`, `play()`, `gotoAndPlay`/`gotoAndStop` (a frame number, 1-based, or + a label; optionally a scene), `nextFrame()`, `prevFrame()`, `nextScene()`, `prevScene()`; + the same on instance-name paths (`hero_mc.arm_mc.play()`, `this.parent`, `parent`, `root`, + the casts `MovieClip(…)`, `Object(…)` and `… as MovieClip`); `addEventListener` for + `MouseEvent.CLICK`, `MOUSE_DOWN`, `MOUSE_UP`, `ROLL_OVER`/`MOUSE_OVER` and + `ROLL_OUT`/`MOUSE_OUT` (or their strings), with a function declared in the script or written + in place, whose body is made of these calls; `e.currentTarget` in a listener is the instance + listened to; `trace` of literals and of `+ - * / %` over them, joined and formatted as + ActionScript does (`Number.toString`, ECMA-262 §9.8.1); setting `x`, `y`, `alpha`, + `visible`, `rotation`, `scaleX`, `scaleY` to such values; a call to one of the script's own + functions runs its body in place (no recursion; 16 deep at most). `import`, comments, missing + semicolons (insertion as ECMA-262 §7.9), type annotations and `return;` read as the language + does. +* **Never half-run.** Lowering accepts only what the IR says exactly. Anything else (variables, + `if`, loops, reading a property, `removeEventListener`, other events, classes) is a problem + with its line and column, and the whole script doesn't run. The parser reads more of the + language than runs (statements and expressions in general, skipping loop headers and + `switch`/`try` bodies by balanced brackets), so the problem names the construct and where it + is, and lowering lists every problem (up to 32), not just the first. A syntax error stops at + the first. +* **Outside the movie.** `navigateToURL`, `sendToURL`, `fscommand` and `ExternalInterface.call` + are ignored and listed as *notes*; the script still runs. `buttonMode` and `useHandCursor` + are noted too (the pointer is already a hand over everything clickable). +* **Bounds.** 256 KiB of source runs (the 1 MiB kept limit still holds), 65,536 tokens, + nesting 64 deep (statements and expressions; deeper is a problem, never a stack overflow), + 100,000 statements lowered counting inlined copies (calls that fan out), 256 steps per + script and per listener, 64 listeners per script, 32 problems. The player's per-step + budgets (ADR 0024) count each step as one action. A hostile-input test (token soup and raw + bytes, 5,000 scripts) runs in well under a second; it must never panic. Measured (dev + profile, this build's optimised debug): a typical frame script compiles in ~9 µs, a 200 KB + one of 2,500 functions in ~11 ms, once per script. +* **Listeners in the player.** The IR gains no new action: a compiled script is a list of + `ScriptOp`s, each an `Action` or a `Listen` (a target, a `ButtonEvent`, the function's name + and its actions). Running a `Listen` adds the listener to `PlayerState.listeners` under the + instance it names (buttons and movie clips; a graphic, the main timeline or a missing name is + an Output line). Adding the same function for the same event again changes nothing, as in + ActionScript (an inline function counts as one function, so a looping frame doesn't pile up + copies). A listener lives while its instance and its script's timeline stay on the stage. On + an event the instance's own handler (ADR 0024) runs first, then its listeners in the order + added, each on its script's timeline. A movie clip with a listener can be clicked, as one + with handlers can. `nextScene()` in a movie clip's own script writes an Output line instead + of moving the main timeline (a clip has one scene in ActionScript); the Actions panel's Next + scene action keeps its meaning. +* **Where it shows.** Test Movie's Output starts with one line per kept script: "Frame script + runs: Scene 1 › Actions, frame 1", or "not run" with the first problem; the window counts + the scripts that don't run. The Actions panel's Script view says whether the script runs + (and how many steps it lowered to), lists the notes, or lists each problem with its line and + column above the code and marks those lines in the gutter; clicking a problem puts the + cursor there. The XFL import report lists frame scripts that run apart from those kept. + `script.set` and `script.list` say `runs` and `problems`; `script.check {text, language?}` + compiles a text without storing it and returns its steps. The HTML canvas export writes the + same steps for `player.js`, which mirrors the Rust player's listeners (tested step by step in + Boa, state, output and display list alike); scripts outside the subset stay out of the page + and are counted in its report. +* **Messages.** Problems are engine messages, in English like the rest of the engine's + (`docs/localisation.md`); the panel's frame around them is translated. +* **Not in tier 2 yet:** variables and conditions, reading properties, `removeEventListener`, + `Event.ENTER_FRAME` and keyboard events, functions declared on other frames of the timeline, + event bubbling from a clip's children to its listeners, `e.target`, `getChildByName`, + sound and `stage`, and ActionScript 1.0 and 2.0. Each is reported where it is, so the + subset can grow from what users' files actually use. diff --git a/docs/adr/0030-motion-paths.md b/docs/adr/0030-motion-paths.md index d6b73af4..0652c711 100644 --- a/docs/adr/0030-motion-paths.md +++ b/docs/adr/0030-motion-paths.md @@ -1,6 +1,6 @@ # ADR 0030: Motion paths for motion tweens -* Status: accepted (2026-11-09) +* Status: accepted (2026-11-09); §4 between the ends superseded by ADR 0049 (pins) * Relates to: ADR 0016 (motion tweens), ADR 0003 (file format), ADR 0004 (destructive actions), roadmap M2 @@ -88,7 +88,10 @@ and loses nothing irreversible, so it doesn't ask (ADR 0004). * A path's anchors are not tied to frames: an anchor in the middle of the path is reached when the timing says so, not on a frame of its own. Moving the object at a middle frame bends the - path through that point rather than adding an anchor there. + path through that point rather than adding an anchor there. *Since ADR 0049, anchors can be + pinned to frames, and moving the object at a middle frame pins a new anchor there instead; + this timing still applies, leg by leg between pinned anchors, and is unchanged for files + without pins.* * The X/Y values the Motion Editor shows are timing on a path, not the object's place. Editing them retimes the motion along the path. * Performance: evaluating a tween on an 8-segment path with orient takes 10–15 µs per object @@ -96,7 +99,7 @@ and loses nothing irreversible, so it doesn't ask (ADR 0004). measured on the development machine, release and dev profiles). * Adding, deleting and converting path points and moving the whole path came next, in ADR 0038, which also explains why anchors tied to frames wait for a model change. -* Not yet (later PRs): position keys as anchors (spatial keys), copying and pasting +* Not yet (later PRs): ~~position keys as anchors (spatial keys)~~ (done in ADR 0049), copying and pasting a path from a stroke or onto a guide, ease along the path for loop paths, the path shown for tweens inside symbols edited in place, snapping the ends, and importing motion paths from XFL (motion tween import still waits on samples, ADR 0016). diff --git a/docs/adr/0031-merge-drawing.md b/docs/adr/0031-merge-drawing.md index d63eefe7..57441bfc 100644 --- a/docs/adr/0031-merge-drawing.md +++ b/docs/adr/0031-merge-drawing.md @@ -108,11 +108,13 @@ the program; nothing was copied. * Adjacent fills of different colours are separate paths, so antialiasing can show a faint seam where they meet, as in Animate. * Remaining parts of issue #42 (later slices, on this model): - * bending a segment by dragging it with the Selection tool; - * snapping dragged points to points and strokes within 10 screen pixels; - * moving a point to move every shape that shares it (Subselection and arrows); - * a marquee that selects parts of fills and strokes; - * Subselection anchors and handles of connected raw shapes; - * merging the Paint Bucket's fills and pasted raw shapes; - * importing Animate's raw shapes (XFL) as raw shapes; - * gradients and width profiles in the merge. + * ~~bending a segment by dragging it with the Selection tool~~, ~~snapping dragged points + to points and strokes within 10 screen pixels~~ (and keyboard moves within 0.2), ~~moving + a point to move every shape that shares it~~ (with the Selection tool) and ~~a marquee + that selects parts of fills and strokes~~: done in ADR 0041; + * ~~moving shared points with the Subselection tool and its arrows~~ and ~~Subselection + anchors and handles of connected raw shapes~~: done in ADR 0042; + * a marquee that selects across layers (ADR 0041 keeps a selection on one layer); + * ~~merging the Paint Bucket's fills and pasted raw shapes~~ and ~~importing Animate's raw + shapes (XFL) as raw shapes~~: done in ADR 0042; + * ~~gradients~~ (ADR 0042) and width profiles in the merge (ADR 0042 says why profiles wait). diff --git a/docs/adr/0035-xfl-corpus-and-golden-renders.md b/docs/adr/0035-xfl-corpus-and-golden-renders.md index 0d924936..24efc3b5 100644 --- a/docs/adr/0035-xfl-corpus-and-golden-renders.md +++ b/docs/adr/0035-xfl-corpus-and-golden-renders.md @@ -81,7 +81,7 @@ hand from the public descriptions of the format. per-property curves keep the slider's ease and are reported; * reverse loop modes play forward and are reported; * what AniCraft draws the nearest way is now reported instead of silently changed: caps and - joins other than round, gradient and bitmap strokes, repeating and reflecting gradients, + joins other than round (drawn as they are since ADR 0046), gradient and bitmap strokes, repeating and reflecting gradients, focal points, elliptical radial gradients, linear-RGB gradients, and extra tween spins. ## Consequences diff --git a/docs/adr/0038-motion-path-points.md b/docs/adr/0038-motion-path-points.md index 145e9a32..958f2c96 100644 --- a/docs/adr/0038-motion-path-points.md +++ b/docs/adr/0038-motion-path-points.md @@ -1,6 +1,6 @@ # ADR 0038: Editing motion path points and moving the whole path -* Status: accepted (2026-11-09) +* Status: accepted (2026-11-09); anchors tied to frames came in ADR 0049 * Relates to: ADR 0030 (motion paths), ADR 0016 (motion tweens), ADR 0004 (destructive actions), roadmap M2 @@ -97,6 +97,10 @@ the timing model of ADR 0030 cleanly: Until then, moving the object at a frame bends the path through that point (ADR 0030 §4), which covers the common "be here on this frame" case without a new model. +*ADR 0049 does this: pinned anchors with frames, whose X/Y keys hold their place, cutting the +timing into legs. Point edits keep pins on their anchors, deleting a pinned point lets its pin +go, and unpinning brings back this ADR's behaviour.* + ## Consequences * The X/Y keys never change from a point edit, so retiming and path editing stay independent. @@ -111,7 +115,7 @@ which covers the common "be here on this frame" case without a new model. Most of the cost is measuring the path again (`CurveWalk`) and snapshotting the keyframe. * Not yet (later PRs): - * anchors tied to frames (above); + * ~~anchors tied to frames (above)~~ (ADR 0049); * a marquee over motion path anchors; * arrow-key nudging and Free Transform (scale, rotate) of a whole path; * deleting an end by giving the start to the next anchor (with its keys); diff --git a/docs/adr/0040-interface-languages.md b/docs/adr/0040-interface-languages.md new file mode 100644 index 00000000..8e9df82a --- /dev/null +++ b/docs/adr/0040-interface-languages.md @@ -0,0 +1,117 @@ +# ADR 0040: Interface languages (localisation, first slice) + +* Status: accepted (2026-11-10) +* Relates to: ADR 0005 (typography and fonts), ADR 0006 (platforms), ADR 0022 (accessibility), + ADR 0036 (web build); outside PR #38 (ideas credited below) + +## Context + +M8 lists localisation. Artists coming from Animate use it in their own language, and the +Craft family already has a shared translation repository, **storytold/craft-i18n** +(MIT OR Apache-2.0): TSV catalogs keyed by the English text (`contextEnglishtranslation`, +`@plural`, `@id`, `@msg` rows), a `common.tsv` per locale with the strings the apps share +(about 1 200 rows in 50 locales today) and a `.tsv` per app, consumed as an optional build +input (`CRAFT_I18N_DIR`), like craft-fonts. It has **no AniCraft catalog yet**. + +The lookup code the other apps use lives in craft-libs, which is a git dependency; AniCraft +takes dependencies from crates.io only (`deny.toml`). Outside PR #38 built localisation on that +crate and on storytold's egui and winit forks (for Arabic), so it could not be taken as it is, +but its design was sound and several of its ideas are used here. + +egui 0.36 from crates.io lays text out glyph by glyph: there is no Unicode bidirectional +algorithm (UAX #9) and no shaping. Arabic and Hebrew come out in the wrong order and Arabic +letters unjoined; Devanagari, Bengali, Tamil, Thai and Lao need shaping too. Layouts can be +built right to left (`Layout::right_to_left`), but egui's own widgets (menus, checkboxes, +sliders, scroll bars, text editing) have no mirrored mode. Chinese, Japanese, Korean and +Georgian need no shaping, only a font the app doesn't bundle. + +## Decision + +1. **English source text is the key, in our own small layer** (`src/i18n/`, shell only). + Code keeps writing English: `tr!("Save")`, `tr!("Saved {path}", path = p)` (placeholders + filled after the lookup, in one pass), `trn!("{n} frame", "{n} frames", n)` (CLDR plural + rules for whole numbers, `plural.rs`), `trc!("menu", "Open")` (a context word), and + `tr_noop!` to mark strings in tables that are translated where drawn (`i18n::t`). The macros + take literals only, so the extractor sees every key. A missing translation, an unknown + language or a malformed row is the English: the lookup never fails. Nothing below the shell + changes: the command registry, command ids, the `.anicraft` format, the CLI, `serve` and MCP + stay English. Menus are generated from the registry and translate each label when drawn + (`@id ` rows first, then the label's own row), so ids stay stable. + +2. **Catalogs are craft-i18n's, read by our own parser.** We read the craft-i18n format as + specified in its `docs/catalog-format.md` (rows, escapes, placeholders, `@plural` form + counts, `@id`, `language.name`) in under 300 lines with its tests (`catalog.rs`) instead of depending on + craft-libs. build.rs follows craft-i18n's `docs/integration.md`: `CRAFT_I18N_DIR=` + embeds `locales//common.tsv` and `anicraft.tsv` with `include_str!` for every locale + that has AniCraft's own catalog (plus a regional locale's base language, for fallback); + unset, the interface is English; `CRAFT_I18N_REQUIRED=1` makes a missing checkout an error + for releases. Fallback order for `pt-br`: pt-br app → pt-br shared → pt app → pt shared → + English. No catalog files are committed here, and craft-i18n is never a Cargo dependency. + One format means our strings go to craft-i18n without conversion, and every translation the + family already has (its shared catalog) applies to AniCraft as soon as a locale has its + `anicraft.tsv`. + +3. **Which languages are offered.** A locale is offered when it has its own AniCraft catalog + (a locale with only shared strings is a fallback, so the app never offers a language it is + barely translated into, as craft-i18n's integration rule says) **and** is in `i18n::READY`: + left-to-right languages in Latin, Greek or Cyrillic script, which the bundled faces cover and + egui draws correctly. Right-to-left (Arabic, Hebrew, Persian, Urdu, Kurdish, Dhivehi), + shaped scripts (Indic, Thai, Lao) and CJK/Georgian (font) catalogs are embedded but not + offered until the shell can draw them (consequences). + +4. **A pseudo-locale ships instead of a real language** while craft-i18n has no AniCraft + catalog. `--lang pseudo` (and Preferences in debug builds) draws every string accented, + about a third longer and bracketed (`Save` → `[Šàvé ~~]`), with placeholders kept: untranslated + text stands out, truncation loses the `]`, and layouts are tested for German-length text. + It uses only Latin-1 and Latin Extended-A letters, which every bundled face has. + +5. **Choosing the language.** Preferences › Appearance › Language, first row: *System language + (…)*, the default, then each offered language by its own name. A change shows in the same + frame. The system language comes from `platform::system_locale` (the `sys-locale` crate, + MIT OR Apache-2.0: Windows' user locale, macOS' preferred languages, `LC_ALL`/`LC_MESSAGES`/ + `LANG`, the browser's languages on the web) and is matched by full tag, language-script or + language-region, then language (`de-AT` → `de`, `zh-TW` → `zh-hant`). A stored code this + build lacks is kept and follows the system, so a newer build shows it again. + `--lang |auto|pseudo` sets it for one run without saving (screenshots, tests). + +6. **The current language is a global with a per-thread override in tests.** Lookups read an + atomic index (English is a fast path that returns the key without hashing); under + `cfg(test)` `set_language` writes a thread-local instead, so parallel tests (which always + run in English, whatever the machine) never change each other's language. + +7. **Guardrails.** `every_interface_string_goes_through_tr` lexes every shell source file + (`scan.rs`: strings, raw strings, comments, char literals) and fails on a prose literal + outside the macros, unless its context shows it isn't interface text (logs, ids, commands, + comparisons, match patterns) or it is marked `// i18n-exempt: why`. The accessibility audit + runs the whole window in the pseudo-locale and fails on a screen-reader name that wasn't + translated, which also catches strings passed through variables. `scripts/i18n-extract.sh` + writes the template for translators and, with a craft-i18n checkout, the coverage of every + locale and stale rows. + +## Consequences + +* Every interface string in the shell is translatable today, and a translation needs only a + craft-i18n PR: `locales//anicraft.tsv`, then a build with that checkout. +* Text from below the shell stays English in this slice: engine error messages, import + reports, the body of confirmations (their titles and buttons are translated on an exact + match), default document names (`Layer 2`, `Symbol 1`) and plug-in names. `@msg` templates + for engine messages are the next step. +* **Right to left needs upstream work**: text needs bidi and shaping in egui's text layout, and + the widgets a mirrored mode. We don't fork egui (PR #38 used storytold's fork); we follow + upstream and offer RTL languages when egui on crates.io can draw them. CJK and Georgian need + only a font from craft-fonts and a `READY` entry. +* Per frame, a busy window looks up a few hundred strings: about 13 ns each from a catalog and + 16 ns in the pseudo-locale (made once, then cached), and English returns the key without a + lookup (measured on the development machine, Windows 10, in + `lookups_are_cheap_enough_for_every_label_every_frame`): a few microseconds a frame. +* Translated window titles keep their egui ids explicit, so a window keeps its place and state + when the language changes. + +## Credit + +From PR #38 (SoldierPePe): English source text as the key with a safe fallback; command labels +by `@id` then by label; `trn`/`fmt`-style plural and one-pass placeholder helpers; a per-thread +language for tests; `--lang` for one run and a pseudo mode that shows strings that skip +translation; build.rs following craft-i18n's integration rules. Not taken: the git +dependencies, the egui/winit forks and their API moves, the MSRV raise, the Arabic font and +the right-to-left mirroring helpers (they need the forked text layout). diff --git a/docs/adr/0041-selection-tool-on-raw-drawings.md b/docs/adr/0041-selection-tool-on-raw-drawings.md new file mode 100644 index 00000000..8093ca7d --- /dev/null +++ b/docs/adr/0041-selection-tool-on-raw-drawings.md @@ -0,0 +1,132 @@ +# ADR 0041: Selection tool on raw drawings + +* Status: accepted (2026-11-10) +* Relates to: ADR 0031 (merge drawing), ADR 0004 (destructive actions), ADR 0001 (undo + snapshots), issue #42 (sections 1, 2 and 4) + +## Context + +Merge drawing's first slice (ADR 0031) made the shape tools draw raw strokes and fills, stored as +one element per fill region and per stroke run. Clicking selected one of them, but the Selection +tool still treated them as objects: + +* dragging an unselected line moved it; +* a corner could not be pulled; +* nothing snapped; +* a marquee selected whole shapes whose boxes it touched. + +Issue #42, from an Animate user, describes the Animate behaviour: + +* drag a segment away from its ends to curve it; +* drag an endpoint or corner to move it; +* drag a fill to move only that fill; +* points snap to points, strokes and fill edges within 10 screen pixels when moved by the mouse, + and within 0.2 document pixels when moved by the keyboard (anchors meet at their midpoint; a + point snaps onto a line without changing it); +* a marquee selects the parts of fills and strokes under it. + +Behaviour was learned from the issue, Adobe's public help pages and watching the program; nothing +was copied. + +## Decision + +1. **Shared geometry is edited in every copy.** ADR 0031's model stores a shared edge or corner + once in each raw shape that has it. We keep that model and make each edit change all the + copies alike, then merge the shapes again. Pure parts are in `anicraft_geom::raw`: + * `follow` replaces every stretch of a path that runs along an edge (within `SNAP`) with the + same stretch of the bent edge. It splits a longer segment at the edge's ends first. + * `anchors_at` gives a path's anchors at a point. When only an edge passes there (another + shape ends on it), it splits the edge, so the T-junction moves with the point. + + *Rejected:* moving to a planar-map element (edges with fills on either side) now. It would + make sharing automatic, but every command and exporter would have to address parts of an + element (ADR 0031 rejected it for the same reason). The copies approach costs a geometric + match per edit (measured below) and keeps every existing system working. + +2. **Commands for each gesture** (headless, CLI, MCP, plug-ins: namespace `raw` added to the + plug-in policy). + * `path.bend_segment {x, y, dx, dy, id?, cmd?, t?, merge?}` bends a segment so its point at + `t` moves exactly by `(dx, dy)`, ends fixed. This is the least-squares control-point move + `Path::bend_segment` already used for motion paths. On a raw shape, every copy of the edge + follows (the fill under an outline, a neighbouring fill). On an object, only it bends. + * `raw.move_point {x, y, to_x, to_y, points?, snap?, merge?}` moves a corner or end with every + raw shape that shares it. Handles move with their anchors, and straight segments stay + straight. + * `raw.select_rect {x0, y0, x1, y1, add?}` is the marquee (point 4). + * `raw.merge {ids?}` merges shapes again in place, keeping their stacking. + * `raw.hit {x, y}` says what a drag from a point takes. + * `element.translate` takes `snap` and `from`. + + A drag runs its command every frame with `merge: false`, passing on the segment + (`id, cmd, t`) or the `points` the first frame returned. Release runs `raw.merge` on what + changed. The whole drag is one gesture, so one undo step (ADR 0004: undoable, no + confirmation). Scripts call a command once with the default `merge: true`. + +3. **What a Selection-tool drag takes** (`Session::raw_grab`), in this order: + * anything selected: the drag moves the selection; + * an unselected raw corner or end within 6 screen pixels: it moves; + * an unselected raw stroke, or a raw fill's edge, within 3 screen pixels: it bends; + * the inside of a raw fill: it is selected alone and moved (the outline stays); + * an object: it moves, as before. + + A small corner or arc mark by the pointer shows which, like Animate's pointers. + +4. **Snapping.** + * **Mouse:** the target is the nearest anchor within 10 screen pixels, else the nearest point + on a stroke or fill edge (`10 / zoom` document units, so it feels the same at any zoom). + The shapes that move with the point are left out of the targets. A moving selection snaps + its anchor nearest the pointer onto the shapes that do not move. A ring shows where it + snapped. + * **Keyboard:** nudges merge on drop as before. The planar merge now places a vertex at the + midpoint of the distinct segment ends within `SNAP` (0.2), unless one of its points lies + inside a segment, away from its ends. Then the vertex stays on that line and the line is + not changed. + +5. **The marquee cuts provisionally.** `planar::merge_cut` merges with a closed cutter whose + edges divide fills and end stroke runs, but never show. Each piece says whether it is inside. + Raw shapes partly under the rectangle are replaced by their pieces; the inside pieces are + selected, with raw shapes and objects wholly inside. + * In Animate a marquee is only a selection. So the cut records **no undo step** and leaves + a saved document saved. + * The session keeps the document from before the cut. Once the selection lets go of every + inside piece with nothing else changed (a click elsewhere, a new marquee), the cut is + taken back exactly. Saving, undo and redo also take it back first. Selected pieces map to + the shapes they came from. + * The first edit that uses the cut (a move, delete, recolour) records one step from before + the cut, so undo goes straight back to the whole drawing. + * Shift adds a marquee's parts to the selection; parts already selected stay selected when + cut again. + * The marquee only cuts on a keyframe's own frame: inside a tween, an edit would add a key. + + *Rejected:* keeping cuts permanently (seams and ever more fragments after every marquee), and + a lazy "region" selection that every command would have to understand. + +6. ~~**A selection lives on one layer.**~~ Superseded by ADR 0044: the selection is a set of + `(layer, element)` pairs and the marquee works on every visible, unlocked layer, cutting raw + parts per layer. + +## Consequences + +* The Selection tool now bends, pulls corners, snaps and selects parts as #42 describes. Every + gesture is a command and one undo step. +* Measured on 1,320 raw shapes (12 × 12 outlined squares and 12 lines; optimised debug build, + `raw_drag_timings`): + + | Operation | Time | + |---|---| + | Hover test | 0.04 ms | + | Bend frame | 0.14 ms | + | Point frame with snapping | 0.22 ms | + | Snapping selection move frame | 0.29 ms | + | Merge on release | 0.22 ms | + | Marquee cut and take-back | 1.8 ms | + +* The midpoint rule changes where any two ends within 0.2 meet (before, the lower shape's point + won). The move is at most 0.2, and merging again changes nothing (tested). +* Not in this slice: + * ~~selecting across layers~~ (ADR 0044); + * snapping while drawing with the shape tools; + * ~~a Snap to Objects switch~~ (ADR 0042); + * ~~Subselection anchors and handles of connected raw shapes~~ (ADR 0042); + * bending or moving points of raw shapes inside symbols; + * the Free Transform tool's handles on raw parts. diff --git a/docs/adr/0042-subselection-and-merging-everywhere.md b/docs/adr/0042-subselection-and-merging-everywhere.md new file mode 100644 index 00000000..747ceb49 --- /dev/null +++ b/docs/adr/0042-subselection-and-merging-everywhere.md @@ -0,0 +1,160 @@ +# ADR 0042: Subselection on raw drawings, and merging everywhere + +* Status: accepted (2026-11-10) +* Relates to: ADR 0031 (merge drawing), ADR 0041 (Selection tool on raw drawings), ADR 0004 + (destructive actions), ADR 0009 and 0035 (XFL import and its corpus), issue #42 (section 3, + and the rest of section 1) + +## Context + +ADR 0031 made the shape tools draw raw strokes and fills: one element per fill region and per +stroke run, which cut and join where they meet. ADR 0041 taught the Selection tool to bend, +pull corners, snap and select parts. Three things still did not behave as issue #42 describes. + +* **Subselection (A)** treated raw shapes as objects. Clicking a raw side of a rectangle showed + only that side's two points. In Animate, a click shows the anchors of **everything + connected**, and a point drag moves every shape that has the point. +* **Not everything merged.** These came in as objects that never cut or joined the drawing: + * the Paint Bucket's fills; + * pasted raw shapes; + * Animate's own raw shapes (XFL `DOMShape`); + * gradient and bitmap fills. +* **Snapping could not be switched off.** Animate has View > Snapping > Snap to Objects (the + magnet). + +Behaviour was learned from the issue, Adobe's public help pages and watching the program; +nothing was copied. + +## Decision + +1. **Connected means sharing a point.** Two raw shapes are connected when a point of one (an + anchor) lies within `2 × SNAP` (0.4 units) of the other's outline: + * a corner both have; + * an edge two fills share; + * a line ending on an edge. + + `cmds_rawsub::connected` takes that transitively over the active layer's raw shapes. A grid + over their bounds keeps it near linear, and it is bounded (20,000 shapes). + +2. **Anchors are positions, listed once.** ADR 0041 stores a shared corner once in each shape + that has it, so the Subselection tool works in stage positions: + * `Session::raw_points` lists each anchor once, merging copies within `SNAP`; + * it lists each curve handle once, a fill's edge and its outline having the same one; + * a point drag is `raw.move_point` with `with: [[x, y], ..]` for the other selected anchors, + which finds every shape's copy of each. + + Which anchors are selected is view state in the editor (`App::raw_anchors`), as it is for + drawing objects. Positions survive the re-merge a drag ends with: the merge renumbers + elements but moves a point by at most `SNAP`, so the editor keeps each selected anchor on + the nearest point within 0.5 units. + + *Rejected:* addressing anchors as `(element, command)` pairs. Every merge renumbers elements, + so the selection would be lost after every edit. + +3. **Commands for each gesture** (namespace `raw`, already allowed for plug-ins): + * `raw.subselect {x, y, add?}` is the click. It selects the connected raw shapes, and + returns their anchors, handles, and the clicked edge's ends (whose handles show). An + object is selected alone. + * `raw.subselect_rect {x0, y0, x1, y1, add?}` is the marquee, on the **active layer only**. + It selects whole the shapes it touches (raw ones with everything connected to them), and + returns the raw anchors inside it. It never cuts; cutting is the Selection tool's. + * `raw.points {ids?}` lists anchors and handles. + * `raw.move_handle {id, cmd, slot, dx, dy, merge?}` moves a control point. Every raw shape + with that edge follows (`edit_edge`, which `path.bend_segment` now shares; built on + `anicraft_geom::raw::follow`). + + As in ADR 0041, a drag runs its command every frame with `merge: false` and `raw.merge` on + release. The whole drag is one gesture, so one undo step (ADR 0004: undoable, no + confirmation). Arrow keys move the selected anchors 1 screen px (Shift 10) as one step each, + merged where they land, so ends within 0.2 px meet as ADR 0041 describes. + +4. **What a Subselection press takes**, in order: + * a shown handle: the drag bends that curve; + * a shown anchor: it moves, with the other selected anchors (Shift adds to them); + * a raw anchor not shown yet: its shapes show and the anchor moves; + * a raw line or fill: its connected shapes show and **all of them move**, merged on release; + * otherwise, the object behaviour as before. + + Anchors are hollow squares (solid when selected). The handles of the selected anchors' curves, + and of the clicked edge, are lines ending in filled dots. On a drawing object, the + Subselection tool behaves as before. + +5. **Snap to Objects is tool state**, like Object Drawing (ADR 0031): + * it is `ToolStyle.snap_objects`, on by default, toggled by `draw.snap_to_objects`; + * the switch is in View > Snapping, and also a magnet under the tools and a checkbox in the + Selection, Subselection and Free Transform options; + * off, every `snap` parameter does nothing (`ToolStyle::snap_radius`), so the Selection tool + and Subselection, and scripts, stop snapping alike; + * merging still joins points within 0.2 px: that is the drawing model, not snapping. + + There is no default shortcut. Animate's is Ctrl+Shift+/, and the slash's shifted key depends + on the keyboard layout. Users can give it one in Keyboard Shortcuts. + +6. **The Paint Bucket fills raw drawings exactly.** Unless `object` (default: Object Drawing), + the fill is raw and merges **behind** the drawing, so it takes only what is empty. It joins + the fills of its colour it touches, and the lines that bound it stay on top. + * **The area** comes from the planar merge itself. A *probe* fill under everything is + merged with the raw shapes. What is left of the probe is the empty area, divided by every + line and fill edge. The piece under the click is the area, unless it reaches the probe's + border (the area is open). The result is exact: up to the lines' centres, with holes. + * **It is local.** The probe starts as a 128-unit window around the click, with only the + shapes that reach into it. It grows fourfold while the area reaches its border. A shape + wholly outside a window cannot touch an area inside it. + * **Fallback.** When raw shapes do not close the area (drawing objects close it, or a gap + has to be bridged), the rasterized flood fill of before is used, and its result merges the + same way. + * **Recolouring** a raw fill merges it again, so it joins neighbours of its new colour. + +7. **Pasted raw shapes merge where they land** (Paste, Paste in Place), cutting and joining + like a drop (ADR 0031). Objects on the clipboard go on top whole, as before. + +8. **Animate's raw shapes import raw.** In `anicraft-xfl`, a `DOMShape` loose on a frame + (not `isDrawingObject`, not inside a `DOMGroup`) makes shapes with `merge: true`. The + importer is layer L2, below the engine. So when `file.open` imports, the engine merges each + keyframe's raw shapes into one drawing (`merge::merge_document`), across scenes and symbols. + * XFL arrives one shape per style; afterwards there is one element per fill region and per + stroke run, as AniCraft draws. + * Keyframes a tween joins keep their shapes as they came, because tweens pair shapes in + order. + * The corpus renders still match their goldens. A raw outline is one stroke per side, so at + a corner two round caps overlap where one round join was, and their antialiased edges add + up: 47 of the shapes frame's 14,400 pixels are slightly darker. The merged-corpus test + allows that and compares only, never rewriting goldens. + +9. **Gradients and bitmap fills take part in the merge.** A fill's paint is carried into + keyframe space with the shape (`Paint::transformed`), and back into each piece. Each piece + shows its part of the gradient where it was. Fill styles are matched with a thousandth-unit + tolerance (`same_paint`), so a gradient cut in two joins again when the cut goes. + + **Width profiles stay whole, as objects.** A profile runs along the whole stroke (width + points by arc length). Cutting it at crossings, and joining runs again, would need each + piece's length range carried through the planar map, which it does not track. That is a + later change to `planar`. + +## Consequences + +* Measured on 748 raw shapes (12 × 12 outlined, rounded squares and 12 lines; optimised debug + build, `subselection_timings`): + + | Operation | Time | + |---|---| + | Subselection click (63 connected shapes, 122 anchors, 96 handles) | 0.9 ms | + | Listing anchors and handles (every frame) | 0.1 ms | + | Handle drag frame | 0.1 ms | + | Merge on release | 0.2 ms | + | Paint Bucket fill, exact | 0.3 ms (20 ms when the probe took the whole layer) | + | Paint Bucket on an open area (every window, then the raster) | 29–36 ms | + +* Opening an Animate file now gives merge drawing as Animate had it. Its drawings cut and join + as soon as they are edited. +* A Paint Bucket fill in merge drawing lies exactly along its lines. Deleting a line later + joins fills of one colour, as in Animate. +* Not in this slice: + * deleting raw anchors (Delete says so), and adding them; + * Make Smooth and Make Corner on raw anchors; + * smooth handle pairs (a handle moves alone, as on drawing objects); + * width profiles in the merge; + * Subselection inside symbols; + * a default shortcut for Snap to Objects; + * snapping while drawing with the shape tools; + * a marquee across layers (ADR 0041). diff --git a/docs/adr/0043-bones-and-inverse-kinematics.md b/docs/adr/0043-bones-and-inverse-kinematics.md new file mode 100644 index 00000000..105f51ce --- /dev/null +++ b/docs/adr/0043-bones-and-inverse-kinematics.md @@ -0,0 +1,98 @@ +# ADR 0043: Bone tool and inverse kinematics (symbol-instance armatures) + +* Status: accepted (2026-11-10) +* Relates to: roadmap M7 (Bone/IK tool), ADR 0003 (file format), ADR 0004 (destructive + actions), ADR 0016 (motion tweens), ADR 0027 (camera layer: the model for a special layer) + +## Context + +Animate's Bone tool links symbol instances into an **armature** on an armature (pose) layer. +Each bone starts at a joint on one instance and ends in the next; dragging a bone end moves the +chain by inverse kinematics; poses at frames are keyframes of the armature and tween between +them; joints can be limited and bones pinned. Behaviour was learned from Adobe's public help +pages and from observing the program; nothing was copied. The question is how to fit it into a +model where time is a function (`evaluate` is pure), every renderer and export draws a display +list, and every edit is a command. + +## Decision + +1. **Model.** `LayerKind::Armature` marks an armature layer, and `Layer.armature: + Option>` holds its bones (`#[serde(default, skip_serializing_if)]`, so older + files read and write as before). A `Bone` joins a **parent** instance to a **child** + instance: its `head` (the joint) is a point in the parent's local space, its `tail` (the end + a drag pulls) a point in the child's, and `rest` is the child's transform in the parent's + space as it was drawn. The child turns about the joint; an instance is the child of at most + one bone, and the instance no bone ends in is the **root**, which keeps its own transform. + Bones are listed parent first; `Armature::sanitize` (run on load) drops non-finite bones, + repeats, second bones into one instance and cycles, sorts, and caps at 256 bones. +2. **Poses are joint angles on keyframes.** `Keyframe.pose` lists an angle per bone (radians; + 0 is the bone as drawn, measured against its parent, so turning a parent carries its + children). Forward kinematics is `W_child = R_joint(angle) · W_parent · rest`, the rotation + about the joint in the layer's space (so a scaled or flipped parent never shears its child). + Between pose keyframes the angles tween linearly at the span's eased time (the existing + classic tween and `Easing`); the root's transform tweens as any element does. At a keyframe + the pose is exact. +3. **Pure evaluation.** `evaluate_guided` (behind `evaluate_layer_elements`, `evaluate`, + `evaluate_player` and the HTML exporter) places an armature layer's instances by the pose at + the frame. Every export, the GPU stage, onion skins and Test Movie see poses with no change + of their own. Commands also write the posed transforms into the keyframe's elements, so the + file holds what shows. +4. **Inverse kinematics is cyclic coordinate descent** (CCD; L.-C. T. Wang and C. C. Chen, + *A combined optimization method for solving the inverse kinematics problem of mechanical + manipulators*, IEEE Trans. Robotics and Automation 7(4), 1991; C. Welman, *Inverse + Kinematics and Geometric Constraints for Articulated Figure Manipulation*, MSc thesis, Simon + Fraser University, 1993). FABRIK (Aristidou and Lasenby, 2011) converges in fewer sweeps but + moves joint *positions*, so angles must be recovered and limits re-projected after every + step; CCD works on joint angles, which is what a pose stores, so a limit is a clamp per step + and the result is a pose by construction. Each sweep turns the joints from the dragged bone + upward so the effector points at the target; it stops within 0.01 px or when it stops + moving, and a stall (CCD's blind spot: a straight chain whose target lies on its own line) + bends the joints a little, at most four times, keeping the best pose seen. At most 2,048 + sweeps. An unreachable target leaves the chain stretched straight toward it, the root where + it was. Measured from the rest pose: 0.007 ms per solve for 2 bones, 0.065 ms for 10, 4.7 + ms for 64, every target within 0.01 px. A drag starts each solve from the last pose, so it + converges in far fewer sweeps. +5. **Pins.** A pinned bone and the bones it hangs from never turn in a solve, so its end stays + put; a drag stops at the first such bone, and dragging a pinned bone itself is refused. +6. **Commands** (`bone.*`, a document namespace plug-ins may call): `bone.add {from, to, + head?, tail?}` moves both instances to a new armature layer above them (one pose spanning + from their keyframe to the end of the timeline, a classic tween on it) or adds the new one + to an existing armature (in every pose, at angle 0); a new bone's joint defaults to the end + of the bone into `from`, so chains join end to start. `bone.remove` takes a bone and those + below it out of every pose; the instances they moved go to a normal layer of their own, as + they look at the playhead; with the last bone the whole armature does and its layer goes. + It asks first when the armature has more than one pose (undoable tier, ADR 0004). + `bone.set_limits`, `bone.pin`, `bone.pose {bone, angle | rotate_by}` or `{dx, dy}` (moves + the root), `bone.solve {bone, x, y, local?}` (headless IK) and `bone.info`. Pose edits go + through `Session::editable_keyframe_in(KeyEdit::Pose)`: inside a pose tween they key the + frame with the pose it shows, past the layer's end they carry the last pose on. +7. **The armature layer holds only its armature.** Artwork commands are refused there with a + message that says how to pose instead (like the camera layer, ADR 0027); it can't become + another kind of layer, and motion tweens are refused on it (poses tween with classic tweens). +8. **The shell.** The **Bone tool** (M) drags from one symbol instance to another to add a + bone (starting on a bone's end continues the chain from it) and clicks to pick a bone. Bones + draw over the artwork as wedges, widest by the round joint and narrowing to a smaller round + end, in the armature layer's colour (green by default), the picked bone in the selection + colour; they fade with other tools and on locked layers. The **Selection tool** drags a + bone, or an instance a bone moves (the grabbed point follows the pointer), to pose by IK, + and the root instance to move the armature; each drag is one undo step. Properties shows a + **Bone** section: the joint angle at the playhead, Constrain rotation with min and max, Pin, + and Remove Bone; Delete removes the picked bone. The timeline shows the armature layer with + a bone icon. + +## Consequences + +* Nothing that draws needed to change: poses become transforms in the layer evaluation. +* Files without armatures are written exactly as before; a pose on a keyframe of another kind + of layer (pasted frames) is kept and plays no part; an armature on another kind of layer is + dropped on load. +* Colour effects, names and other instance properties of armature members can't be edited on + the armature layer in this slice (set them before rigging, or inside the symbol). + +## Not yet + +* Shape armatures (bones inside a shape, with binding of its points), spring and damping, + joint translation (Animate's X/Y joint constraints), Animate's runtime armatures (poses that + ActionScript drives), the Bind tool, and XFL import of armature layers. +* Editing instance properties of armature members in place; armature layers under masks and + motion guides; an IK drag that keeps pinned bones *below* the dragged one in place. diff --git a/docs/adr/0044-selection-across-layers.md b/docs/adr/0044-selection-across-layers.md new file mode 100644 index 00000000..d72cf259 --- /dev/null +++ b/docs/adr/0044-selection-across-layers.md @@ -0,0 +1,136 @@ +# ADR 0044: Selection across layers + +* Status: accepted (2026-11-10) +* Relates to: ADR 0041 (Selection tool on raw drawings, decision 6), ADR 0042 (Subselection), + ADR 0001 (undo snapshots), ADR 0004 (destructive actions), issue #42 (section 4) + +## Context + +Until now the session's selection was a list of element ids on the active layer. ADR 0041 left +the marquee on one layer: the active layer when it had something under the rectangle, else the +topmost visible, unlocked layer that did. Issue #42 says the Selection tool's marquee selects +"the specific parts of fills and stroke segments that fall under the selection rectangle across +all unlocked layers". In Animate a selection holds elements on several layers: Shift-click adds +from any layer, Select All takes every unlocked layer, and moving, deleting, aligning, copying, +transforming and the Properties panel act on all of them. + +Behaviour was learned from the issue, Adobe's public help pages and watching the program; +nothing was copied. + +## Decision + +1. **The selection is a set of `(layer, element)` pairs at the playhead** + (`anicraft_engine::Selection`, `crates/engine/src/selection.rs`). It keeps selection order + and a hash set for membership, and is saved in every undo snapshot as before. Element ids + stay unique within a document, so commands keep their `ids` params and results; the pairs make + the layer explicit instead of implied by the active layer. + + * `fix_selection` (after every command, undo, redo and frame change) drops pairs whose + element is not on its layer at the playhead, and pairs on a layer that is gone, hidden or + locked, directly or through a folder. **A locked or hidden layer is never selected.** + * The active layer stays a separate thing: the layer the last click, `element.select` or + marquee landed on. A selection may hold items on layers other than the active one. + + *Rejected:* keeping `Vec` and finding each id's layer on demand. It would work + while ids are unique, but every reader would search every layer, and a selection could not + say which copy it means if ids ever repeat (imports, frames pasted with their ids). + +2. **Every command that reads the selection is classified**, and a selection on the active layer + alone runs exactly the code it ran before (`Session::each_layer` calls the body once, + unchanged): + + | How | Commands | + |---|---| + | **Per layer**: the single-layer body runs once for each layer with selected items, top to bottom, with that layer active and the selection narrowed to it | `edit.delete`, `edit.duplicate`, `element.translate` (and nudges), `element.set_transform`, `element.set_alpha`, `element.rename`, `arrange.*` (within each layer), `modify.transform`, rotate and flip (about the combined centre), `modify.remove_transform`, `draw.drop`, `raw.merge` (default ids) | + | **Per layer, where it applies**: a layer where the edit does not apply (no shapes, no movie clips, no text) is left as it was; the command fails only when it applies nowhere | `element.set_fill`, `element.set_stroke`, `element.set_filters`, `element.set_blend`, `element.set_loop`, `stroke.set_profile`, `paint.apply_style`, `text.edit`, `modify.break_apart` | + | **Across** the layers | `align.*` and `align.distribute_*` (bounds of every selected element, each moved on its own layer), the Free Transform box (`selection_bounds`), `edit.copy` and `edit.cut`, `edit.paste*`, `modify.convert_to_symbol`, snapping a move, `symbol.set_kind` (the first selected instance), the Actions panel's selected instance | + | **On the active layer**, as Animate does | the Subselection tool and its marquee (ADR 0042), the Width tool, the Eraser's selected fills, `raw.move_point`, `path.bend_segment`, `raw.merge {ids}` | + + Per-layer runs reuse the single-layer code, so the auto-key rules hold on each layer: inside + a classic tween every selected layer gets a keyframe at the playhead, and a motion tween's + target becomes property keys on its own layer (the session finishes each layer's motion edit + after its run). A per-layer command returns one result: lists joined, counts added, other + values from the first layer, and `layers` naming the layers it ran on. + +3. **Selecting.** + * `element.pick {add: true}` (Shift-click) adds or removes the element under the point on + whichever layer it is, keeping the rest; a plain click on something unselected selects only + it; a click on something selected keeps the selection, so a drag moves it all. The clicked + layer becomes active. + * `element.select {ids, add?, layer?}` takes ids on any visible, unlocked layer (looking on + the active layer first, then top to bottom, or only on `layer`); the active layer becomes + the first id's layer unless it holds some of them. + * A click on a layer's name in the timeline makes it active and selects all of its artwork at + the playhead, as in Animate (`layer.select {layer, select: true}`; nothing on a locked or + hidden layer). Without `select`, `layer.select` only changes the active layer, as before. + * `edit.select_all` takes every visible, unlocked layer's artwork at the playhead (the camera + and armature layers only while active: one holds the camera, the other's instances are posed + by their bones). In a document with one layer nothing changes; with several, Select All now + selects what Animate's does. + +4. **The marquee works on every visible, unlocked layer** (`raw.select_rect`). One display list + finds what each layer has wholly inside the rectangle and which raw shapes it crosses; raw + shapes are then cut per layer (ADR 0041's provisional cut, `planar::merge_cut`), so a cut never + joins artwork of two layers. The cut of all layers is one provisional change: it records no + undo step, a marquee alone leaves a saved document saved, letting go takes back every layer's + cut exactly, and the first edit that uses it records one step from before it. The active layer + stays when the marquee took something there, else the topmost layer it took from becomes + active. Re-merging after a move (`draw.drop`, `raw.merge`) runs per layer. + +5. **Paste keeps each layer.** The clipboard keeps the copied artwork apart by layer (id and + name). Artwork copied from one layer pastes on the active layer, as before. From several: + back on the layers it came from when every one of them is in this scene with the same name + and can be drawn on; otherwise on the active layer and the drawable layers below it in order, + with layers created at the bottom for the rest, named after the copied ones, as Paste Frames + does. Raw shapes merge into each target layer's drawing. + +6. **Convert to Symbol** of a selection on several layers makes one symbol **with those layers + inside it**, named and stacked as they were, registered at the centre of the combined box. The + instance lands on the **topmost** selected layer, where its first selected element was; the + other layers lose what was selected. On one layer it is unchanged (one inner layer, + "Layer 1"). The issue asked which layer the symbol lands on: the topmost, as Animate does. + + *Rejected:* flattening everything onto one inner layer (it loses the stacking between + layers, so masks and overlaps would change how the symbol looks). + +7. **In the editor.** + * Interface text goes through `tr!`/`trn!` (ADR 0040). "6 elements on 4 layers" has two + counts but a template holds one plural: the layers' phrase is its own plural with its + preposition ("on {n} layers"), placed by the outer one ("{n} elements {on_layers}"), so each + language can inflect both and order them. + * Every timeline row whose layer holds selected items shows a small square in the layer's + colour after its name, as in Animate, and screen readers hear "has selected artwork". + * Properties lists the selection from every layer and titles it "6 elements on 4 layers". For + several elements, Position is the combined box's corner (a change moves them all), and + Scale, Rotation, Alpha, Fill and Stroke say "mixed" when the elements differ (the fields + show the first one's; a change applies to all). + * The stage draws every selected element's box (or raw dots) whatever its layer; Free + Transform's box covers them all. + * `doc.info` reports `selection_layers`; plug-ins see the selected ids as before. + +8. **Undo is one step per gesture**, as before: a drag across layers runs `element.translate` + per frame and `draw.drop` on release inside one gesture. + +## Consequences + +* The Selection tool's marquee, Shift-click and Select All select across layers, and every + command that reads the selection has a defined multi-layer behaviour (tested with a selection + on two layers in `selection_tests.rs`, and in `panic_hunt_every_command`, which now also starts + from raw drawings on two layers with a marquee's cut still provisional). +* Select All in a document with several layers takes them all (was: the active layer only). +* Measured on 1,440 raw shapes on 8 layers (optimised debug build, `selection_timings`): + + | Operation | Time | + |---|---| + | Select All | 0.06 ms | + | `fix_selection` (after every command) | 0.05 ms | + | Move frame, every layer | 0.32 ms | + | Snapping move frame, every layer | 0.44 ms | + | Marquee cut and take-back, every layer (461 parts, 202 cut) | 2.5 ms | + +* Not in this slice: + * a marquee or Select All that takes armature instances from layers that are not active; + * Paste in Place across scenes keeping layers by name only (it uses the active layer and the + ones below); + * the plug-in `elements` view of other layers (it shows the active layer, as before); + * "mixed" for every Properties row (filters, blending and looping show the first instance's). diff --git a/docs/adr/0046-stroke-caps-joins-and-dashes.md b/docs/adr/0046-stroke-caps-joins-and-dashes.md new file mode 100644 index 00000000..1ece935c --- /dev/null +++ b/docs/adr/0046-stroke-caps-joins-and-dashes.md @@ -0,0 +1,100 @@ +# ADR 0046: Stroke caps, joins, miter limit and dashes + +* Status: accepted (2026-11-10) +* Relates to: roadmap M7, requirements (Fills and strokes: caps, joins, miter limit, dashes), + ADR 0002 (render pipeline), ADR 0003 (file format), ADR 0018 (variable-width strokes), + ADR 0021 (SVG import), ADR 0031 (merge drawing), ADR 0035 (XFL corpus; supersedes its + "caps and joins other than round" report) + +## Context + +Every AniCraft stroke had round caps and round joins and was solid. Artists coming from Animate +expect Properties › Stroke to offer Cap (None, Round, Square), Join (Miter, Round, Bevel) with +a Miter limit, and a Style (Solid, Dashed, Dotted, Ragged, Stipple, Hatched). SVG files use +`stroke-linecap`, `stroke-linejoin`, `stroke-miterlimit` and `stroke-dasharray`; the SVG and XFL +importers reported all of these as drawn differently. + +## Decision + +1. **Model: a `StrokeStyle` on every `Stroke`** (`anicraft_doc::stroke_style`): `cap`, `join`, + `miter_limit` and an optional `dash`. Its default is what every stroke was before (round, + round, solid; miter limit 3, Animate's default) and is written as nothing + (`#[serde(default, skip_serializing_if)]`), so older files open unchanged and unstyled + strokes are stored byte for byte as before. No format version change. Styles are sanitized on + every way in (files, commands, importers): miter limit in 1..=100, dash lengths finite and in + 0..=10 000, at most 16 entries. +2. **Dashes are a general pattern; dots are their own kind.** `Dash::Dashed { lengths, offset }` + holds SVG's model: on/off lengths starting with a dash (an odd count repeats, as in SVG; no + gap at all means solid), and how far into the pattern each subpath starts. + `Dash::Dotted { spacing }` is Animate's dotted line: round dots one stroke width across, + `spacing` apart edge to edge, drawn as zero-length dashes with round caps whatever the cap + (so they export exactly to SVG, canvas and Lottie). Lengths are in the shape's own units + like the width, so scaling a shape scales its dashes (`Stroke::scaled`), and the pattern + restarts on every subpath, as in SVG. Properties edits the first dash and gap; a longer + imported pattern keeps the rest. +3. **Out of scope: Animate's Ragged, Stipple and Hatched styles.** They are randomised textures + with no open description and no equivalent in SVG, canvas or Lottie. The XFL importer draws + them solid and says so. +4. **Rendering in the CPU oracle: the same positive-pieces stroker, generalised.** A styled + stroke is a set of positively wound polygons filled non-zero (ADR 0002, 0018): a trapezoid + per segment, a join on the outer side of each bend, caps on open ends. Butt caps add nothing; + square caps carry the cross-section half its thickness past the end; round caps are the + existing half discs. Miter joins fill to where the outer edges meet, + `p + (n₀ + n₁) / (1 + n₀·n₁) · w`, when that is within the limit (SVG's definition: the + point's distance over the half-width, `1 / cos(θ/2)` for a turn θ, at most the limit); + otherwise, and for bevel joins, the corner is cut straight across. Dashes cut each subpath by + arc length into open pieces stroked with the caps and joins, so a dash bends round a corner + with the stroke's join. Round, solid strokes keep the existing code paths, pixel for pixel. +5. **Dash lengths are measured along the output lines, scaled like the width** (by the mean + scale of the transform), the same rule the SVG and canvas exports already use for widths. + The exports therefore write `stroke-dasharray` and `setLineDash` exactly as the renderer + draws them; under a non-uniform scale the pattern follows the mean scale, as the width does. + A width profile still varies by position along each whole subpath, so a dash takes the + widths of its place (dashed tapers work). +6. **Patterns finer than a pixel draw solid, faded by their ink.** At small zooms a dash + pattern can repeat many times per pixel; the renderer then draws the line solid at the share + of it that is on (as it already does for strokes thinner than a pixel). Every stroke is cut + into at most 200 000 dashes; past that, the rest of a subpath draws solid. Vector outlines + (exports of width-profiled strokes) always get the exact dashes. +7. **The GPU stage** draws the oracle's prepared polygons (ADR 0019), so styles need nothing of + their own there; the parity scenes include caps, joins, dashes and dotted tapers. +8. **Exports.** SVG writes `stroke-linecap`, `stroke-linejoin`, `stroke-miterlimit` (miter + joins), `stroke-dasharray` and `stroke-dashoffset`; HTML canvas sets `lineCap`, `lineJoin`, + `miterLimit`, `setLineDash` and `lineDashOffset` from a `k` entry written only for styled + strokes; Lottie writes `lc`, `lj`, `ml` and `d` (dash, gap…, offset). Width-profiled + strokes stay filled outlines (ADR 0018), now with their caps, joins and dashes. Default + strokes are written exactly as before. +9. **Imports.** SVG reads the four properties and `stroke-dashoffset`, inherited, from + attributes and inline styles, with SVG's own defaults (butt, miter, limit 4); an invalid + dash list draws solid, as the SVG specification says. XFL reads `caps`, `joints` and + `miterLimit` and the `DashedStroke` (`dash1`, `dash2`) and `DottedStroke` (`dotSpace`) + elements, from public descriptions of the format and our own corpus. +10. **Everything is a command.** `stroke.set_style` sets any of `cap`, `join`, `miter`, + `style` (solid, dashed, dotted), `dash`, `dash_offset`, `dot_spacing` on the selection, + leaving the rest as it was; a new pattern is sized by the stroke (dashes three widths, gaps + two; dots one width apart). The same params work on `element.set_stroke`, the drawing + commands and `paint.ink`; the drawing tools have a current line style (tool options), the + Ink Bottle gives it, and the Eyedropper picks it (dashes scaled as drawn). +11. **Tweens.** Shape tweens blend the miter limit and dash lengths when both ends have the + same kind and count; caps, joins and different kinds hold the start's until the end + keyframe. +12. **Merge drawing** keeps the style on every piece a raw stroke is cut into; equal styles are + one style to the merge, so differently dashed lines stay apart. The dash pattern restarts on + each piece. + +## Consequences + +* Styled strokes cost no more than round ones (measured: 300 curved strokes at 1280×720, + 32 threads, median 2.5 ms uniform round, 2.2 ms square caps with miter joins, 1.8 ms dashed, + 1.9 ms dotted, 2.2 ms dashed taper). +* A dashed raw stroke cut by merge drawing restarts its pattern at each cut, so the dashes can + shift where lines cross. +* Bounds and picking use the stroke's reach, now including miter points (up to the limit) and + square caps; picking treats a dashed line as solid, so clicking a gap still selects it. + +## Not yet + +Ragged, stipple and hatched styles; custom dash patterns of more than one dash and gap in +Properties (they are kept and editable through commands); Animate's stroke Scale (normal, +horizontal, vertical, none) and hairlines; a dash pattern that continues across subpaths; +dashed strokes in XFL export (there is no XFL export yet). diff --git a/docs/adr/0047-onion-skin-and-edit-multiple-frames.md b/docs/adr/0047-onion-skin-and-edit-multiple-frames.md new file mode 100644 index 00000000..b21ccd77 --- /dev/null +++ b/docs/adr/0047-onion-skin-and-edit-multiple-frames.md @@ -0,0 +1,117 @@ +# ADR 0047: Onion skin controls and Edit Multiple Frames + +* Status: accepted (2026-11-10) +* Relates to: ADR 0002 (render pipeline, frame cache), ADR 0007 (tiled stage), ADR 0019/0032 + (GPU stage), ADR 0044 (selection across layers), ADR 0001 (undo), ADR 0040 (interface + languages) + +## Context + +Onion skin was a toggle that drew the two frames before the playhead in red and the two after +in green, under the whole picture, with no ADR. `docs/requirements.md` asks for a before/after +range, tint and outlines (P1). Artists coming from Animate expect its controls: onion markers +on the frame ruler that they drag, Always Show Markers, Anchor Markers, the Onion 2 / Onion 5 / +Onion All presets, outlines, and Edit Multiple Frames to move a whole animation at once. + +Behaviour was learned from Adobe's public help pages on onion skinning and Edit Multiple Frames +and from watching the program; nothing was copied. + +## Decision + +1. **Settings are view state, composition is a pure function.** `anicraft_engine::onion:: + OnionSkin` holds: on/off, Edit Multiple Frames on/off, the markers, tint, past and future + colours, fade by distance, outlines, keyframes only. The shell owns one (`App::onion`), and + passes it with each render job (`FrameJob::onion`, was a `bool`). `onion::compose(doc, scene, + frame, skin, eval)` builds the display list; the document never changes for it (golden rule + 3). Render keys hash the settings (`OnionSkin::key`; nothing when it shows nothing), so the + frame cache keeps every look apart and a second look is a hit: going back to a frame or + undoing to a state already seen draws nothing new. + +2. **Markers.** `Markers::Relative { before, after }` follow the playhead; + `Markers::Anchored { first, last }` stay on their frames. `range(playhead, frames)` always + lies inside the timeline with `first <= last` (a playhead past the end counts as the last + frame). Dragging a marker never crosses the playhead (relative) or the other marker + (anchored). Anchoring keeps the frames shown; un-anchoring keeps their distances from the + playhead, and a marker the playhead has passed lands on it. Onion 2 and Onion 5 are relative + ±2 and ±5; **Onion All** is anchored from frame 1 to `MAX_FRAME`, so it grows with the + timeline. + +3. **Which frames.** Onion skin draws every frame within the markers except the playhead's, + nearest on top, the past one first at each distance. **Locked layers are not onion-skinned**, + as in Animate (it is how artists keep a background out of the way), nor hidden ones. + **Keyframes only** keeps, per layer, the frames where that layer has a keyframe; the keyframe + under the playhead is left out unless it tweens (it would only repeat the playhead's frame). + At most `MAX_EXTRA_FRAMES` (120) extra frames are evaluated, the nearest ones. + +4. **Look.** An onion frame's colour effect is `alpha` × the past or future colour at + `TINT_AMOUNT` (0.8: fills and lines inside it stay apart). With **fade**, alpha falls + linearly from `NEAR_ALPHA` (0.5) next to the playhead to `FAR_ALPHA` (0.12) at the marker; + without, every frame has 0.5. **Tint off** keeps the artwork's own colours (only faded). + **Outlines** draw onion frames as hairlines in their colour and alpha, through the existing + outline-mode path of the renderers (`DisplayItem::outline`), so the CPU oracle and the GPU + stage draw them alike. The default colours are theme tokens (`onion_past` blue and + `onion_future` green, as Animate users know them, brighter in high contrast); the onion menu + changes them, and Reset goes back to the theme's. + +5. **Layering.** Extra frames are **interleaved layer by layer**: each layer's onion frames sit + under that layer's artwork at the playhead and over the layers below. (Before, they went + under the whole picture, so an opaque background layer hid them.) Each evaluated frame is + already back to front; one k-way merge by layer moves every item once. This is safe because + a group's run lies within one layer and both renderers take mask artwork apart from what + they draw. Extra frames are evaluated in parallel. + +6. **Edit Multiple Frames** shows, on every visible, unlocked layer that holds artwork (not + folders, the camera or armatures), every keyframe whose span reaches into the markers, at + full strength, as it looks on its first frame, with the playhead's frame on top on each + layer; onion frames are not drawn meanwhile. Its selection is a list of `FrameItem + { layer, frame (the keyframe's first frame), element }` (element ids are shared between + keyframes, so the frame says which copy), kept in the shell like the frame selection, since + commands get explicit items (`Session::selection` stays the playhead's, ADR 0044). + * `frames.artwork {first, last}` lists what it shows, with stage bounds; + `frames.edit_multiple {first, last, dx, dy, items?}` moves the items given, or all of + them, on each keyframe: one undo step (a drag is one gesture). A motion tween's path and + X/Y keys move with its object (`MotionTween::translate`). Items outside the markers or on + a locked or hidden layer are refused with nothing changed. + * On the stage the Selection and Free Transform tools click, Shift-click, marquee (what lies + wholly inside) and drag across those keyframes; Select All and Deselect All, and the arrow + keys, act on them. The playhead's keyframe is boxed in the selection colour, the others a + step lighter, and a badge on the stage names the frames. + * A new command namespace, `frames`; plug-ins may call it (document edits). + + *Rejected:* a `range` param on `element.translate`. The selection it moves is the + playhead's (pairs of layer and element), and the same id is on several keyframes; it would + need a second kind of selection inside the engine for one command. + +7. **In the editor.** The timeline has Onion Skin (Alt+Shift+O), Edit Multiple Frames and an + onion menu (also on a right-click on the ruler and in View › Onion Skin Options): Onion + Skin, Edit Multiple Frames, Outlines, Keyframes Only; Always Show Markers, Anchor Markers, + Onion 2 / 5 / All; Tint, Fade by Distance, Before and After colours, Reset. The menu stays + open while options change. The markers are brackets on the frame ruler in the past and future + colours, with the frames between them tinted, pinned when anchored; dragging one shows the + change live. Options, preset ranges and colours are saved in the preferences; on/off and + anchored markers last for the session. Screen readers hear the markers as sliders ("Onion + start marker", frame) and the menu by name; all text goes through `tr!`. + +## Consequences + +* Onion skin meets the P1 requirement (range, tint, outlines) and adds Animate's markers, + keyframes only and Edit Multiple Frames. +* Onion frames now show over opaque lower layers (a visible change: the sample's sky no longer + hides them). +* Measured at 1080p through the tiled path (release, 32 threads; `onion_timings`): + + | Scene | Off | ±5 tinted, fading | ±5 outlines | Edit Multiple Frames ±5 | + |---|---|---|---|---| + | Sample (7 items a frame) | 5.9–6.1 ms | 6.0–6.5 ms | 6.5–7.0 ms | 6.0–6.1 ms | + | Stress, 2,000 items a frame (22,000 with ±5) | 7.2–7.9 ms | 16.2–17.2 ms | 34–39 ms | 6.6–7.3 ms | + + Composing the ±5 stress scene takes 3.0–3.3 ms (was 8.3 ms before the merge and parallel + evaluation); a second look at the same 40 tiles is 0.02 ms, all cache hits. Hairline outlines + cost more to rasterize than fills, so outline mode on very heavy scenes is the slow case. +* Not in this slice: + * per-layer onion skin toggles, and onion skin inside a symbol being edited in place; + * Edit Multiple Frames deleting, transforming (scale, rotate), copying or recolouring across + keyframes; it moves only. Raw (merge) shapes moved there are not merged again with what + they land on; + * a marker drag that also scrolls the timeline; + * onion skin in Test Movie and exports (never: it is an editing aid). diff --git a/docs/adr/0049-motion-path-pins.md b/docs/adr/0049-motion-path-pins.md new file mode 100644 index 00000000..040965a7 --- /dev/null +++ b/docs/adr/0049-motion-path-pins.md @@ -0,0 +1,138 @@ +# ADR 0049: Motion path anchors pinned to frames + +* Status: accepted (2026-11-10) +* Relates to: ADR 0030 (motion paths), ADR 0038 (motion path points), ADR 0016 (motion + tweens), ADR 0003 (file format), ADR 0004 (destructive actions), roadmap M2 + +## Context + +ADR 0030 gave motion tweens a path that the object travels by arc length, timed by the X/Y +curves. Only the path's ends were tied to frames: the first and last position keys. A middle +anchor was reached whenever the timing got there, and moving the object at a middle frame bent +the path through that point without adding a key. ADR 0038 left anchors tied to frames out, +because a pinned anchor would compete with the X/Y curves for the timing. + +In Animate, a motion tween's position keyframes *are* the path's anchors. Moving the object at +frame 12 adds an anchor the object passes on frame 12, and the eases set the speed between those +anchors. Artists coming from Animate expect to say "be here on this frame" and have it hold +while they keep editing the path. We learned this from Adobe's public help pages and from +watching the program. Nothing was copied. + +## Decision + +1. **A pin ties an anchor to a frame.** `MotionTween.pins: Vec` + (`crates/doc/src/motion.rs`) lists the anchors between the ends that are pinned, by frame. + Frames and anchors both increase, so a later frame is always on a later anchor. The ends are + always pinned, to the first and last position keys, and they are not stored. A pin's frame + holds X and Y keys with the anchor's place, so the X/Y curves pass through every pinned + anchor and stay a truthful picture of the motion. Anchors that aren't pinned still shape the + path, as in ADR 0038. We chose this over the alternatives below: + * Making every position key an anchor would break older files. Their middle position keys + are timing keys under ADR 0030, and they would have to be turned into anchors, which moves + objects. + * Giving anchors a frame of their own, separate from the keys, would mean two sources of + timing. That is the conflict ADR 0038 described. +2. **Timing goes leg by leg.** The pinned anchors, ends included, cut the span into legs. On each + leg, ADR 0030's rule applies to the stretch of path between its two anchors: + * Position keys inside the leg split it into pieces. + * On each piece, how far along its chord the X/Y curves are (signed) is how far along the + piece's share of the stretch the object is. The shares are the chords' lengths. + * A leg whose chords add up to nothing (a loop) is crossed at an even pace. + + The results: + * the object is **exactly on each pinned anchor on its frame**; + * eases, holds and overshoot work between pins as they did between the ends; + * a straight path still reproduces the X/Y curves exactly, pins or not; + * **with no pins, it is ADR 0030's arithmetic, number for number.** A test compares + evaluation bit for bit with a copy of the old code, over eased, overshooting and middle-key + tweens and a loop. + + `CurveWalk::anchor_distance` gives each anchor's distance along the path. `evaluate` stays + pure. +3. **Pinning and unpinning.** + * `MotionTween::pin(anchor, frame)` writes the anchor's place as the X/Y keys on that frame. + A pin already on that frame, or the same anchor's pin on another frame, gives way (that is + how a pin is retimed). A pin that would break the order is refused, and the refusal names + the pin in the way. + * `pin_here(frame)` pins where the object is. It uses the anchor there, or splits the path at + that point (the curve unchanged), so nothing moves on that frame. + * `unpin(frame)` removes the pin **and its frame's X/Y keys**. The anchor stays and shapes the + path only. Pinning a frame without keys and then unpinning it gives back the same tween, + key for key. So unpinning brings back ADR 0038's behaviour instead of leaving timing keys + where the pin was. + * Removing the X or Y key of a pinned frame unpins it, taking both keys. A pin always has + both. +4. **The path keeps its pins.** + * `set_path` writes each pin's anchor place as its keys. Keys that already hold the place + stay exactly as they are, so editing elsewhere never changes the timing. + * Adding a point moves the later pins' indices up with their anchors. + * Deleting a pinned point lets its pin go, with its keys. `motion.delete_points` reports how + many it unpinned. + * Moving the whole path, splitting a span (pins after the cut move to the second half, + re-indexed onto the cut path) and Straighten keep the meaning. Straighten forgets the pins, + but their keys stay as the straight path's corners. + * A tween without a path of its own shows the straight path through its position keys, and + those keys are pinned to its corners. The first edit that makes the path the tween's own + keeps them pinned when the edited path has as many anchors. A path of another shape is a + new path: only its ends are pinned. +5. **Auto-key pins** (replacing ADR 0030 §4 between the ends). Moving the object on a path at a + frame: + * at a pinned frame (an end or a pin), moves that anchor with its handles, and its keys + follow; + * before the first position key, moves the start (as before); + * between the ends, adds an anchor where the object is, pins it to that frame and moves it: + Animate's "move it on frame 12, it passes there on frame 12"; + * after the last position key, carries the path on in a straight stretch to where the object + was put. The new end is reached on that frame, and the old end stays pinned to its frame. + + Only where the object is off the path (an ease overshooting an end) does the old least-squares + bend remain. A stage drag is one gesture, so it makes one pin and one undo step. Insert + Keyframe (F6) inside a path tween pins where the object is. +6. **The Motion Editor shows X/Y keys as anchor timing.** On X and Y, a pinned frame's key is + drawn larger in the motion colour. A note explains the blue keys, and the hover says which + point a key belongs to. Setting the X or Y key of a pinned frame (dragging it in the graph or + typing the value) moves the anchor, and the stage follows. That holds for the ends too, which + ADR 0030 left inconsistent. The key toggle on a pinned frame says it unpins. +7. **On the stage** (`src/motion_path.rs`): + * Pinned anchors are diamonds, the keyframe mark, with their frame number on a tag beside + them. The other anchors stay squares. + * Selection takes the ends and the pinned anchors (the motion's keyframes). Subselection + takes every anchor. + * Subselection's right-click menu has *Pin to Frame n* (the playhead's frame). It is + disabled, with the reason, outside the motion or out of order. It also has *Unpin from + Frame n*, and for an end, a disabled *Pinned to Frame n* that says why. + * The timeline draws a larger diamond with a hole at pinned frames. + * Properties › Frame shows how many points are pinned, with *Pin Here* or *Unpin* at the + playhead. That is the keyboard and screen-reader route. +8. **Headless.** `motion.pin_point {anchor?, frame?}` pins an anchor to the frame, or, without + `anchor`, pins where the object is. `motion.unpin_point {anchor? | frame?}` unpins. + `motion.info` and every path command's result list `pins` as `{anchor, frame, end, at}`, ends + included, frames counted from the timeline's start. Unpinning is undoable and loses nothing + irreversible, so it doesn't ask (ADR 0004). +9. **File format.** `pins` is additive, `#[serde(default)]`, and not written when it is empty. A + file from before pins has none and evaluates exactly as before. Loading drops pins that + can't hold: out of order, outside the position keys, on an end or a missing anchor, or on a + tween without a path. An older build ignores the field. It still has the pins' X/Y keys, so + it shows the same path with those frames as timing keys (close to the pinned motion, but not + exact). + +## Consequences + +* "Be here on this frame" now holds through later path edits, the way it does in Animate. Bending + a segment, moving other anchors or adding points never moves a pinned frame's place. +* ADR 0030's statement that a middle anchor is reached "when the timing says so" now holds for + unpinned anchors only. ADR 0038's "anchors tied to frames: not in this slice" is this ADR. +* An X or Y key added in the Motion Editor on a path frame that isn't pinned is still a timing + key (ADR 0030). Pinning is a deliberate act: the stage, F6, the menu, Properties or the command. +* Performance, measured with the optimised dev profile on the development machine, on an + 8-segment oriented path: evaluating a frame takes 3.3 µs per object without pins and 4.0 µs + with 7 pins. The stage's 97 frame dots take 9.5 µs and 11.4 µs. Release builds are 6–16% + faster. The cost is the per-call list of live pins and one binary search per pin. +* Not yet (later PRs): + * dragging keys in time in the Motion Editor or on the timeline to retime a pin (re-pinning to + another frame does it today); + * two pins on one anchor (a hold is an ease or a timing key today); + * the pins' frame tags avoiding each other where points crowd; + * pins on loop paths whose start and end meet; + * importing Animate's motion path keyframes from XFL (motion tween import still waits on + samples, ADR 0016). diff --git a/docs/adr/README.md b/docs/adr/README.md new file mode 100644 index 00000000..8a35fed1 --- /dev/null +++ b/docs/adr/README.md @@ -0,0 +1,25 @@ +# Architecture decision records + +One file per decision: `NNNN-short-title.md`, numbered in order. The files in this folder are the +index. + +## Numbers never move + +A pull request keeps the ADR number it was given until it merges or closes, so its author never +has to renumber because another PR merged first. + +* **Taking a number:** use the next number above every ADR in this folder **and** every number in + the table below. Add your number to the table in the same PR (or ask a maintainer to reserve it + for you before you start). +* **Reserved numbers are skipped.** No other PR may use a reserved number, even if a lower number + looks free on `main`. Gaps in the sequence are expected. +* **When a PR merges,** its row leaves the table (the ADR file now holds the number). **When a PR + closes without merging,** its row leaves the table and the number stays unused. +* Maintainers keep this table current for open pull requests from anyone, including outside + contributors whose PR already contains an ADR: that PR's number is reserved as it is. + +## Reserved for open pull requests + +| Number | Pull request | Topic | +|---|---|---| +| 0037 | #38 (outside contribution) | Interface languages | diff --git a/docs/architecture.md b/docs/architecture.md index 81fe1feb..5f1cad2d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -65,7 +65,8 @@ 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, depth, volume, muted, kind (Normal | Guide | Mask | Folder | Camera) +│ ├── name, visible, locked, outline, depth, volume, muted, kind (Normal | Guide | Mask | Folder | Camera | Armature), +│ │ armature?: bones joining symbol instances (armature layer; ADR 0043) │ └── keyframes: [Keyframe] (sorted by start, spans do not overlap) │ ├── start, duration (frames covered by this keyframe) │ ├── elements: [Element] @@ -99,6 +100,13 @@ when they are compatible: tween's first keyframe steer it: placed hints join subpaths, cut both outlines at the hinted points and match the pieces in order by length. +**Armatures** (ADR 0043): on an armature layer, bones join symbol instances (a joint on the +parent, the child turning about it) and each keyframe's `pose` holds joint angles, tweened at +the span's eased time. `evaluate_layer_elements` places the instances by forward kinematics +(`W_child = R_joint(angle) · W_parent · rest`), so every export and the player see poses; +`armature::solve` finds a pose from a dragged bone end by cyclic coordinate descent with joint +limits and pins. + **The camera** (ADR 0027): a scene's top layer may be its camera layer. `evaluate` (every export), `evaluate_player` and `evaluate_scene_camera` draw each top-level layer through `Camera::view(stage, layer.depth)`: the camera's centre at the middle of the output, zoomed @@ -121,7 +129,7 @@ iterations and a bisection fallback, the same model CSS uses. Interactivity is time as a function too (ADR 0013, ADR 0024). Keyframes and button or movie clip instances carry lists of typed actions (`anicraft-actions`) or a frame-script plug-in -entry, or keep a script in another language verbatim (ADR 0013 tier 1: `FrameScript::Source`, which the player skips); nothing in the document changes while a movie plays. `player::step(doc, &state, +entry, or keep a script in another language verbatim (ADR 0013 tier 1: `FrameScript::Source`; ActionScript 3.0 in the timeline subset compiles once, in `anicraft_actions::as3`, to actions and mouse listeners the player runs, tier 2); nothing in the document changes while a movie plays. `player::step(doc, &state, &events, scripts) -> Step` advances a `PlayerState` (the main timeline's scene and playhead, each movie clip instance's playhead by its element-id path, script-set properties, the pointer) by one frame, runs the actions of the frames entered and routes pointer events to @@ -154,7 +162,7 @@ frame changes), and `doc::sound::trigger` turns them into voices for Test Movie. 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 + └─ stroke: polylines ──► stroker (segment quads + joins/caps, dashes; ADR 0046) ──► accumulator coverage ──► fill rule (non-zero / even-odd) ──► paint shader ──► src-over blend (rows of the bbox in parallel with rayon) ``` @@ -241,6 +249,12 @@ Library on the right. The timeline at the bottom has layer rows (eye and lock to grid with keyframe dots, tween spans and a playhead, plus transport controls and fps/time readouts. Theme tokens live in `theme.rs`. +Interface text is English in the code and translated as it is drawn (`src/i18n/`, +[ADR 0040](adr/0040-interface-languages.md), [docs/localisation.md](localisation.md)): `tr!` +looks the English up in the craft-i18n catalogs build.rs embedded, and menus translate the +registry's labels, so nothing below the shell (commands, the CLI, MCP, the file format) sees +another language. + 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. diff --git a/docs/development.md b/docs/development.md index 033dfe33..7c23c65a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -6,7 +6,7 @@ cargo build # app + CLI (debug) cargo run # desktop app with the sample cargo run -- --screenshot shots/now.png # draw ~120 frames, save the window, exit -cargo run -- --open --screenshot x.png # palette|shortcuts|files|confirm|transform|points|pen|frames|span|bucket|sound|tlzoom|tlwide|prefs|licenses|zoom +cargo run -- --open --screenshot x.png # palette|shortcuts|files|confirm|selection|transform|points|pen|frames|span|bucket|sound|tlzoom|tlwide|prefs|licenses|zoom cargo run -- --theme high-contrast --scale 200 --screenshot x.png # a palette and interface scale for one run (not saved) cargo test # every crate cargo clippy --all-targets -- -D warnings diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index 9c2a5a1c..438cdc64 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -50,6 +50,17 @@ cargo deny check advisories # RustSec security advisories (needs ne user's own files: AniCraft ships none in the binary; the sample plug-ins are source under `examples/plugins` (MIT OR Apache-2.0). +### Interface languages (2026-11-10, ADR 0040) + +New crate: `sys-locale` 0.3 (MIT OR Apache-2.0, crates.io), which reads the system's interface +language (on the web through `js-sys`/`web-sys`, already in the tree). No new licence. +Translations are **not** a dependency: they come from storytold/craft-i18n (MIT OR Apache-2.0) +as an optional build input (`CRAFT_I18N_DIR`), embedded at build time like craft-fonts; no +catalog file is committed here. Its catalogs follow a clean-room rule (written from the plain +meaning of the English, never from another product's localisation), which `docs/localisation.md` +repeats for translators. The plural rules are written from the public Unicode CLDR rules +(`ATTRIBUTION.md`). + ### Web build (2026-11-09, ADR 0036) New crates, all MIT OR Apache-2.0, from crates.io: `web-time` (clocks that work in a browser; diff --git a/docs/legal/third-party-inventory.txt b/docs/legal/third-party-inventory.txt index 70af4693..63ed7bd5 100644 --- a/docs/legal/third-party-inventory.txt +++ b/docs/legal/third-party-inventory.txt @@ -3,7 +3,7 @@ All target platforms (Windows, macOS, Linux, Android, wasm). Regenerate when Car Dual-licensed crates appear under each licence they offer; see docs/legal/compliance.md for the licence elected. 0BSD (1): adler2@2.0.1 -Apache-2.0 (313): 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, alsa@0.11.0, android-activity@0.6.1, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-audio@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-plugins@0.1.0, anicraft-render@0.1.0, anicraft-svg@0.1.0, anicraft-text@0.1.0, anicraft-xfl@0.1.0, anicraft-xml@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, cc@1.10.0, cfg-if@1.0.5, cgl@0.3.2, codespan-reporting@0.13.1, color@0.3.3, concurrent-queue@2.5.0, core-foundation@0.9.4, core-foundation-sys@0.8.7, core-graphics@0.23.2, core-graphics-types@0.1.3, coreaudio-rs@0.14.2, cpal@0.18.2, crc32fast@1.5.3, crossbeam-deque@0.8.8, crossbeam-epoch@0.9.21, crossbeam-utils@0.8.23, cursor-icon@1.2.0, dasp_sample@0.11.0, dispatch2@0.3.1, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, gethostname@1.1.0, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, gl_generator@0.14.0, glow@0.17.0, glutin@0.32.3, glutin_egl_sys@0.7.1, glutin_glx_sys@0.6.1, glutin_wgl_sys@0.6.1, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, khronos_api@3.1.0, kurbo@0.13.1, lewton@0.10.2, 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, mach2@0.6.0, 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, nanomp3@0.2.0, nanomp3-core@0.2.0, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-derive@0.4.2, num-traits@0.2.19, num_enum@0.7.6, num_enum_derive@0.7.6, objc2-app-kit@0.3.2, objc2-audio-toolbox@0.3.2, objc2-avf-audio@0.3.2, objc2-core-audio@0.3.2, objc2-core-audio-types@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, ordered-stream@0.2.0, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, pxfm@0.1.30, quick-error@2.0.1, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, renderdoc-sys@1.1.0, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, scoped-tls@1.0.1, scopeguard@1.2.0, self_cell@1.3.0, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, serde_spanned@1.1.3, shlex@2.0.1, signal-hook-registry@1.4.8, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, smallvec@1.16.4, smol_str@0.2.2, spirv@0.4.0+sdk-1.4.341.0, static_assertions@1.1.0, syn@2.0.119, syn@3.0.9, tempfile@3.27.0, thiserror@1.0.69, thiserror@2.0.21, thiserror-impl@1.0.69, thiserror-impl@2.0.21, tinyvec@1.13.3, toml@1.2.1+spec-1.1.0, toml_datetime@1.1.3+spec-1.1.0, toml_edit@0.25.17+spec-1.1.0, toml_parser@1.1.5+spec-1.1.0, ttf-parser@0.25.1, type-map@0.5.1, unicode-general-category@1.1.0, unicode-ident@1.0.27, unicode-segmentation@1.13.3, unicode-width@0.2.2, uuid@1.29.0, vello_common@0.1.0, vello_cpu@0.1.0, version_check@0.9.5, wasip2@1.0.4+wasi-0.2.12, wasm-bindgen@0.2.129, wasm-bindgen-futures@0.4.79, wasm-bindgen-macro@0.2.129, wasm-bindgen-macro-support@0.2.129, wasm-bindgen-shared@0.2.129, wasmi@2.0.0, wasmi_collections@2.0.0, wasmi_core@2.0.0, wasmi_ir@2.0.0, wasmparser@0.228.0, web-sys@0.3.106, web-time@1.1.0, 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 (316): 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, alsa@0.11.0, android-activity@0.6.1, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-actions@0.1.0, anicraft-audio@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-gpu@0.1.0, anicraft-plugins@0.1.0, anicraft-render@0.1.0, anicraft-svg@0.1.0, anicraft-text@0.1.0, anicraft-xfl@0.1.0, anicraft-xml@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, cc@1.10.0, cfg-if@1.0.5, cgl@0.3.2, codespan-reporting@0.13.1, color@0.3.3, concurrent-queue@2.5.0, core-foundation@0.9.4, core-foundation-sys@0.8.7, core-graphics@0.23.2, core-graphics-types@0.1.3, coreaudio-rs@0.14.2, cpal@0.18.2, crc32fast@1.5.3, crossbeam-deque@0.8.8, crossbeam-epoch@0.9.21, crossbeam-utils@0.8.23, cursor-icon@1.2.0, dasp_sample@0.11.0, dispatch2@0.3.1, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, gethostname@1.1.0, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, gl_generator@0.14.0, glow@0.17.0, glutin@0.32.3, glutin_egl_sys@0.7.1, glutin_glx_sys@0.6.1, glutin_wgl_sys@0.6.1, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, khronos_api@3.1.0, kurbo@0.13.1, lewton@0.10.2, 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, mach2@0.6.0, 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, nanomp3@0.2.0, nanomp3-core@0.2.0, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-derive@0.4.2, num-traits@0.2.19, num_enum@0.7.6, num_enum_derive@0.7.6, objc2-app-kit@0.3.2, objc2-audio-toolbox@0.3.2, objc2-avf-audio@0.3.2, objc2-core-audio@0.3.2, objc2-core-audio-types@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, ordered-stream@0.2.0, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, pxfm@0.1.30, quick-error@2.0.1, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, renderdoc-sys@1.1.0, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, scoped-tls@1.0.1, scopeguard@1.2.0, self_cell@1.3.0, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, serde_spanned@1.1.3, shlex@2.0.1, signal-hook-registry@1.4.8, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, smallvec@1.16.4, smol_str@0.2.2, spirv@0.4.0+sdk-1.4.341.0, static_assertions@1.1.0, syn@2.0.119, syn@3.0.9, sys-locale@0.3.2, 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@1.2.1+spec-1.1.0, toml_datetime@1.1.3+spec-1.1.0, toml_edit@0.25.17+spec-1.1.0, toml_parser@1.1.5+spec-1.1.0, ttf-parser@0.25.1, type-map@0.5.1, unicode-general-category@1.1.0, unicode-ident@1.0.27, unicode-segmentation@1.13.3, unicode-width@0.2.2, uuid@1.29.0, vello_common@0.1.0, vello_cpu@0.1.0, version_check@0.9.5, wasip2@1.0.4+wasi-0.2.12, wasm-bindgen@0.2.129, wasm-bindgen-futures@0.4.79, wasm-bindgen-macro@0.2.129, wasm-bindgen-macro-support@0.2.129, wasm-bindgen-shared@0.2.129, wasmi@2.0.0, wasmi_collections@2.0.0, wasmi_core@2.0.0, wasmi_ir@2.0.0, wasmparser@0.228.0, web-sys@0.3.106, web-time@1.1.0, 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 (7): linux-raw-sys@0.12.1, linux-raw-sys@0.4.15, rustix@0.38.44, rustix@1.1.5, wasip2@1.0.4+wasi-0.2.12, wasmparser@0.228.0, wit-bindgen@0.57.1 BSD-2-Clause (3): mach2@0.6.0, zerocopy@0.8.63, zerocopy-derive@0.8.63 BSD-3-Clause (5): moxcms@0.8.1, num_enum@0.7.6, num_enum_derive@0.7.6, ogg@0.8.0, pxfm@0.1.30 @@ -11,7 +11,7 @@ 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 (386): 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, alsa@0.11.0, alsa-sys@0.4.0, android-activity@0.6.1, android-properties@0.2.2, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-audio@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-plugins@0.1.0, anicraft-render@0.1.0, anicraft-svg@0.1.0, anicraft-text@0.1.0, anicraft-xfl@0.1.0, anicraft-xml@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, block2@0.5.1, block2@0.6.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, byteorder@1.5.0, 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, coreaudio-rs@0.14.2, 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, dasp_sample@0.11.0, dispatch@0.2.0, dispatch2@0.3.1, dlib@0.5.3, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, endi@1.1.1, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fax@0.2.7, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, fontdb@0.23.0, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, glow@0.17.0, glutin-winit@0.5.0, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, harfrust@0.12.0, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, kurbo@0.13.1, lewton@0.10.2, 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, mach2@0.6.0, 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, nanomp3@0.2.0, nanomp3-core@0.2.0, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-derive@0.4.2, 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-audio-toolbox@0.3.2, objc2-avf-audio@0.3.2, objc2-core-audio@0.3.2, objc2-core-audio-types@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-encode@4.1.0, objc2-foundation@0.2.2, objc2-foundation@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.2.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, orbclient@0.3.55, ordered-float@5.5.0, ordered-stream@0.2.0, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, phf@0.13.1, phf_generator@0.13.1, phf_macros@0.13.1, phf_shared@0.13.1, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, quick-error@2.0.1, quick-xml@0.41.0, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, redox_syscall@0.4.1, redox_syscall@0.5.18, redox_syscall@0.9.5, renderdoc-sys@1.1.0, rfd@0.17.2, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, same-file@1.0.6, scoped-tls@1.0.1, scopeguard@1.2.0, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, serde_spanned@1.1.3, shlex@2.0.1, signal-hook-registry@1.4.8, simd-adler32@0.3.10, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, slab@0.4.12, smallvec@1.16.4, smithay-client-toolkit@0.19.2, smithay-client-toolkit@0.20.0, smithay-clipboard@0.7.3, smol_str@0.2.2, spin@0.9.9, static_assertions@1.1.0, syn@2.0.119, syn@3.0.9, tempfile@3.27.0, thiserror@1.0.69, 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@1.2.1+spec-1.1.0, toml_datetime@1.1.3+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, 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, wasmi@2.0.0, wasmi_collections@2.0.0, wasmi_core@2.0.0, wasmi_ir@2.0.0, wasmparser@0.228.0, 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, 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, winresource@0.1.34, 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 +MIT (389): 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, alsa@0.11.0, alsa-sys@0.4.0, android-activity@0.6.1, android-properties@0.2.2, android_system_properties@0.1.6, anicraft@0.1.0, anicraft-actions@0.1.0, anicraft-audio@0.1.0, anicraft-doc@0.1.0, anicraft-engine@0.1.0, anicraft-geom@0.1.0, anicraft-gpu@0.1.0, anicraft-plugins@0.1.0, anicraft-render@0.1.0, anicraft-svg@0.1.0, anicraft-text@0.1.0, anicraft-xfl@0.1.0, anicraft-xml@0.1.0, arboard@3.7.0, arrayvec@0.7.8, as-raw-xcb-connection@1.0.1, ash@0.38.0+1.3.281, async-broadcast@0.7.2, async-channel@2.5.0, async-executor@1.14.0, async-io@2.6.0, async-lock@3.4.2, async-process@2.5.0, async-recursion@1.2.0, async-signal@0.2.14, async-task@4.7.1, async-trait@0.1.92, atomic-waker@1.1.2, atspi@0.29.0, atspi-common@0.13.0, atspi-proxies@0.13.0, autocfg@1.5.1, bit-set@0.10.0, bit-vec@0.9.1, bitflags@1.3.2, bitflags@2.13.2, block2@0.5.1, block2@0.6.2, blocking@1.7.0, bumpalo@3.20.3, bytemuck@1.25.2, bytemuck_derive@1.12.1, byteorder@1.5.0, 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, coreaudio-rs@0.14.2, 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, dasp_sample@0.11.0, dispatch@0.2.0, dispatch2@0.3.1, dlib@0.5.3, document-features@0.2.12, downcast-rs@1.2.1, dpi@0.1.2, ecolor@0.36.2, eframe@0.36.2, egui@0.36.2, egui-wgpu@0.36.2, egui-winit@0.36.2, egui_glow@0.36.2, either@1.19.0, emath@0.36.2, endi@1.1.1, enumflags2@0.7.12, enumflags2_derive@0.7.12, epaint@0.36.2, epaint_default_fonts@0.36.2, equivalent@1.0.3, errno@0.3.14, euclid@0.22.14, event-listener@5.4.2, event-listener-strategy@0.5.4, fastrand@2.5.0, fax@0.2.7, fdeflate@0.3.7, fearless_simd@0.4.1, find-msvc-tools@0.1.15, flate2@1.1.10, font-types@0.12.7, fontdb@0.23.0, foreign-types@0.5.0, foreign-types-macros@0.2.4, foreign-types-shared@0.3.1, futures-core@0.3.34, futures-io@0.3.34, futures-lite@2.6.1, futures-macro@0.3.34, futures-task@0.3.34, futures-util@0.3.34, getrandom@0.3.4, getrandom@0.4.3, gif@0.14.2, glow@0.17.0, glutin-winit@0.5.0, gpu-allocator@0.28.0, guillotiere@0.7.0, half@2.7.1, harfrust@0.12.0, hashbrown@0.16.1, hashbrown@0.17.1, hermit-abi@0.5.3, hex@0.4.3, image@0.25.10, indexmap@2.14.2, itertools@0.15.0, itoa@1.0.18, jni@0.22.4, jni-macros@0.22.4, jni-sys@0.3.1, jni-sys@0.4.1, jni-sys-macros@0.4.1, jobserver@0.1.35, js-sys@0.3.106, khronos-egl@6.0.0, kurbo@0.13.1, lewton@0.10.2, 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, mach2@0.6.0, 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, nanomp3@0.2.0, nanomp3-core@0.2.0, ndk@0.9.0, ndk-context@0.1.1, ndk-sys@0.6.0+11769913, nohash-hasher@0.2.0, num-derive@0.4.2, 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-audio-toolbox@0.3.2, objc2-avf-audio@0.3.2, objc2-core-audio@0.3.2, objc2-core-audio-types@0.3.2, objc2-core-foundation@0.3.2, objc2-core-graphics@0.3.2, objc2-encode@4.1.0, objc2-foundation@0.2.2, objc2-foundation@0.3.2, objc2-metal@0.3.2, objc2-quartz-core@0.3.2, objc2-ui-kit@0.2.2, objc2-ui-kit@0.3.2, once_cell@1.21.4, orbclient@0.3.55, ordered-float@5.5.0, ordered-stream@0.2.0, parking@2.2.1, parking_lot@0.12.5, parking_lot_core@0.9.12, peniko@0.6.1, percent-encoding@2.3.2, phf@0.13.1, phf_generator@0.13.1, phf_macros@0.13.1, phf_shared@0.13.1, pin-project@1.1.13, pin-project-internal@1.1.13, pin-project-lite@0.2.17, piper@0.2.5, pkg-config@0.3.34, plain@0.2.3, png@0.17.16, png@0.18.1, polling@3.11.0, pollster@0.4.0, pollster@1.0.1, polycool@0.4.0, portable-atomic@1.15.0, portable-atomic-util@0.2.8, presser@0.3.1, proc-macro-crate@3.5.0, proc-macro2@1.0.107, profiling@1.0.18, quick-error@2.0.1, quick-xml@0.41.0, quote@1.0.47, r-efi@5.3.0, r-efi@6.0.0, range-alloc@0.1.5, raw-window-handle@0.6.2, raw-window-metal@1.1.0, rayon@1.12.0, rayon-core@1.13.0, read-fonts@0.41.0, redox_syscall@0.4.1, redox_syscall@0.5.18, redox_syscall@0.9.5, renderdoc-sys@1.1.0, rfd@0.17.2, rustc-hash@1.1.0, rustc-hash@2.1.3, rustc_version@0.4.1, rustix@0.38.44, rustix@1.1.5, rustversion@1.0.23, same-file@1.0.6, scoped-tls@1.0.1, scopeguard@1.2.0, semver@1.0.28, serde@1.0.229, serde_core@1.0.229, serde_derive@1.0.229, serde_json@1.0.154, serde_repr@0.1.21, serde_spanned@1.1.3, shlex@2.0.1, signal-hook-registry@1.4.8, simd-adler32@0.3.10, simd_cesu8@1.2.0, simdutf8@0.1.5, siphasher@1.0.4, skrifa@0.44.0, slab@0.4.12, smallvec@1.16.4, smithay-client-toolkit@0.19.2, smithay-client-toolkit@0.20.0, smithay-clipboard@0.7.3, smol_str@0.2.2, spin@0.9.9, static_assertions@1.1.0, syn@2.0.119, syn@3.0.9, sys-locale@0.3.2, 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@1.2.1+spec-1.1.0, toml_datetime@1.1.3+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, 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, wasmi@2.0.0, wasmi_collections@2.0.0, wasmi_core@2.0.0, wasmi_ir@2.0.0, wasmparser@0.228.0, 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, 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, winresource@0.1.34, 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 (1): unicode-ident@1.0.27 diff --git a/docs/localisation.md b/docs/localisation.md new file mode 100644 index 00000000..dc658d0b --- /dev/null +++ b/docs/localisation.md @@ -0,0 +1,127 @@ +# Localisation + +AniCraft's interface can be drawn in other languages (ADR 0040). This page is for contributors +who write interface text, translators, and whoever builds a release. + +## What is translated + +Everything the shell draws: menus (labels from the command registry, translated as they are +drawn), panels, the timeline, Properties, tool options, dialogs, tooltips, status messages, +on-stage hints, and the names screen readers announce. + +Not translated, on purpose: your documents (layer, symbol and scene names), command ids and +parameters, the `.anicraft` format, `anicraft-cli`, `serve` and MCP (scripts and agents see +the same English everywhere), log output, and the `--help` text. + +Not yet: engine messages (errors, import reports and the body of confirmations stay English; +their titles and buttons are translated), default names of new layers and symbols, and +plug-in names. + +## Choosing a language + +**Preferences › Appearance › Language.** *System language* (the default) follows the +computer's (the browser's on the web); a language this build has no catalog for falls back to +English. A change shows at once. For one run, without saving: `anicraft --lang de` +(`--lang auto`, `--lang pseudo`). + +Which languages a build offers depends on the catalogs it was built with (below). Today +craft-i18n has no AniCraft catalog yet, so builds offer English, and the **pseudo-locale** +(`--lang pseudo`; listed in Preferences in debug builds) for testing. + +## The pseudo-locale + +Every string accented, about a third longer and in brackets: `Save` → `[Šàvé ~~]`. Use it to +check a change: + +* Text that is still plain English skipped translation. +* A label whose `]` is cut off is truncated: give it room, or let it wrap. +* Layouts must survive text a third longer (German and Finnish run that long). + +```sh +cargo run -- --lang pseudo --screenshot shots/pseudo.png +cargo run -- --lang pseudo --open prefs --screenshot shots/pseudo-prefs.png +``` + +## Writing interface text (contributors) + +Write English in the code, through the macros (`src/i18n/mod.rs`; in scope everywhere): + +| You write | You get | +|---|---| +| `tr!("Save")` | `&'static str` in the interface language | +| `tr!("Saved {path}", path = p)` | `String`; placeholders filled after the lookup | +| `trn!("{n} layer", "{n} layers", count)` | `String`; the plural form for `count` (CLDR rules), `{n}` filled | +| `trc!("menu", "Open")` | a context word, when the same English means two things | +| `tr_noop!("Graphite")` in a table, `i18n::t(x)` where drawn | for `const` tables and functions returning English keys | +| `i18n::t_cmd(spec.id, spec.label)` | a registry command's label | +| `i18n::t(blend.label())` | a lower crate's `&'static str` label | + +Rules: + +* **One sentence, one template.** Never glue translated pieces together; word order differs + between languages. Name placeholders for what they hold (`{name}`, `{frame}`), never `{}`. +* **Counts use `trn!`**, never `if n == 1`. Languages have up to six plural forms. +* **Keys stay English.** Translate at the point of display only; anything compared, stored, + sent to the engine or used as an egui id stays English. +* **Window titles carry their own id** (`egui::Window::new(tr!("…")).id(egui::Id::new("…"))`), + so a window keeps its place when the language changes. +* **Screen-reader names are text too**: `.named(tr!("…"))`. +* Data is not translated: numbers, units, timecode, shortcuts (`platform::shortcut_label`). + +`cargo test` enforces it: `every_interface_string_goes_through_tr` fails on a prose literal +outside the macros (mark one that isn't interface text with `// i18n-exempt: why`), and the +accessibility audit fails on a name that the pseudo-locale didn't reach. + +## Translating (translators) + +Translations live in the Craft family's shared repository, +[storytold/craft-i18n](https://github.com/storytold/craft-i18n) (MIT OR Apache-2.0), in its +format: `locales//anicraft.tsv`, one row per string, `contextEnglishtranslation` +(see its `docs/catalog-format.md`). Strings the apps share are in `locales//common.tsv` +and already apply to AniCraft; AniCraft's catalog adds the rest and may override a shared row. + +To get the list of strings: + +```sh +scripts/i18n-extract.sh # target/i18n/anicraft.tsv: every string +CRAFT_I18N_DIR=/abs/path/craft-i18n scripts/i18n-extract.sh + # also prints how much of AniCraft each locale already covers +CRAFT_I18N_DIR=/abs/path/craft-i18n ANICRAFT_I18N_LOCALE=de scripts/i18n-extract.sh de.tsv + # only the strings German doesn't have yet +``` + +(`scripts/i18n-extract.ps1` on Windows.) Every row is commented out, as craft-i18n's starter +files are: delete the `#` and type the translation after the last TAB. Keep `{placeholders}` +and a trailing `…`. Then open a pull request in craft-i18n. Follow its clean-room rule: write +from the plain meaning of the English, never from another product's translated interface. + +A language is offered once craft-i18n has its `anicraft.tsv` and it is in `i18n::READY` +(left-to-right Latin, Greek and Cyrillic scripts today). + +## Building with translations + +```sh +git clone https://github.com/storytold/craft-i18n ../craft-i18n +CRAFT_I18N_DIR="$PWD/../craft-i18n" cargo build --release # an absolute path +``` + +Without `CRAFT_I18N_DIR` the build is English (and pseudo). `CRAFT_I18N_REQUIRED=1` turns a +missing or empty checkout into a build error, for releases. A row the app can't use (bad +placeholders, wrong number of plural forms, an unknown `@` context) is skipped with a message +on the console, and that string shows in English. + +## Scripts and direction + +egui 0.36 lays text out glyph by glyph, without the Unicode bidirectional algorithm or +shaping. So: + +| Script | Today | +|---|---| +| Latin, Greek, Cyrillic | Offered when a catalog exists. | +| Chinese, Japanese, Korean, Georgian | Draw correctly, but need a font the app doesn't bundle (a craft-fonts face), then a `READY` entry. | +| Arabic, Hebrew, Persian, Urdu, Kurdish, Dhivehi | Not offered: right to left needs bidi and shaping in egui's text layout, and mirrored widgets. We follow upstream egui rather than fork it. | +| Devanagari, Bengali, Tamil, Telugu, Thai, Lao | Not offered: they need shaping. | +| Vietnamese | Not offered yet: needs a check that every fallback face has its letters. | + +Catalogs for these are still embedded (as fallbacks) and pass through the parser, so turning a +language on is one line once the shell can draw it. diff --git a/docs/performance.md b/docs/performance.md index 3e7c7da0..f10e5bb3 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -52,6 +52,25 @@ Timing each step of a frame showed the time was outside the drawing itself: Output is unchanged: the sample's frames and a bitmap document render byte-identical before and after. +**Onion skin ±5 at 1080p (2026-11-10, ADR 0047).** Through the stage's tiled path (40 tiles +of 256 px, one scene evaluation per frame, tiles in parallel), release build, 32 threads, best +of frames 12, 30 and 48: +`cargo test --release -p anicraft-engine onion_timings -- --ignored --nocapture`. + +| Scene | Off | ±5 tinted, fading | ±5 outlines | Keyframes only ±5 | Edit Multiple Frames ±5 | +|---|---|---|---|---|---| +| Sample (7 items a frame; 67 with ±5) | 5.9–6.1 ms | 6.0–6.5 ms | 6.5–7.0 ms | 5.8–6.2 ms | 6.0–6.1 ms | +| Stress 20 × 100 (2,000 items a frame; 22,000 with ±5) | 7.2–7.9 ms | 16.2–17.2 ms | 34–39 ms | 7.5–7.6 ms | 6.6–7.3 ms | + +Composing the stress scene with ±5 (ten extra evaluations, then each layer's onion frames +merged under its own artwork) took 8.3 ms at first: 3.9 ms of it was putting the items in layer +order (an append, then a reorder). One k-way merge by layer, each item moved once, brought that +to 0.85 ms, and evaluating the extra frames in parallel brought the whole to 3.0–3.3 ms. Output +is unchanged (the onion tests compare items and pixels). The settings are part of every tile's +key, so the frame cache keeps working: looking at the same frame again is 40 hits in 0.02 ms, +and other settings are other pictures. Hairline outlines cost more to rasterize than fills, so +outline mode on very heavy scenes is the slow case. + **Crash-recovery autosave (2026-11-09, ADR 0015).** `bench` now runs one autosave the way the app does: an `Autosaver` in a scratch recovery folder. The editing thread only hands over an `Arc` snapshot of the document; the worker serializes and writes atomically (temp file, diff --git a/docs/plugins.md b/docs/plugins.md index 0871d502..de3d8648 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -114,7 +114,7 @@ first). A refused or failed request is an answer, not a trap: the plug-in decide | Request | Result | |---|---| | `{"op":"command","id":"draw.star","params":{…}}` | The command's result (see `anicraft-cli commands` for ids and params). | -| `{"op":"document"}` | `{abi, stage: {width, height, fps, background}, scene, scenes, frame, frames, layer, layers: [{id, name, kind, visible, locked, parent}], selection: [ids]}` | +| `{"op":"document"}` | `{abi, stage: {width, height, fps, background}, scene, scenes, frame, frames, layer, layers: [{id, name, kind, visible, locked, parent}], selection: [ids]}` (the selection on every layer, ADR 0044) | | `{"op":"elements","selected"?:bool,"paths"?:bool}` | The elements on the active layer at the playhead (tweens applied): `{layer, frame, elements: [{id, kind: shape\|symbol\|text, name, selected, transform: [a,b,c,d,e,f], bounds: [x,y,w,h] (stage), alpha, fill, stroke, path (SVG path data, local space, with "paths")}]}` (at most 10,000). | | `{"op":"log","message":"…"}` | `null`; the line goes into the run's report, and the last one explains a failure. | diff --git a/docs/requirements.md b/docs/requirements.md index 626df4b6..e94ae252 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -54,6 +54,7 @@ Priority: **P0** = M0–M2 skeleton must have, **P1** = parity core, **P2** = lo | **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. | +| **Localisation** | Every interface string translatable, keyed by its English text (ADR 0040); catalogs from the Craft family's craft-i18n; a missing translation shows English, never an error. The command registry, CLI, MCP and file format stay English. | | **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`. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 423a4cf9..d705aefe 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,17 +10,18 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---| | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | -| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path`). Not yet: anchors tied to frames (spatial keys, a model change: ADR 0038), a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | -| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. Not yet: bending segments by dragging, snapping, moving shared points together, partial marquee selection, merging bucket fills and pastes, XFL raw shapes, gradients and width profiles in the merge. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing gradient or width-profiled shapes, eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | +| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | +| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: a marquee across several layers, snapping while drawing, width profiles in the merge, deleting or adding raw anchors, smooth handle pairs. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | -| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; nothing runs them (Test Movie says so once; the HTML export reports them). Not yet: running the ActionScript timeline subset (ADR 0013 tier 2), scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | +| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). Not yet: ActionScript variables, conditions, reading properties, `removeEventListener`, enter-frame and keyboard events, functions from other frames, event bubbling, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Reported rather than silently changed: non-round caps and joins, gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; soft masks, per-character positions, text on a path and dashes are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | | Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. Not yet: double-clicking a document in Finder opens it (the app starts, the file doesn't open), AppImage desktop integration, portable mode, store listings, video export inside the Flatpak. | +| Languages | **First slice** (ADR 0040, `docs/localisation.md`): every shell string goes through `tr!`/`trn!` (keyed by its English; placeholders; CLDR plurals for whole numbers), menus translate the registry's labels when drawn (ids, CLI, MCP and the file format stay English), screen-reader names too. Catalogs are craft-i18n's TSV, read by our own parser and embedded from `CRAFT_I18N_DIR` (fallback app → shared → base language → English). Preferences › Appearance › Language (system language by default) and `--lang`. A **pseudo-locale** (`--lang pseudo`: accented, a third longer, bracketed) tests layout; checked by a source guideline test and a pseudo-locale accessibility audit; `scripts/i18n-extract.sh` writes the translators' template and per-locale coverage. Not yet: a real language (craft-i18n has no `anicraft.tsv` yet), engine messages and confirmation bodies (`@msg`), default document names, right to left (needs bidi and shaping in egui upstream), CJK and Georgian (need a font), shaped scripts. | | Accessibility | **First pass** (ADR 0022, `docs/accessibility.md`): AccessKit (via eframe) gives every control a name and role, checked by a headless test that walks the tree in 23 interface states (custom-painted tools, layer rows and toggles, icon buttons, Library rows, every Properties field, the Motion Editor, every dialog; the stage is a named canvas; the status bar a polite live region). **Ctrl+F6 / Ctrl+Shift+F6** move focus between Stage, Timeline, Properties, Library and Tools (rebindable); focused controls keep Enter/Space/arrows while other shortcuts still work; pointer-only surfaces are not Tab stops. **High contrast** palette (Preferences › Theme) from the same roles, text ≥ 7:1, controls and focus ≥ 3:1; both palettes checked by the contrast test (the graphite one now meets AA everywhere). **Interface scale** 75–200 % holds up (stage refits, tools and timeline header scroll, status truncates). Not yet: stage elements and single frames exposed one by one, keyboard menu bar, following the OS contrast setting, manual passes with Narrator, VoiceOver and Orca. | | Stage rendering & build | **Tiled stage** (ADR 0007): 512 px cached tiles, batched per frame with one scene evaluation per frame, look-ahead ring and playback prefetch, scaled older tiles instead of blank areas, pixel-aligned (no seams). **Space-biased build**: debug build 6.9 GB → 1.04 GB, fresh build 44 s, edit rebuild 4–6 s (`docs/development.md`). | | Scale & performance | Pulled forward from M2: persistent document with snapshot undo (memory-budgeted history, save-point dirty tracking, History panel), background render worker with frame cache and playback look-ahead, band-parallel renderer with culling, compact streaming file format v2, `anicraft-cli bench`. Measured numbers are in `docs/performance.md`. Memory, sharing, file-size and culling budgets are a test on every PR; timing budgets are `anicraft-cli bench --check yes` (all met; the 1080p render is 15.3–15.8 ms against 16.7 ms). | @@ -30,14 +31,14 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | M | Theme | Exit criteria | |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | -| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (basic); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | -| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038; spatial keys, 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | +| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | +| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); GPU binning deferred (not the bottleneck as tiles); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); not yet: `.fla` variants of the corpus, sound and video items; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, fallback faces for letters the chosen font lacks, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | -| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts. The full language, the `flash.*` API and SWF bytecode are not planned. | -| **M7** | Advanced animation | Bone/IK tool; ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); localisation; accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | +| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | +| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | +| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. | ## Releases @@ -56,9 +57,9 @@ titled with its milestone. | M3 | GPU stage: filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032) | CPU oracle, tiled stage, GPU stage slices 1–3 | | M4 | Text from Animate files | XFL import, text engine (M5 first slice) | | M5 | Audio layers: import, waveform, playback sync | timeline, layers | -| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); next: command macros, or ActionScript tier 2 | command registry, plug-in host, action IR and player | -| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | -| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | +| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); next: command macros, or growing the ActionScript subset (variables and conditions) | command registry, plug-in host, action IR and player | +| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation | +| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and ActionScript (on M6's plug-in host). @@ -78,11 +79,34 @@ has a key (P is the Pen, as in Animate). Next, in order: +0. **Raw drawing as in Animate (issue #42, a user's detailed report).** Merge drawing's first + slice (ADR 0031, outside contribution #92) makes the shape tools draw raw strokes and fills + that cut and join. Still to match the report, first-party: + * ~~**Selection tool on raw drawings** (ADR 0041)~~ ✅: drag an unselected segment to bend + it; drag an endpoint or corner to move it, moving every shape that shares the point; snap + dragged points to points, strokes and fill edges within 10 screen px, and keyboard moves + within 0.2 document px; a marquee that selects the parts of fills and strokes under it + (cut at its edges); Shift adds. Not yet: snapping while drawing. + * ~~**Selection across layers** (ADR 0044)~~ ✅: a selection is a set of (layer, element) + pairs; the marquee, Shift-click and Select All work across visible, unlocked layers (raw + parts cut and re-merged per layer); move, delete, duplicate, arrange, transforms, colour + effects, filters and break apart act on each layer; align, distribute, Free Transform and + copy act across them; paste keeps each layer; Convert to Symbol keeps the layers inside and + lands on the topmost; the timeline marks layers with selected artwork, and a click on a + layer's name selects its artwork; Properties shows mixed values. Not yet: armature + instances from inactive layers in a marquee, "mixed" on every Properties row. + * ~~**Subselection on raw drawings, and merging everywhere** (ADR 0042)~~ ✅: hollow anchors + on connected raw shapes, handles on curves, point marquee on the active layer, dragging a + segment or fill moves what is connected, arrow keys; Snap to Objects (View › Snapping, the + magnet); the Paint Bucket's fills (exact, up to the lines) and pasted raw shapes merge; + raw shapes from Animate files come in raw; gradients take part in the merge. Not yet: + width profiles in the merge, deleting or adding raw anchors, smooth handle pairs, a + default Snap to Objects shortcut. 1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, ~~shape tweens~~ ✅, ~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), ~~text~~ ✅ (one style per line; per-character styles with the text model), motion tweens, and ~~a larger self-authored corpus checked by render tests~~ ✅ (ADR 0035). -2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅, ~~text, clip paths and masks (onto mask layers)~~ ✅ (ADR 0021). Next for SVG: dashes, soft (luminance) masks, per-character text positions and text on a path. +2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅, ~~text, clip paths and masks (onto mask layers)~~ ✅ (ADR 0021). ~~dashes~~ ✅ (ADR 0046). Next for SVG: soft (luminance) masks, per-character text positions and text on a path. ## Risks diff --git a/docs/ui-guidelines.md b/docs/ui-guidelines.md index 4c14b71a..a6b8a657 100644 --- a/docs/ui-guidelines.md +++ b/docs/ui-guidelines.md @@ -181,6 +181,17 @@ are not used for UI text, because they would change metrics per OS. (`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. +## 8a. Interface languages (ADR 0040, `docs/localisation.md`) + +* Write interface text in English through the macros: `tr!("Save")`, `tr!("Saved {path}", + path = p)`, `trn!("{n} layer", "{n} layers", n)`; `tr_noop!` in tables, `i18n::t` where they + are drawn. Screen-reader names too. +* One sentence is one template with named placeholders; never glue translated pieces. Counts + use `trn!`, never `if n == 1`. +* Keys stay English (ids, stored values, engine params); translate at the point of display. + Translated window titles carry an explicit `.id(..)`. +* Leave room: labels must survive text a third longer. Check with `--lang pseudo`. + ## 9. Checklist for a UI change 1. Uses `theme::text(Type::…)` / `theme::font` / `with_type`, with no raw sizes or families, @@ -192,3 +203,5 @@ are not used for UI text, because they would change metrics per OS. 4. Screenshot checked (`cargo run -- --screenshot shots/now.png`, `--open ` for dialogs), also with `--theme high-contrast` and `--scale 200`. 5. Named for screen readers (section 7a); `cargo test --bin anicraft a11y` passes. +6. Text goes through `tr!` (section 8a); `cargo test --bin anicraft i18n` passes and a + `--lang pseudo` screenshot shows no plain English and no cut-off `]`. diff --git a/scripts/build-web.sh b/scripts/build-web.sh index 619a94eb..1028b5d4 100755 --- a/scripts/build-web.sh +++ b/scripts/build-web.sh @@ -24,10 +24,10 @@ esac # The CLI and the crate must be the same version, or the generated glue doesn't match. WANT="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)" -[ -n "$WANT" ] || { echo "error: Cargo.lock names no wasm-bindgen version" >&2; exit 1; } +[[ -n "$WANT" ]] || { echo "error: Cargo.lock names no wasm-bindgen version" >&2; exit 1; } command -v wasm-bindgen >/dev/null || { echo "error: wasm-bindgen not found: cargo install wasm-bindgen-cli --version $WANT --locked" >&2; exit 1; } HAVE="$(wasm-bindgen --version | awk '{ print $2 }')" -[ "$HAVE" = "$WANT" ] || { echo "error: wasm-bindgen $HAVE found, Cargo.lock needs $WANT: cargo install wasm-bindgen-cli --version $WANT --locked" >&2; exit 1; } +[[ "$HAVE" = "$WANT" ]] || { echo "error: wasm-bindgen $HAVE found, Cargo.lock needs $WANT: cargo install wasm-bindgen-cli --version $WANT --locked" >&2; exit 1; } if command -v rustup >/dev/null && ! rustup target list --installed | grep -qx wasm32-unknown-unknown; then echo "error: the wasm32-unknown-unknown target is missing: rustup target add wasm32-unknown-unknown" >&2 exit 1 @@ -37,7 +37,7 @@ cargo build -p anicraft --bin anicraft --target wasm32-unknown-unknown --profile TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" DIR="$PROFILE" -[ "$PROFILE" = dev ] && DIR=debug +[[ "$PROFILE" = dev ]] && DIR=debug WASM="$TARGET_DIR/wasm32-unknown-unknown/$DIR/anicraft.wasm" OUT="$ROOT/web" rm -rf "$OUT" diff --git a/scripts/i18n-extract.ps1 b/scripts/i18n-extract.ps1 new file mode 100644 index 00000000..b40925d8 --- /dev/null +++ b/scripts/i18n-extract.ps1 @@ -0,0 +1,20 @@ +# Lists every AniCraft interface string for translators (ADR 0040, docs/localisation.md), as a +# craft-i18n catalog template. Same as scripts/i18n-extract.sh: +# +# scripts/i18n-extract.ps1 [out.tsv] # default: target/i18n/anicraft.tsv +# $env:CRAFT_I18N_DIR = 'C:\src\craft-i18n'; scripts/i18n-extract.ps1 # + coverage per locale +# $env:ANICRAFT_I18N_LOCALE = 'de'; scripts/i18n-extract.ps1 de.tsv # only what German lacks +param([string]$Out = '') +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot +if ($Out -eq '') { $Out = Join-Path $root 'target/i18n/anicraft.tsv' } +elseif (-not [System.IO.Path]::IsPathRooted($Out)) { $Out = Join-Path (Get-Location) $Out } +Push-Location $root +try { + $env:ANICRAFT_I18N_OUT = $Out + cargo test --quiet --bin anicraft i18n::tests::extract -- --ignored --exact --nocapture + if ($LASTEXITCODE -ne 0) { throw "extraction failed ($LASTEXITCODE)" } +} finally { + Remove-Item Env:ANICRAFT_I18N_OUT -ErrorAction SilentlyContinue + Pop-Location +} diff --git a/scripts/i18n-extract.sh b/scripts/i18n-extract.sh new file mode 100755 index 00000000..5793a369 --- /dev/null +++ b/scripts/i18n-extract.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Lists every AniCraft interface string for translators (ADR 0040, docs/localisation.md), as a +# craft-i18n catalog template: the header, then one commented-out row per string +# (`#`), for locales//anicraft.tsv in storytold/craft-i18n. +# The strings come from the shell's tr!/trc!/trn!/tr_noop! calls and the command registry's +# labels and menus. +# +# scripts/i18n-extract.sh [out.tsv] # default: target/i18n/anicraft.tsv +# CRAFT_I18N_DIR=/abs/craft-i18n scripts/i18n-extract.sh # also: how much each locale covers +# CRAFT_I18N_DIR=/abs/craft-i18n ANICRAFT_I18N_LOCALE=de scripts/i18n-extract.sh de.tsv +# # only what German is missing +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +OUT="${1:-$ROOT/target/i18n/anicraft.tsv}" +case "$OUT" in + /* | [A-Za-z]:*) ;; + *) OUT="$PWD/$OUT" ;; +esac +ANICRAFT_I18N_OUT="$OUT" cargo test --quiet --bin anicraft i18n::tests::extract -- --ignored --exact --nocapture diff --git a/sonar-project.properties b/sonar-project.properties index 2be8fd01..b0aa5244 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,2 +1,6 @@ sonar.projectKey=storytold_anicraft sonar.organization=storytold + +# CI only publishes the Rust lcov report, so JS, PowerShell and Python never +# appear covered. Same idea as filmcraft and lightcraft excluding tools/docs. +sonar.coverage.exclusions=**/*.js,**/*.ps1,**/*.py diff --git a/src/a11y.rs b/src/a11y.rs index 2b5bd956..15318b84 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -148,13 +148,14 @@ pub enum Region { impl Region { pub const CYCLE: [Region; 5] = [Region::Stage, Region::Timeline, Region::Properties, Region::Library, Region::Tools]; + /// English (a key): translate where it is shown with `crate::i18n::t`. pub fn label(self) -> &'static str { match self { - Region::Stage => "Stage", - Region::Timeline => "Timeline", - Region::Properties => "Properties", - Region::Library => "Library", - Region::Tools => "Tools", + Region::Stage => tr_noop!("Stage"), + Region::Timeline => tr_noop!("Timeline"), + Region::Properties => tr_noop!("Properties"), + Region::Library => tr_noop!("Library"), + Region::Tools => tr_noop!("Tools"), } } @@ -348,10 +349,10 @@ mod tests { fn every_interactive_node_has_a_name_and_a_role() { let mut found = Vec::new(); found.extend(check("default", |_, _| {})); - for tool in [Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { + for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "camera", "cameraview", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/actions_panel.rs b/src/actions_panel.rs index 8ae72684..106087c5 100644 --- a/src/actions_panel.rs +++ b/src/actions_panel.rs @@ -61,34 +61,39 @@ pub fn show(app: &mut App, ctx: &egui::Context) { } let mut open = app.show_actions; let at = ctx.content_rect().right_top() + egui::vec2(-760.0, 96.0); - let shown = egui::Window::new("Actions").id(egui::Id::new("actions_panel")).open(&mut open).default_pos(at).default_width(420.0).resizable(true).collapsible(false).show(ctx, |ui| { + let shown = egui::Window::new(tr!("Actions")).id(egui::Id::new("actions_panel")).open(&mut open).default_pos(at).default_width(420.0).resizable(true).collapsible(false).show(ctx, |ui| { egui::ScrollArea::vertical().max_height(ctx.content_rect().height() * 0.7).auto_shrink([false, true]).show(ui, |ui| panel(app, ui)); }); - crate::a11y::name_title_bar(&shown, "Actions"); + crate::a11y::name_title_bar(&shown, tr!("Actions")); app.show_actions = open; } /// The selected movie clip or button instance on the active layer, if exactly one is selected. fn selected_instance(app: &App) -> Option<(Element, SymbolKind)> { - let [id] = app.s.selection.as_slice() else { return None }; - let e = app.s.visible_elements().into_iter().find(|e| e.id == *id)?; + let sel = app.s.selected_elements(); + let [(_, e)] = sel.as_slice() else { return None }; let ElementKind::Symbol { symbol, .. } = &e.kind else { return None }; let kind = app.s.doc.symbol(*symbol)?.kind; - (kind != SymbolKind::Graphic).then(|| ((*e).clone(), kind)) + (kind != SymbolKind::Graphic).then(|| ((**e).clone(), kind)) } fn panel(app: &mut App, ui: &mut egui::Ui) { let inst = selected_instance(app); ui.horizontal(|ui| { - if ui.selectable_label(app.actions.tab == Tab::Frame, "Frame").on_hover_text("What runs when the playhead enters a keyframe").clicked() { + if ui.selectable_label(app.actions.tab == Tab::Frame, tr!("Frame")).on_hover_text(tr!("What runs when the playhead enters a keyframe")).clicked() { app.actions.tab = Tab::Frame; } let label = match &inst { - Some((e, k)) => format!("{} {}", if *k == SymbolKind::Button { "Button" } else { "Movie clip" }, if e.name.is_empty() { "(unnamed)".to_string() } else { format!("“{}”", e.name) }), - None => "Instance".to_string(), + Some((e, k)) => match (*k == SymbolKind::Button, e.name.is_empty()) { + (true, true) => tr!("Button (unnamed)").to_string(), + (true, false) => tr!("Button “{name}”", name = e.name), + (false, true) => tr!("Movie clip (unnamed)").to_string(), + (false, false) => tr!("Movie clip “{name}”", name = e.name), + }, + None => tr!("Instance").to_string(), }; - let r = ui.add_enabled(inst.is_some(), egui::Button::selectable(app.actions.tab == Tab::Instance, label)).on_hover_text("What the selected button or movie clip does on clicks and the pointer"); - let r = r.on_disabled_hover_text("Select one button or movie clip instance on the stage"); + let r = ui.add_enabled(inst.is_some(), egui::Button::selectable(app.actions.tab == Tab::Instance, label)).on_hover_text(tr!("What the selected button or movie clip does on clicks and the pointer")); + let r = r.on_disabled_hover_text(tr!("Select one button or movie clip instance on the stage")); if r.clicked() { app.actions.tab = Tab::Instance; } @@ -97,7 +102,7 @@ fn panel(app: &mut App, ui: &mut egui::Ui) { match (app.actions.tab, inst) { (Tab::Instance, Some((e, _))) => instance_tab(app, ui, &e), (Tab::Instance, None) => { - ui.label(text(Type::Caption, "Select one button or movie clip instance on the stage to give it events (a graphic can't have them: set its symbol's Type in Properties).")); + ui.label(text(Type::Caption, tr!("Select one button or movie clip instance on the stage to give it events (a graphic can't have them: set its symbol's Type in Properties)."))); } (Tab::Frame, _) => frame_tab(app, ui), } @@ -120,11 +125,6 @@ fn symbol_timelines(doc: &Document) -> Vec<(SymbolId, String, SymbolKind)> { doc.library.iter().filter(|s| s.kind == SymbolKind::MovieClip || keeps_script(&s.timeline)).map(|s| (s.id, s.name.clone(), s.kind)).collect() } -/// Kept scripts in the document (ADR 0013 tier 1), in every scene and symbol. -pub fn kept_scripts(doc: &Document) -> usize { - doc.timelines().flat_map(|tl| tl.layers.iter()).flat_map(|l| l.keyframes.iter()).filter(|k| is_kept(k)).count() -} - /// Whether the document uses scripts at all (a kept script, a linkage class or a document /// class), so the class fields in Properties are worth showing. pub fn scripted(doc: &Document) -> bool { @@ -138,7 +138,7 @@ pub fn class_field(ui: &mut egui::Ui, field: &str, current: &str, name: &str, hi let id = ui.make_persistent_id(field); let mut draft: String = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| current.to_string()); let ok = draft.trim().is_empty() || anicraft_engine::doc::actions::valid_class_name(draft.trim()); - let mut edit = egui::TextEdit::singleline(&mut draft).desired_width(170.0).font(font(Type::Path)).hint_text("none"); + let mut edit = egui::TextEdit::singleline(&mut draft).desired_width(170.0).font(font(Type::Path)).hint_text(tr!("none")); if !ok { edit = edit.text_color(T.error); } @@ -164,36 +164,37 @@ fn is_kept(k: &anicraft_engine::doc::Keyframe) -> bool { matches!(k.script, Some(FrameScript::Source(_))) } -fn kind_name(k: SymbolKind) -> &'static str { +/// A symbol's timeline as the Timeline picker names it: one template per kind. +fn kind_name(name: &str, k: SymbolKind) -> String { match k { - SymbolKind::MovieClip => "movie clip", - SymbolKind::Button => "button", - SymbolKind::Graphic => "graphic", + SymbolKind::MovieClip => tr!("{name} (movie clip)", name = name), + SymbolKind::Button => tr!("{name} (button)", name = name), + SymbolKind::Graphic => tr!("{name} (graphic)", name = name), } } fn frame_tab(app: &mut App, ui: &mut egui::Ui) { let doc = app.s.doc.clone(); - let scene_name = doc.scenes.get(app.s.scene).map_or_else(|| "Scene".to_string(), |s| s.name.clone()); + let scene_name = doc.scenes.get(app.s.scene).map_or_else(|| tr!("Scene").to_string(), |s| s.name.clone()); // Which timeline: the scene being edited, or a symbol's. let symbols = symbol_timelines(&doc); if app.actions.symbol.is_some_and(|id| !symbols.iter().any(|(c, _, _)| *c == id)) { app.actions.symbol = None; } - let current = app.actions.symbol.and_then(|id| symbols.iter().find(|(c, _, _)| *c == id)).map_or(scene_name.clone(), |(_, n, k)| format!("{n} ({})", kind_name(*k))); - form_row(ui, FORM_LABEL_DOCK, "Timeline", |ui| { + let current = app.actions.symbol.and_then(|id| symbols.iter().find(|(c, _, _)| *c == id)).map_or(scene_name.clone(), |(_, n, k)| kind_name(n, *k)); + form_row(ui, FORM_LABEL_DOCK, tr!("Timeline"), |ui| { egui::ComboBox::from_id_salt("act_timeline").width(220.0).selected_text(current).show_ui(ui, |ui| { - if ui.selectable_label(app.actions.symbol.is_none(), format!("{scene_name} (main timeline)")).clicked() { + if ui.selectable_label(app.actions.symbol.is_none(), tr!("{name} (main timeline)", name = scene_name)).clicked() { app.actions.symbol = None; } for (id, n, k) in &symbols { - if ui.selectable_label(app.actions.symbol == Some(*id), format!("{n} ({})", kind_name(*k))).clicked() { + if ui.selectable_label(app.actions.symbol == Some(*id), kind_name(n, *k)).clicked() { app.actions = State { tab: Tab::Frame, symbol: Some(*id), ..State::default() }; } } }) .response - .set_name("Timeline"); + .set_name(tr!("Timeline")); }); let Some(t) = frame_target(app, ui, &doc) else { return }; let source = t.script.as_ref().and_then(FrameScript::source).cloned(); @@ -205,16 +206,16 @@ fn frame_tab(app: &mut App, ui: &mut egui::Ui) { }; if !t.runs { // Graphics, buttons and guides never run frame scripts; a kept one is still shown. - ui.label(text(Type::Caption, "Frames here don't run (graphic and button timelines, guide layers); the script is kept with the document.")); + ui.label(text(Type::Caption, tr!("Frames here don't run (graphic and button timelines, guide layers); the script is kept with the document."))); script_view(app, ui, &t, source.as_ref()); return; } let mut to = None; - form_row(ui, FORM_LABEL_DOCK, "Type", |ui| { + form_row(ui, FORM_LABEL_DOCK, tr!("Type"), |ui| { for (k, label, hint) in [ - (Holds::Actions, "Actions", "A list of actions, in order"), - (Holds::Plugin, "Plug-in", "An entry point of a frame-script plug-in (WebAssembly)"), - (Holds::Script, "Script", "Code in a scripting language (such as an Animate document's ActionScript), kept with the document. It doesn't run yet"), + (Holds::Actions, tr!("Actions"), tr!("A list of actions, in order")), + (Holds::Plugin, tr!("Plug-in"), tr!("An entry point of a frame-script plug-in (WebAssembly)")), + (Holds::Script, tr!("Script"), tr!("Code in a scripting language (such as an Animate document's ActionScript), kept with the document. ActionScript 3.0 runs when it uses only timeline control, mouse listeners, trace and instance properties")), ] { if ui.selectable_label(kind == k, label).on_hover_text(hint).clicked() && kind != k { to = Some(k); @@ -232,12 +233,12 @@ fn frame_tab(app: &mut App, ui: &mut egui::Ui) { let list = t.script.as_ref().map(|s| s.actions().to_vec()).unwrap_or_default(); let cx = Choices::new(&doc, &t.timeline, t.main); if list.is_empty() { - ui.label(text(Type::Caption, "No actions yet. Add one: Stop on a frame holds the movie there; a button's Click can then go on.")); + ui.label(text(Type::Caption, tr!("No actions yet. Add one: Stop on a frame holds the movie there; a button's Click can then go on."))); } if let Some((new, live)) = edit_list(ui, "frame", &list, &cx) { let mut p = t.base.clone(); p["actions"] = serde_json::to_value(&new).unwrap_or(Value::Null); - run(app, live, "Edit actions", "actions.set", p); + run(app, live, tr_noop!("Edit actions"), "actions.set", p); } } } @@ -260,9 +261,9 @@ fn switch_kind(app: &mut App, t: &FrameTarget, from: Holds, to: Holds) { Holds::Plugin => { if let Some((id, entry)) = frame_scripts(app).first().map(|(id, _, e)| (id.clone(), e.first().cloned().unwrap_or_else(|| "main".into()))) { set_frame(app, &t.base, json!({"plugin": id, "entry": entry})); - app.status_ok("Frame script set — Ctrl+Z to undo"); + app.status_ok(tr!("Frame script set — {undo} to undo", undo = app.undo_key())); } else { - app.status_err("No frame-script plug-ins are installed (Commands › Install Plug-in…)"); + app.status_err(tr!("No frame-script plug-ins are installed (Commands › Install Plug-in…)")); } return; } @@ -275,38 +276,95 @@ fn switch_kind(app: &mut App, t: &FrameTarget, from: Holds, to: Holds) { } } if had { - let what = match from { - Holds::Actions => "the actions", - Holds::Plugin => "the plug-in frame script", - Holds::Script => "the script", + let removed = match from { + Holds::Actions => tr!("Removed the actions — {undo} to undo", undo = app.undo_key()), + Holds::Plugin => tr!("Removed the plug-in frame script — {undo} to undo", undo = app.undo_key()), + Holds::Script => tr!("Removed the script — {undo} to undo", undo = app.undo_key()), }; - app.status_ok(format!("Removed {what} — Ctrl+Z to undo")); + app.status_ok(removed); } } /// Space above the first line of the script editor (and its line numbers). const EDITOR_MARGIN: i8 = 4; +/// The character index of a 1-based line and column in `text` (lines split at `\n`). +fn char_index(text: &str, line: u32, column: u32) -> usize { + let mut index = 0; + for (i, l) in text.split('\n').enumerate() { + if i + 1 == line as usize { + return index + (column.max(1) as usize - 1).min(l.chars().count()); + } + index += l.chars().count() + 1; + } + index +} + +/// Under the editor: whether the script runs (ADR 0013 tier 2), what in it is ignored, and +/// each problem that keeps it from running, where it is. Clicking a problem puts the cursor +/// there. +fn script_status(ui: &mut egui::Ui, src: &SourceScript, text_shown: &str, editor: egui::Id) { + let row = |ui: &mut egui::Ui, p: &anicraft_engine::doc::actions::as3::Problem, color: egui::Color32| { + // The engine marks code with backticks (for the CLI and agents); here it reads plainly. + let message = p.message.replace('`', ""); + let label = match p.pos() { + Some(at) => tr!("Line {line}, column {column}: {message}", line = at.line, column = at.column, message = message.as_str()), + None => message, + }; + let r = ui.add(egui::Label::new(text(Type::Caption, label).color(color)).sense(egui::Sense::click()).wrap()); + if let Some(at) = p.pos() + && r.on_hover_text(tr!("Show this line in the script")).clicked() + { + let i = char_index(text_shown, at.line, at.column); + if let Some(mut st) = egui::text_edit::TextEditState::load(ui.ctx(), editor) { + st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(i)))); + st.store(ui.ctx(), editor); + } + ui.ctx().memory_mut(|m| m.request_focus(editor)); + } + }; + match src.compiled() { + Ok(c) => { + ui.horizontal(|ui| { + ui.label(text(Type::Body, tr!("Runs in Test Movie and the HTML canvas export")).color(T.ok)); + ui.label(text(Type::Data, trn!("{n} step", "{n} steps", c.ops.len())).color(T.text_dim)); + }); + for n in &c.notes { + row(ui, n, T.text_dim); + } + } + Err(problems) => { + ui.label(text(Type::Body, trn!("Doesn't run: {n} problem", "Doesn't run: {n} problems", problems.len())).color(T.error)); + // A few rows tall, so the code stays in view however many there are. + egui::ScrollArea::vertical().id_salt("act_script_problems").max_height(96.0).auto_shrink([false, true]).show(ui, |ui| { + for p in problems { + row(ui, p, T.error); + } + }); + } + } +} + /// The Script view: the kept script's language, and its text in a monospace editor with line -/// numbers. Typing edits the document live (`script.set`, one undo step per burst of typing). +/// numbers; under it, whether it runs and what keeps it from running. Typing edits the +/// document live (`script.set`, one undo step per burst of typing). fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&SourceScript>) { let language = src.map_or(Language::default(), |s| s.language); let mut pick = None; - form_row(ui, FORM_LABEL_DOCK, "Language", |ui| { + form_row(ui, FORM_LABEL_DOCK, tr!("Language"), |ui| { ui.add_enabled_ui(src.is_some(), |ui| { - egui::ComboBox::from_id_salt("act_language").width(180.0).selected_text(language.label()).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("act_language").width(180.0).selected_text(crate::i18n::t(language.label())).show_ui(ui, |ui| { for l in Language::ALL { - if ui.selectable_label(l == language, l.label()).clicked() && l != language { + if ui.selectable_label(l == language, crate::i18n::t(l.label())).clicked() && l != language { pick = Some(l); } } }) .response - .set_name("Script language"); + .set_name(tr!("Script language")); }); if let Some(s) = src { - let n = s.lines(); - ui.label(text(Type::Data, format!("{n} {}", if n == 1 { "line" } else { "lines" })).color(T.text_dim)); + ui.label(text(Type::Data, trn!("{n} line", "{n} lines", s.lines())).color(T.text_dim)); } }); if let Some(l) = pick { @@ -319,6 +377,13 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S let mut edited = shown.clone(); let code = font(Type::Path); let rows = shown.split('\n').count().max(1); + let editor_id = ui.make_persistent_id("act_script_editor"); + // The lines that hold a problem, marked in the gutter. + let bad: std::collections::BTreeSet = src.and_then(|s| s.compiled().as_ref().err()).map(|p| p.iter().map(|p| p.line).collect()).unwrap_or_default(); + // Whether it runs, and what keeps it from running, above the code. + if let Some(s) = src { + script_status(ui, s, &shown, editor_id); + } let changed = egui::ScrollArea::both() .id_salt("act_script") .max_height(320.0) @@ -327,19 +392,25 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S ui.horizontal_top(|ui| { // Line numbers, right-aligned in a gutter, on the same rows as the text. let digits = rows.to_string().len().max(2); - let numbers: String = (1..=rows).map(|i| format!("{i:>digits$}")).collect::>().join("\n"); + let mut numbers = egui::text::LayoutJob::default(); + for i in 1..=rows { + let color = if bad.contains(&(i as u32)) { T.error } else { T.text_faint }; + let sep = if i < rows { "\n" } else { "" }; + numbers.append(&format!("{i:>digits$}{sep}"), 0.0, egui::TextFormat { font_id: code.clone(), color, ..Default::default() }); + } ui.vertical(|ui| { ui.add_space(f32::from(EDITOR_MARGIN)); - ui.add(egui::Label::new(text(Type::Path, numbers).color(T.text_faint)).selectable(false)); + ui.add(egui::Label::new(numbers).selectable(false)); }); let editor = egui::TextEdit::multiline(&mut edited) + .id(editor_id) .code_editor() .font(code.clone()) .margin(egui::Margin::symmetric(6, EDITOR_MARGIN)) .desired_rows(12) .desired_width(f32::INFINITY) - .hint_text("// Type or paste a frame script"); - ui.add(editor).named("Frame script").changed() + .hint_text(tr!("// Type or paste a frame script")); + ui.add(editor).named(tr!("Frame script")).changed() }) .inner }) @@ -351,12 +422,20 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S if src.is_none() { p["language"] = json!(language.key()); } - run(app, true, "Edit script", "script.set", p); + run(app, true, tr_noop!("Edit script"), "script.set", p); } - ui.label(text(Type::Caption, "Kept with the document as written. AniCraft doesn't run scripts yet: Test Movie and exports skip it. Use actions for what should happen while the movie plays.")); - if src.is_some() && ui.small_button("Remove script").on_hover_text("Delete this keyframe's script").clicked() { + match src.map(SourceScript::runs) { + None => { + ui.label(text(Type::Caption, tr!("Kept with the document as written. ActionScript 3.0 that controls the timeline runs in Test Movie and the HTML canvas export."))); + } + Some(false) => { + ui.label(text(Type::Caption, tr!("A script runs only when all of it is in the ActionScript 3.0 subset AniCraft runs: timeline control (stop, play, go to a frame or label), mouse listeners, trace, and setting x, y, alpha, visible, rotation and scale on named instances. Until then it is kept as written and doesn't run."))); + } + Some(true) => {} + } + if src.is_some() && ui.small_button(tr!("Remove script")).on_hover_text(tr!("Delete this keyframe's script")).clicked() { app.run("script.clear", t.base.clone()); - app.status_ok("Removed the script — Ctrl+Z to undo"); + app.status_ok(tr!("Removed the script — {undo} to undo", undo = app.undo_key())); } } @@ -368,22 +447,22 @@ fn frame_target(app: &mut App, ui: &mut egui::Ui, doc: &Document) -> Option Option Option Option = None; - form_row(ui, FORM_LABEL_DOCK, "Plug-in", |ui| { + form_row(ui, FORM_LABEL_DOCK, tr!("Plug-in"), |ui| { egui::ComboBox::from_id_salt("act_plugin").width(220.0).selected_text(shown).show_ui(ui, |ui| { for (pid, name, entries) in &all { if ui.selectable_label(pid == id, name.as_str()).on_hover_text(pid.as_str()).clicked() { @@ -449,10 +528,10 @@ fn plugin_rows(app: &mut App, ui: &mut egui::Ui, base: &Value, id: &str, entry: } }) .response - .set_name("Plug-in"); + .set_name(tr!("Plug-in")); }); let entries = installed.map(|(_, _, e)| e.clone()).unwrap_or_default(); - form_row(ui, FORM_LABEL_DOCK, "Entry", |ui| { + form_row(ui, FORM_LABEL_DOCK, tr!("Entry"), |ui| { with_type(ui, Type::Data, |ui| { egui::ComboBox::from_id_salt("act_entry").width(160.0).selected_text(entry).show_ui(ui, |ui| { for e in &entries { @@ -462,13 +541,13 @@ fn plugin_rows(app: &mut App, ui: &mut egui::Ui, base: &Value, id: &str, entry: } }) .response - .set_name("Entry point"); + .set_name(tr!("Entry point")); }); }); if installed.is_none() { - ui.label(text(Type::Caption, format!("“{id}” isn't installed here: Test Movie says so and plays on.")).color(T.error)); + ui.label(text(Type::Caption, tr!("“{id}” isn't installed here: Test Movie says so and plays on.", id = id)).color(T.error)); } - ui.label(text(Type::Caption, "The plug-in runs each time the playhead enters this keyframe, reads where the movie is, and sends actions back. It can't change the document.")); + ui.label(text(Type::Caption, tr!("The plug-in runs each time the playhead enters this keyframe, reads where the movie is, and sends actions back. It can't change the document."))); if let Some((pid, e)) = pick { set_frame(app, base, json!({"plugin": pid, "entry": e})); } @@ -493,40 +572,40 @@ fn run(app: &mut App, live: bool, label: &str, id: &str, p: Value) { fn instance_tab(app: &mut App, ui: &mut egui::Ui, e: &Element) { let doc = app.s.doc.clone(); let mut name = e.name.clone(); - form_row(ui, FORM_LABEL_DOCK, "Name", |ui| { - if ui.add(egui::TextEdit::singleline(&mut name).desired_width(200.0).hint_text("instance name")).named("Instance name").changed() { - run(app, true, "Instance name", "instance.set_name", json!({"element": e.id.0, "name": name})); + form_row(ui, FORM_LABEL_DOCK, tr!("Name"), |ui| { + if ui.add(egui::TextEdit::singleline(&mut name).desired_width(200.0).hint_text(tr!("instance name"))).named(tr!("Instance name")).changed() { + run(app, true, tr_noop!("Instance name"), "instance.set_name", json!({"element": e.id.0, "name": name})); } }); if e.name.is_empty() { - ui.label(text(Type::Caption, "Name it to address it from actions (letters, digits and _). Its events work without a name.")); + ui.label(text(Type::Caption, tr!("Name it to address it from actions (letters, digits and _). Its events work without a name."))); } let ElementKind::Symbol { events, .. } = &e.kind else { return }; let tl = doc.timeline(app.s.scene).clone(); let cx = Choices::new(&doc, &tl, true); ui.add_space(4.0); - ui.label(text(Type::Caption, "Its actions run on the timeline it is on: “this” is the main timeline.")); + ui.label(text(Type::Caption, tr!("Its actions run on the timeline it is on: “this” is the main timeline."))); for h in events { ui.add_space(6.0); ui.horizontal(|ui| { - ui.label(text(Type::Body, format!("On {}", h.event.label().to_lowercase())).strong()).on_hover_text(h.event.hint()); + ui.label(text(Type::Body, event_heading(h.event)).strong()).on_hover_text(crate::i18n::t(h.event.hint())); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.small_button("Remove event").clicked() { + if ui.small_button(tr!("Remove event")).clicked() { app.run("actions.clear", json!({"element": e.id.0, "event": h.event.key()})); - app.status_ok(format!("Removed the {} event — Ctrl+Z to undo", h.event.label().to_lowercase())); + app.status_ok(event_removed(h.event, &app.undo_key())); } }); }); if let Some((new, live)) = edit_list(ui, h.event.key(), &h.actions, &cx) { - run(app, live, "Edit event", "actions.set", json!({"element": e.id.0, "event": h.event.key(), "actions": new})); + run(app, live, tr_noop!("Edit event"), "actions.set", json!({"element": e.id.0, "event": h.event.key(), "actions": new})); } } let unused: Vec = ButtonEvent::ALL.into_iter().filter(|ev| !events.iter().any(|h| h.event == *ev)).collect(); if !unused.is_empty() { ui.add_space(6.0); - ui.menu_button("Add event", |ui| { + ui.menu_button(tr!("Add event"), |ui| { for ev in unused { - if ui.button(ev.label()).on_hover_text(ev.hint()).clicked() { + if ui.button(crate::i18n::t(ev.label())).on_hover_text(crate::i18n::t(ev.hint())).clicked() { // A new event starts with the action people want most: go on playing. let first = Action::Play { target: Target::this() }; app.run("actions.set", json!({"element": e.id.0, "event": ev.key(), "actions": [first]})); @@ -537,6 +616,28 @@ fn instance_tab(app: &mut App, ui: &mut egui::Ui, e: &Element) { } } +/// An event's heading in the Instance tab ("On click"): one sentence per event. +fn event_heading(ev: ButtonEvent) -> &'static str { + match ev { + ButtonEvent::Click => tr!("On click"), + ButtonEvent::Press => tr!("On press"), + ButtonEvent::Release => tr!("On release"), + ButtonEvent::Over => tr!("On pointer over"), + ButtonEvent::Out => tr!("On pointer out"), + } +} + +/// The status message after an event is removed: one sentence per event. +fn event_removed(ev: ButtonEvent, undo: &str) -> String { + match ev { + ButtonEvent::Click => tr!("Removed the click event — {undo} to undo", undo = undo), + ButtonEvent::Press => tr!("Removed the press event — {undo} to undo", undo = undo), + ButtonEvent::Release => tr!("Removed the release event — {undo} to undo", undo = undo), + ButtonEvent::Over => tr!("Removed the pointer over event — {undo} to undo", undo = undo), + ButtonEvent::Out => tr!("Removed the pointer out event — {undo} to undo", undo = undo), + } +} + /// What the pickers offer, from the document. struct Choices<'a> { doc: &'a Document, @@ -639,9 +740,9 @@ fn edit_list(ui: &mut egui::Ui, scope: &str, list: &[Action], cx: &Choices<'_>) } let mut added = None; ui.add_space(4.0); - ui.menu_button("Add action", |ui| { + ui.menu_button(tr!("Add action"), |ui| { for (op, label) in KINDS { - if ui.button(label).clicked() { + if ui.button(crate::i18n::t(label)).clicked() { added = Action::new(op); ui.close(); } @@ -675,15 +776,15 @@ fn action_row(ui: &mut egui::Ui, i: usize, n: usize, a: &mut Action, cx: &Choice let mut change = None; ui.horizontal(|ui| { ui.label(text(Type::DataSmall, format!("{:>2}", i + 1)).color(T.text_faint)); - ui.label(text(Type::Body, a.label()).strong()); + ui.label(text(Type::Body, crate::i18n::t(a.label())).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.small_button("Remove").on_hover_text("Remove this action").clicked() { + if ui.small_button(tr!("Remove")).on_hover_text(tr!("Remove this action")).clicked() { change = Some(Change::Remove); } - if i + 1 < n && crate::timeline::icon_button(ui, "Move down", None, Icon::ChevronDown).clicked() { + if i + 1 < n && crate::timeline::icon_button(ui, tr!("Move down"), None, Icon::ChevronDown).clicked() { change = Some(Change::Down); } - if i > 0 && crate::timeline::icon_button(ui, "Move up", None, Icon::ChevronUp).clicked() { + if i > 0 && crate::timeline::icon_button(ui, tr!("Move up"), None, Icon::ChevronUp).clicked() { change = Some(Change::Up); } }); @@ -697,16 +798,16 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { let mut changed: Option = None; let main_here = cx.main; if let Some(t) = a.target_mut() { - form_row(ui, FORM_LABEL_DOCK, "Target", |ui| { + form_row(ui, FORM_LABEL_DOCK, tr!("Target"), |ui| { let shown = t.to_string(); egui::ComboBox::from_id_salt("target").width(200.0).selected_text(shown.clone()).show_ui(ui, |ui| { let mut opts: Vec<(String, String)> = vec![("".into(), "this".into())]; if !main_here { opts.push(("parent".into(), "parent".into())); - opts.push(("root".into(), "root (main timeline)".into())); + opts.push(("root".into(), tr!("{name} (main timeline)", name = "root"))); } for (p, k) in &cx.targets { - opts.push((p.clone(), format!("{p} · {}", if *k == SymbolKind::Button { "button" } else { "movie clip" }))); + opts.push((p.clone(), if *k == SymbolKind::Button { tr!("{path} · button", path = p) } else { tr!("{path} · movie clip", path = p) })); } if !opts.iter().any(|(p, _)| Target::new(p.clone()).to_string() == shown) { opts.push((shown.clone(), shown.clone())); @@ -720,7 +821,7 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { } }) .response - .set_name("Target"); + .set_name(tr!("Target")); }); } let target = a.target().cloned().unwrap_or_default(); @@ -728,13 +829,13 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { Action::GotoAndPlay { frame, scene, .. } | Action::GotoAndStop { frame, scene, .. } => { let resolved = cx.timeline_of(&target); let labels = cx.labels(&target); - form_row(ui, FORM_LABEL_DOCK, "Go to", |ui| { + form_row(ui, FORM_LABEL_DOCK, tr!("Go to"), |ui| { let is_label = matches!(frame, FrameRef::Label(_)); - if ui.selectable_label(!is_label, "Frame").clicked() && is_label { + if ui.selectable_label(!is_label, tr!("Frame")).clicked() && is_label { *frame = FrameRef::Number(0); changed = Some(false); } - if ui.selectable_label(is_label, "Label").on_hover_text("Frame labels survive frames being added or moved").clicked() && !is_label { + if ui.selectable_label(is_label, tr!("Label")).on_hover_text(tr!("Frame labels survive frames being added or moved")).clicked() && !is_label { *frame = FrameRef::Label(labels.first().cloned().unwrap_or_else(|| "label".into())); changed = Some(false); } @@ -742,7 +843,7 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { FrameRef::Number(n) => { let max = resolved.map_or(anicraft_engine::MAX_FRAME, |(tl, _)| tl.frame_count()); let mut shown = *n + 1; - if with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut shown).range(1..=max.max(1)).speed(0.2))).named("Frame number").changed() { + if with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut shown).range(1..=max.max(1)).speed(0.2))).named(tr!("Frame number")).changed() { *n = shown.saturating_sub(1); changed = Some(true); } @@ -750,7 +851,7 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { FrameRef::Label(l) => { egui::ComboBox::from_id_salt("label").width(140.0).selected_text(l.as_str()).show_ui(ui, |ui| { if labels.is_empty() { - ui.label(text(Type::Caption, "No frame labels yet: name a keyframe in Properties › Label")); + ui.label(text(Type::Caption, tr!("No frame labels yet: name a keyframe in Properties › Label"))); } for x in &labels { if ui.selectable_label(x == l, x.as_str()).clicked() && x != l { @@ -760,15 +861,15 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { } }) .response - .set_name("Frame label"); + .set_name(tr!("Frame label")); } } }); if resolved.is_some_and(|(_, main)| main) && cx.doc.scenes.len() > 1 { - form_row(ui, FORM_LABEL_DOCK, "Scene", |ui| { - let shown = scene.clone().unwrap_or_else(|| "This scene".into()); + form_row(ui, FORM_LABEL_DOCK, tr!("Scene"), |ui| { + let shown = scene.clone().unwrap_or_else(|| tr!("This scene").into()); egui::ComboBox::from_id_salt("scene").width(160.0).selected_text(shown).show_ui(ui, |ui| { - if ui.selectable_label(scene.is_none(), "This scene").clicked() && scene.is_some() { + if ui.selectable_label(scene.is_none(), tr!("This scene")).clicked() && scene.is_some() { *scene = None; changed = Some(false); } @@ -780,22 +881,22 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { } }) .response - .set_name("Scene"); + .set_name(tr!("Scene")); }); } } Action::Trace { message } => { - form_row(ui, FORM_LABEL_DOCK, "Message", |ui| { - if ui.add(egui::TextEdit::singleline(message).desired_width(220.0).hint_text("written to Output")).named("Trace message").changed() { + form_row(ui, FORM_LABEL_DOCK, tr!("Message"), |ui| { + if ui.add(egui::TextEdit::singleline(message).desired_width(220.0).hint_text(tr!("written to Output"))).named(tr!("Trace message")).changed() { changed = Some(true); } }); } Action::SetProperty { property, value, .. } => { - form_row(ui, FORM_LABEL_DOCK, "Property", |ui| { - egui::ComboBox::from_id_salt("prop").width(110.0).selected_text(property.label()).show_ui(ui, |ui| { + form_row(ui, FORM_LABEL_DOCK, tr!("Property"), |ui| { + egui::ComboBox::from_id_salt("prop").width(110.0).selected_text(crate::i18n::t(property.label())).show_ui(ui, |ui| { for p in Property::ALL { - if ui.selectable_label(*property == p, p.label()).clicked() && *property != p { + if ui.selectable_label(*property == p, crate::i18n::t(p.label())).clicked() && *property != p { *property = p; *value = match p { Property::Alpha | Property::Visible | Property::ScaleX | Property::ScaleY => 1.0, @@ -806,18 +907,18 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { } }) .response - .set_name("Property"); + .set_name(tr!("Property")); match property { Property::Visible => { let mut on = *value != 0.0; - if crate::theme::checkbox(ui, &mut on, "Shown").changed() { + if crate::theme::checkbox(ui, &mut on, tr!("Shown")).changed() { *value = if on { 1.0 } else { 0.0 }; changed = Some(false); } } Property::Alpha => { let mut pct = *value * 100.0; - if with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).suffix(" %").speed(0.5).max_decimals(0))).named("Alpha").changed() { + if with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).suffix(" %").speed(0.5).max_decimals(0))).named(tr!("Alpha")).changed() { *value = pct / 100.0; changed = Some(true); } @@ -829,7 +930,7 @@ fn fields(ui: &mut egui::Ui, a: &mut Action, cx: &Choices<'_>) -> Option { Property::X | Property::Y => " px", _ => " ×", }; - if with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(value).range(lo..=hi).suffix(suffix).speed(0.5).max_decimals(2))).named(p.label()).changed() { + if with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(value).range(lo..=hi).suffix(suffix).speed(0.5).max_decimals(2))).named(crate::i18n::t(p.label())).changed() { changed = Some(true); } } diff --git a/src/app.rs b/src/app.rs index 1ff6f02a..cb8cf466 100644 --- a/src/app.rs +++ b/src/app.rs @@ -16,6 +16,7 @@ pub enum Tool { Subselect, Transform, Width, + Bone, Pen, Text, Pencil, @@ -48,10 +49,10 @@ 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", + GapSize::None => tr_noop!("Don't close gaps"), + GapSize::Small => tr_noop!("Close small gaps"), + GapSize::Medium => tr_noop!("Close medium gaps"), + GapSize::Large => tr_noop!("Close large gaps"), } } pub fn screen_px(self) -> f32 { @@ -65,29 +66,30 @@ impl GapSize { } impl Tool { - pub const ALL: [Tool; 19] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Width, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom]; + pub const ALL: [Tool; 20] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Width, Tool::Bone, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom]; pub fn label(self) -> &'static str { match self { - Tool::Select => "Selection", - Tool::Subselect => "Subselection", - Tool::Transform => "Free Transform", - Tool::Width => "Width", - Tool::Pen => "Pen", - Tool::Text => "Text", - Tool::Pencil => "Pencil", - Tool::Brush => "Brush", - Tool::Eraser => "Eraser", - Tool::Rect => "Rectangle", - Tool::Oval => "Oval", - Tool::Star => "PolyStar", - Tool::Line => "Line", - Tool::PaintBucket => "Paint Bucket", - Tool::InkBottle => "Ink Bottle", - Tool::Eyedropper => "Eyedropper", - Tool::Camera => "Camera", - Tool::Hand => "Hand", - Tool::Zoom => "Zoom", + Tool::Select => tr_noop!("Selection"), + Tool::Subselect => tr_noop!("Subselection"), + Tool::Transform => tr_noop!("Free Transform"), + Tool::Width => tr_noop!("Width"), + Tool::Bone => tr_noop!("Bone"), + Tool::Pen => tr_noop!("Pen"), + Tool::Text => tr_noop!("Text"), + Tool::Pencil => tr_noop!("Pencil"), + Tool::Brush => tr_noop!("Brush"), + Tool::Eraser => tr_noop!("Eraser"), + Tool::Rect => tr_noop!("Rectangle"), + Tool::Oval => tr_noop!("Oval"), + Tool::Star => tr_noop!("PolyStar"), + Tool::Line => tr_noop!("Line"), + Tool::PaintBucket => tr_noop!("Paint Bucket"), + Tool::InkBottle => tr_noop!("Ink Bottle"), + Tool::Eyedropper => tr_noop!("Eyedropper"), + Tool::Camera => tr_noop!("Camera"), + Tool::Hand => tr_noop!("Hand"), + Tool::Zoom => tr_noop!("Zoom"), } } /// Default shortcut in the command-registry notation; the live key is in `App::keymap`. @@ -97,6 +99,7 @@ impl Tool { Tool::Subselect => Some("A"), Tool::Transform => Some("Q"), Tool::Width => Some("U"), + Tool::Bone => Some("M"), Tool::Pen => Some("P"), Tool::Text => Some("T"), Tool::Pencil => Some("Shift+Y"), @@ -114,27 +117,29 @@ impl Tool { Tool::Zoom => Some("Z"), } } + /// English (a key): translate where it is drawn with `crate::i18n::t`. 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. A motion path's points edit the same way (its ends stay).", - 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. Alt-click a selected shape or a motion path to add a point to it.", - Tool::Text => "Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too.", - Tool::Pencil => "Drag to draw freehand. The options bar sets Smooth, Straighten or Ink.", - Tool::Brush => "Drag to paint filled shapes in the fill colour (a click paints a dab). [ and ] change the size; the options set the shape, smoothing and paint mode.", - Tool::Eraser => "Drag to erase lines and fills drawn with Object Drawing off (drawing objects and symbols are kept). [ and ] change the size; the options set the shape and erase mode, and the Faucet deletes a whole fill or line with a click. Double-click the tool to erase everything on the stage.", - Tool::Width => "Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it.", - 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::Eyedropper => "Click a fill to pick its colour, gradient or bitmap (then pour it with the Paint Bucket), or a line to pick its colour, width and profile (then apply it with the Ink Bottle). With shapes selected, the picked style goes onto them. Shift-click picks into the other swatch only.", - Tool::Camera => "Drag on the stage to pan the camera, drag the round handle to turn it, and use the wheel to zoom (each drag is one undo step). Picking the tool adds a camera if the scene has none.", - 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.", + Tool::Select => tr_noop!("Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection."), + Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. On drawing objects, double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."), + Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point. Alt-click a selected shape or a motion path to add a point to it."), + Tool::Text => tr_noop!("Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too."), + Tool::Pencil => tr_noop!("Drag to draw freehand. The options bar sets Smooth, Straighten or Ink."), + Tool::Brush => tr_noop!("Drag to paint filled shapes in the fill colour (a click paints a dab). [ and ] change the size; the options set the shape, smoothing and paint mode."), + Tool::Eraser => tr_noop!("Drag to erase lines and fills drawn with Object Drawing off (drawing objects and symbols are kept). [ and ] change the size; the options set the shape and erase mode, and the Faucet deletes a whole fill or line with a click. Double-click the tool to erase everything on the stage."), + Tool::Width => tr_noop!("Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it."), + Tool::Bone => tr_noop!("Drag from one symbol instance to another to join them with a bone (they move to an armature layer); start on a bone's end to continue the chain. Click a bone to select it. Pose the armature by dragging bones or instances with the Selection tool."), + Tool::Transform => tr_noop!("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 => tr_noop!("Drag to draw a rectangle. Shift draws a square."), + Tool::Oval => tr_noop!("Drag to draw an oval. Shift draws a circle."), + Tool::Star => tr_noop!("Drag from the centre to draw a star."), + Tool::Line => tr_noop!("Drag to draw a line. Shift snaps to 45°."), + Tool::PaintBucket => tr_noop!("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 => tr_noop!("Click a shape to give it the current stroke colour and width."), + Tool::Eyedropper => tr_noop!("Click a fill to pick its colour, gradient or bitmap (then pour it with the Paint Bucket), or a line to pick its colour, width and profile (then apply it with the Ink Bottle). With shapes selected, the picked style goes onto them. Shift-click picks into the other swatch only."), + Tool::Camera => tr_noop!("Drag on the stage to pan the camera, drag the round handle to turn it, and use the wheel to zoom (each drag is one undo step). Picking the tool adds a camera if the scene has none."), + Tool::Hand => tr_noop!("Drag to pan the stage. Space works with any tool."), + Tool::Zoom => tr_noop!("Click to zoom in, Alt-click to zoom out. Ctrl+wheel zooms anywhere."), } } } @@ -175,10 +180,26 @@ pub struct StageView { pub enum Drag { None, Move { last: egui::Pos2 }, + /// Selection tool: moving the selection, snapping as it goes (ADR 0041): from stage point + /// `start`, `applied` moved so far. + SnapMove { start: egui::Pos2, applied: egui::Vec2 }, + /// Selection tool: bending segment `cmd` of raw shape `id` at `t` (ADR 0041); the pointer + /// was at `last` last frame. + Bend { id: anicraft_engine::doc::ElementId, cmd: usize, t: f32, last: egui::Pos2 }, + /// Selection tool: moving a shared corner or end (ADR 0041), now at `at`; `off` is from the + /// pointer to the point. The points that move are `App::raw_points`. + RawPoint { at: egui::Pos2, off: egui::Vec2 }, Marquee { start: egui::Pos2, cur: egui::Pos2 }, + /// Edit Multiple Frames (ADR 0047): moving the selection on every keyframe it is on, the + /// pointer at `last` last frame; or a marquee over them. + MultiMove { last: egui::Pos2 }, + MultiMarquee { 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: dragging handle `slot` of segment `cmd` of raw shape `id` (ADR 0042); the + /// pointer was at `last` last frame. + RawHandle { id: anicraft_engine::doc::ElementId, cmd: usize, slot: u8, 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`. @@ -205,6 +226,12 @@ pub enum Drag { CameraPan { last: egui::Pos2 }, CameraRotate { last: f32 }, CameraWheel { until: f64 }, + /// Bone tool (ADR 0043): drawing a bone from instance `from`, joint `head` to `cur` (stage). + Bone { from: anicraft_engine::doc::ElementId, head: egui::Pos2, cur: egui::Pos2 }, + /// Posing by inverse kinematics: point `local` of the bone's instance follows the pointer. + BonePose { bone: anicraft_engine::doc::BoneId, local: egui::Pos2 }, + /// Moving a whole armature by its root, from stage point `last` last frame. + ArmatureMove { layer: anicraft_engine::doc::LayerId, last: egui::Pos2 }, Pan, } @@ -219,6 +246,7 @@ pub enum XfKind { /// A small text prompt standing in for native file dialogs (M0). pub struct Prompt { + /// English (a key): translated where it is drawn. pub title: &'static str, pub cmd: &'static str, pub key: &'static str, @@ -266,7 +294,9 @@ pub struct App { pub playing: bool, pub looping: bool, play_acc: f64, - pub onion: bool, + /// Onion skin and Edit Multiple Frames (ADR 0047): view state, passed with each render. + pub onion: anicraft_engine::onion::OnionSkin, + pub onion_ui: crate::onion::OnionUi, /// View › Preview Through Camera: the stage shows what the movie shows (ADR 0027). pub camera_preview: bool, /// The tool in hand last frame (picking the Camera tool adds a camera). @@ -297,6 +327,19 @@ pub struct App { pub pen: Option, /// Pencil samples of the stroke in progress (stage space). pub pencil: Vec, + /// A Selection-tool point drag's points (`raw.move_point`'s `points`), and the raw shapes a + /// bend or point drag changed (merged again when it ends; ADR 0041). + pub raw_points: serde_json::Value, + pub raw_touched: Vec, + /// A Subselection point drag: the other selected anchors that move with the one dragged + /// (`raw.move_point`'s `with`, ADR 0042). + pub raw_with: Vec, + /// Subselection on raw shapes (ADR 0042): the selected anchors (stage positions, shared by + /// every shape that has them), and the ends of the edge last clicked, whose handles show. + pub raw_anchors: Vec, + pub raw_ends: Vec, + /// Where what is being dragged snapped this frame (stage space): the snap ring. + pub snap_ring: Option, pub pencil_mode: pathtools::PencilMode, /// Brush tool options, the samples of the stroke in progress (stage space, pen pressure /// when there is one) and the pen's last pressure (ADR 0033). @@ -312,6 +355,8 @@ pub struct App { pub points: Vec, /// Width tool: the selected width point (shape, index). pub width_sel: Option<(anicraft_engine::doc::ElementId, usize)>, + /// The bone picked on the stage (ADR 0043; view state). + pub bone_sel: Option, /// Subselection: the selected motion path anchors, whose handles show (ADR 0030, 0038). pub motion_anchors: Vec, /// The motion path as it was when the drag on it began. @@ -377,8 +422,9 @@ pub struct App { pub last_panel: Option, } -/// How finished this version is, shown next to the version number (docs/release.md). -pub const RELEASE_STAGE: &str = "early alpha"; +/// How finished this version is, shown next to the version number (docs/release.md). English: +/// translated where the interface shows it (`--version` prints it as is). +pub const RELEASE_STAGE: &str = tr_noop!("early alpha"); /// View-state keys, as Animate users know them: `(keys, action)`. pub const VIEW_SHORTCUTS: &[(&str, &str)] = &[ @@ -437,7 +483,8 @@ impl App { playing: false, looping: true, play_acc: 0.0, - onion: false, + onion: crate::onion::from_prefs(&prefs.onion), + onion_ui: crate::onion::OnionUi::default(), camera_preview: false, last_tool: Tool::Select, status: None, @@ -459,6 +506,12 @@ impl App { rect_radius: 0.0, pen: None, pencil: Vec::new(), + raw_points: serde_json::Value::Null, + raw_touched: Vec::new(), + raw_with: Vec::new(), + raw_anchors: Vec::new(), + raw_ends: Vec::new(), + snap_ring: None, pencil_mode: pathtools::PencilMode::default(), brush: crate::brushtool::BrushOptions::default(), brush_samples: Vec::new(), @@ -468,6 +521,7 @@ impl App { align_to_stage: false, points: Vec::new(), width_sel: None, + bone_sel: None, motion_anchors: Vec::new(), motion_drag: None, frame_sel: None, @@ -509,7 +563,7 @@ impl App { }; app.apply_prefs(ctx); app.decode_sounds(); - app.status_ok("Welcome to AniCraft. Press Enter to play the sample animation."); + app.status_ok(tr!("Welcome to AniCraft. Press Enter to play the sample animation.")); if let Some(e) = recovery_err { app.status_err(e); } @@ -522,10 +576,16 @@ impl App { pub fn toggle_camera_preview(&mut self) { self.camera_preview = !self.camera_preview; if self.camera_preview && self.s.doc.timeline(self.s.scene).camera_layer().is_none() { - self.status_ok("Preview through camera is on; add a camera (the camera button on the timeline, or the Camera tool) to look through it."); + self.status_ok(tr!("Preview through camera is on; add a camera (the camera button on the timeline, or the Camera tool) to look through it.")); } } + /// The Undo key as this computer shows it (rebindable; ⌘Z on macOS), for messages that + /// say how to undo. + pub fn undo_key(&self) -> String { + platform::shortcut_label(self.keymap.primary("edit.undo").unwrap_or("Ctrl+Z")) + } + pub fn status_ok(&mut self, text: impl Into) { self.status = Some(Status { text: text.into(), error: false, at: 0.0 }); } @@ -536,8 +596,7 @@ impl App { /// Runs an engine command, reporting failures in the status bar. /// After a move, selected raw shapes merge where they land (ADR 0031). pub fn drop_raw(&mut self) { - let sel = &self.s.selection; - let raw = self.s.visible_elements().iter().any(|e| sel.contains(&e.id) && matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)); + let raw = self.s.selected_elements().iter().any(|(_, e)| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)); if raw { self.run("draw.drop", json!({})); } @@ -553,7 +612,8 @@ impl App { match result { Ok(v) => Some(v), Err(e) => { - self.status_err(e.to_string()); + // The engine's English, translated when a catalog has that exact message. + self.status_err(crate::i18n::t_dyn(&e.to_string()).into_owned()); None } } @@ -567,7 +627,7 @@ impl App { let path = std::path::PathBuf::from(&name); match p.data.and_then(|data| anicraft_engine::vfs::put(&path, data).map_err(|e| e.to_string())) { Ok(()) => self.request(p.cmd, json!({"path": name})), - Err(e) => self.status_err(format!("Could not open {name}: {e}")), + Err(e) => self.status_err(tr!("Could not open {name}: {e}", name = name, e = e)), } } @@ -576,8 +636,13 @@ impl App { /// 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) { + // The interface language first: everything drawn from here on is in it (ADR 0040). + // (`--lang` holds for the run, over the saved choice: `i18n::force`.) + crate::i18n::set_language(&self.prefs.language); + ctx.request_repaint(); ctx.set_zoom_factor(self.prefs.ui_scale); theme::apply_palette(ctx, self.prefs.theme); + crate::onion::refresh_colors(self); 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(_))); @@ -602,7 +667,7 @@ impl App { }) .collect(); for name in missing { - self.status_err(format!("Font “{name}” is not installed; using the bundled font")); + self.status_err(tr!("Font “{name}” is not installed; using the bundled font", name = name)); } } theme::install_fonts(ctx, ui_font.as_ref(), data_font.as_ref()); @@ -638,7 +703,7 @@ impl App { if self.shot.is_none() && let Err(e) = self.prefs.save() { - self.status_err(format!("Could not save preferences: {e}")); + self.status_err(tr!("Could not save preferences: {e}", e = e)); } } @@ -719,6 +784,30 @@ impl App { self.scan_system_fonts(); } Some("confirm") => self.request("layer.delete", json!({})), + Some(which @ ("onion" | "onionmenu")) => { + // Onion skin ±5 on a frame with frames before and after it, the markers on the + // ruler; with its menu open, in outlines (ADR 0047). + self.onion.ghosts = true; + self.onion.preset(5); + self.run("timeline.goto", json!({"frame": 12})); + if which == "onionmenu" { + self.onion.outlines = true; + self.onion_ui.open_menu = true; + } + } + Some("editmultiple") => { + // Edit Multiple Frames over the sample's walk, everything selected (ADR 0047). + self.onion.preset(5); + crate::onion::toggle_edit_multiple(self); + self.run("timeline.goto", json!({"frame": 12})); + crate::onion::select_all(self); + } + Some("selection") => { + // A selection across layers (ADR 0044): Select All takes every unlocked layer's + // artwork; the timeline marks the layers, Properties says how many. + self.tool = Tool::Select; + self.run("edit.select_all", json!({})); + } Some("plugins") => { // The first generator's dialog, previewing (run with ANICRAFT_PLUGINS set). let first = self.s.plugins.list().find(|p| crate::plugins_ui::is_command(p) && !p.manifest().params.is_empty() && p.manifest().selection == anicraft_engine::plugins::SelectionNeed::Optional).map(|p| p.id().to_string()); @@ -727,6 +816,15 @@ impl App { None => self.show_plugins = true, } } + Some("strokes") => { + // Stroke styles (ADR 0046): a mitred zigzag with square caps, a dotted tapering + // line, and a dashed oval with bevelled corners, selected, so Properties shows + // Style with its dash editor, Cap, Join and Miter. + self.tool = Tool::Select; + self.run("draw.path", json!({"d": "M 80 640 L 200 520 L 320 640 L 440 520 L 560 640", "fill": null, "stroke": "#1b2a4a", "stroke_width": 14, "cap": "square", "join": "miter", "miter": 4, "object": true})); + self.run("draw.line", json!({"x0": 80, "y0": 690, "x1": 560, "y1": 690, "stroke": "#e8553b", "stroke_width": 8, "style": "dotted", "dot_spacing": 6, "profile": "taper_end", "object": true})); + self.run("draw.rect", json!({"x": 640, "y": 500, "w": 300, "h": 180, "fill": "#f3d36b", "stroke": "#3d8bfd", "stroke_width": 6, "cap": "none", "join": "miter", "dash": [18, 8], "object": true})); + } Some("filters") => { // A movie clip with a bevel and a gradient glow, selected: Properties › Filters // shows both (scrolled to the glow's ramp editor). @@ -758,20 +856,30 @@ impl App { crate::test_movie::demo_pointer(self); } } - Some("script") => { + Some(which @ ("script" | "scriptproblems" | "testscript")) => { // The interactive sample as an imported Animate document might bring it: a // frame script kept on the Actions layer's first keyframe (in place of its // Stop action), a linkage class and a document class; the Actions panel shows - // the Script view (ADR 0013 tier 1). + // the Script view (ADR 0013). `script` runs (tier 2); `scriptproblems` uses + // what the subset doesn't, and shows where; `testscript` plays the one that + // runs in Test Movie, its Play button clicked. self.perform("file.new_sample", json!({"which": "interactive"})); self.run("layer.select", json!({"index": 0})); - let code = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(event:MouseEvent):void {\n\tgotoAndPlay(\"show\");\n}\n"; + // i18n-exempt: script source, document content + let runs = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(event:MouseEvent):void {\n\ttrace(\"Play clicked\");\n\tgotoAndPlay(\"show\");\n}\n"; + // i18n-exempt: script source, document content + let problems = "import flash.events.MouseEvent;\n\nstop();\nvar clicks:int = 0;\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(event:MouseEvent):void {\n\tclicks++;\n\tif (clicks > 1) {\n\t\tgotoAndPlay(\"show\");\n\t}\n}\n"; + let code = if which == "scriptproblems" { problems } else { runs }; self.run("script.set", json!({"frame": 0, "text": code, "language": "actionscript3"})); self.run("script.set_class", json!({"class": "com.example.Menu"})); if let Some(button) = self.s.doc.library.iter().find(|s| s.kind == anicraft_engine::doc::SymbolKind::Button).map(|s| s.id.0) { self.run("script.set_class", json!({"symbol": button, "class": "com.example.PlayButton", "base": "flash.display.SimpleButton"})); } crate::actions_panel::open(self, crate::actions_panel::Tab::Frame); + if which == "testscript" { + crate::test_movie::open(self); + crate::test_movie::demo_pointer(self); + } } Some("exporthtml") => { // File › Export › Export HTML Canvas… on the interactive sample (the in-app @@ -816,6 +924,66 @@ impl App { self.run("element.select_connected", json!({"x": 520, "y": 400})); self.tool = Tool::Select; } + Some(which @ ("rawparts" | "rawedit")) => { + // The Selection tool on raw shapes (ADR 0041) on a new layer: a rectangle with its + // outline, an oval and a line that cut each other. + self.run("layer.new", json!({})); + for (id, p) in [ + ("draw.rect", json!({"x": 180, "y": 120, "w": 300, "h": 200, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3})), + ("draw.ellipse", json!({"x": 360, "y": 210, "w": 240, "h": 240, "fill": "#3d8bfd", "stroke": "#1b2a4a", "stroke_width": 3})), + ("draw.line", json!({"x0": 140, "y0": 420, "x1": 680, "y1": 140, "stroke": "#d6336c", "stroke_width": 3})), + ] { + let mut p = p; + p["object"] = json!(false); + self.run(id, p); + } + self.run("edit.deselect", json!({})); + if which == "rawparts" { + // A marquee over the middle: the parts under it are selected, cut at its edges. + self.run("raw.select_rect", json!({"x0": 300, "y0": 170, "x1": 470, "y1": 330})); + } else { + // The top edge bent upwards, the bottom-left corner pulled out, and the + // rectangle's top-right corner being dragged onto the line (the snap ring). + self.run("path.bend_segment", json!({"x": 260, "y": 120, "dx": 0, "dy": -60})); + self.run("raw.move_point", json!({"x": 180, "y": 320, "to_x": 130, "to_y": 350})); + self.s.begin_gesture(tr_noop!("Move Point")); + let r = self.run("raw.move_point", json!({"x": 480, "y": 120, "to_x": 520, "to_y": 214, "snap": 10, "merge": false})); + let f = |k: &str| r.as_ref().and_then(|v| v.get(k)).and_then(Value::as_f64).unwrap_or(0.0) as f32; + self.raw_points = r.as_ref().and_then(|v| v.get("points")).cloned().unwrap_or(Value::Null); + self.snap_ring = r.as_ref().and_then(|v| v.get("snapped")).filter(|v| v.is_object()).map(|_| anicraft_engine::geom::Vec2::new(f("x"), f("y"))); + self.drag = Drag::RawPoint { at: egui::pos2(f("x"), f("y")), off: egui::Vec2::ZERO }; + } + self.tool = Tool::Select; + } + Some("rawsub") => { + // Subselection on raw shapes (ADR 0042) on a new layer: an outlined square, an + // oval and a line that cut each other, merged. A click on the oval shows the + // points of everything connected; its right-hand point is selected, so its curve + // handles show, and one handle is being dragged (both shapes on that edge bend). + self.run("layer.new", json!({})); + for (id, p) in [ + ("draw.rect", json!({"x": 180, "y": 120, "w": 300, "h": 200, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3})), + ("draw.ellipse", json!({"x": 360, "y": 210, "w": 240, "h": 240, "fill": "#3d8bfd", "stroke": "#1b2a4a", "stroke_width": 3})), + ("draw.line", json!({"x0": 140, "y0": 420, "x1": 680, "y1": 140, "stroke": "#d6336c", "stroke_width": 3})), + ] { + let mut p = p; + p["object"] = json!(false); + self.run(id, p); + } + self.run("edit.deselect", json!({})); + self.tool = Tool::Subselect; + let v = self.run("raw.subselect", json!({"x": 480, "y": 450, "slop": 4})); + self.raw_ends = Vec::new(); + let anchor = anicraft_engine::geom::Vec2::new(600.0, 330.0); + self.raw_anchors = vec![anchor]; + let pts = self.s.raw_points(&self.s.selection.on(self.s.layer)); + if let (Some(_), Some(h)) = (v, pts.handles.iter().find(|h| h.anchor.distance(anchor) < 0.5 && h.at.y > anchor.y)) { + self.s.begin_gesture(tr_noop!("Move Handle")); + let r = self.run("raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 40, "dy": 10, "merge": false})); + self.raw_touched = r.as_ref().map(|v| v["changed"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect()).unwrap_or_default(); + self.drag = Drag::RawHandle { id: h.id, cmd: h.cmd, slot: h.slot, last: egui::pos2(h.at.x + 40.0, h.at.y + 10.0) }; + } + } Some(which @ ("brush" | "brushing")) => { // Brushed artwork on a new layer (ADR 0033): a pressure-tapered wave, a flat // calligraphic tip at 45°, square dabs, and a pink stroke painted behind a raw @@ -964,6 +1132,25 @@ impl App { self.last_tool = Tool::Camera; self.camera_preview = which == "cameraview"; } + Some("bones") => { + // A three-limb arm on an armature (ADR 0043): bent by IK at frame 1, the elbow + // limited, a second pose at frame 24, the elbow's bone selected. + self.run("layer.new", json!({"name": "Puppet"})); + self.run("draw.rect", json!({"x": 315, "y": 400, "w": 170, "h": 40, "radius": 20, "fill": "#ff9f43", "stroke": "#1b2a4a", "stroke_width": 3})); + let id = |v: Option, k: &str| v.and_then(|v| v[k].as_u64()).unwrap_or(0); + let made = self.run("modify.convert_to_symbol", json!({"name": "Limb"})); + let (symbol, root) = (id(made.clone(), "symbol"), id(made, "instance")); + let arm = id(self.run("library.place", json!({"symbol": symbol, "x": 560, "y": 420})), "element"); + let hand = id(self.run("library.place", json!({"symbol": symbol, "x": 720, "y": 420})), "element"); + let b1 = id(self.run("bone.add", json!({"from": root, "to": arm, "head": [480, 420], "tail": [640, 420]})), "bone"); + let b2 = id(self.run("bone.add", json!({"from": arm, "to": hand, "tail": [790, 420]})), "bone"); + self.run("bone.set_limits", json!({"bone": b2, "min": -30, "max": 120})); + self.run("bone.solve", json!({"bone": b2, "x": 700, "y": 560, "frame": 0})); + self.run("bone.pose", json!({"bone": b1, "angle": -35, "frame": 23})); + self.run("timeline.goto", json!({"frame": 0})); + self.bone_sel = Some(anicraft_engine::doc::BoneId(b2)); + self.tool = Tool::Select; + } Some("tlwide") => { // Zoomed in: wide frames, playhead on frame 1 and frame 4. self.tl_cell_w = 48.0; @@ -1047,9 +1234,30 @@ impl App { self.run("motion.add_point", json!({"segment": 2, "t": 0.45})); self.run("motion.convert_point", json!({"anchor": 1, "smooth": false})); self.motion_anchors = vec![1, 2]; - self.status_ok(format!("Added a point to the motion path. {} to undo.", platform::shortcut_label("Ctrl+Z"))); + self.status_ok(tr!("Added a point to the motion path. {undo} to undo.", undo = self.undo_key())); } } + Some(which @ ("motionpins" | "motionpinsspan")) => { + // Anchors pinned to frames (ADR 0049): `motionpath`'s curve with its middle point + // pinned to frame 17, and the star moved up on frame 35, which pinned a new point + // there. Subselection on that point, the span selected, and the Motion Editor on + // Y (or the timeline, with its diamonds at the pinned frames). + self.open_panel(Some("motionpath")); + self.run("motion.pin_point", json!({"anchor": 1, "frame": 16})); + self.run("timeline.goto", json!({"frame": 34})); + self.run("element.translate", json!({"dx": 20, "dy": -110})); + self.s.mark_saved(); + self.run("timeline.goto", json!({"frame": 24})); + self.run("element.select", json!({"ids": []})); + self.frame_sel = Some(timeline::FrameSel::cell(self.s.layer, 24)); + self.tool = Tool::Subselect; + self.motion_anchors = vec![2]; + if which == "motionpins" { + self.bottom = BottomTab::MotionEditor; + } + self.me_prop = anicraft_engine::doc::Property::Y; + self.me_key = None; + } Some("pen") => { // A pen path still being drawn: a corner, a smooth point with handles, a corner. self.tool = Tool::Pen; @@ -1093,10 +1301,17 @@ impl App { self.library_sel = LibraryItem::first(&self.s.doc); self.decode_sounds(); self.recovery.restored(&session); - let name = self.s.path.as_deref().and_then(std::path::Path::file_name).map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned()); - self.status_ok(format!("Restored “{name}”. It isn't saved yet: Save to keep it.")); + let name = self.s.path.as_deref().and_then(std::path::Path::file_name).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned()); + self.status_ok(tr!("Restored “{name}”. It isn't saved yet: Save to keep it.", name = name)); return Some(v); } + self.announce(id, &v, selected); + Some(v) + } + + /// What a command's result means for the window: the status line, and the view state a + /// new document resets. `selected` is how many elements were selected before it ran. + pub(crate) fn announce(&mut self, id: &str, v: &Value, selected: usize) { match id { "file.new" | "file.new_sample" | "file.open" => { self.view.fit = true; @@ -1105,8 +1320,8 @@ impl App { 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" }), + Some(r) => self.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)), + None => self.status_ok(if id == "file.open" { tr!("Opened") } else { tr!("New document") }), } } "file.recover" => { @@ -1114,20 +1329,21 @@ impl App { self.frame_sel = None; self.library_sel = LibraryItem::first(&self.s.doc); self.recovery.restored(v["recovered"].as_str().unwrap_or("")); - let name = v["name"].as_str().unwrap_or("Untitled"); + let name = v["name"].as_str().unwrap_or(tr!("Untitled")); self.status_ok(if v["original_newer"].as_bool() == Some(true) { - format!("Restored “{name}” as a new document (the file on disk is newer). Save to keep it.") + tr!("Restored “{name}” as a new document (the file on disk is newer). Save to keep it.", name = name) } else { - format!("Restored “{name}”. It isn't saved yet: Save to keep it.") + tr!("Restored “{name}”. It isn't saved yet: Save to keep it.", name = name) }); } "file.discard_recovery" => { self.recovery.discarded(v["discarded"].as_str().unwrap_or("")); - self.status_ok("Discarded the autosaved copy"); + self.status_ok(tr!("Discarded the autosaved copy")); } "file.save" | "file.save_as" => { // In a browser the file goes to the downloads (ADR 0036). - self.status_ok(format!("Saved {}{}", v["saved"].as_str().unwrap_or(""), if platform::WEB { " to your downloads" } else { "" })); + let path = v["saved"].as_str().unwrap_or(""); + self.status_ok(if platform::WEB { tr!("Saved {path} to your downloads", path = path) } else { tr!("Saved {path}", path = path) }); if self.close_after_save { self.allow_close = true; } @@ -1136,58 +1352,70 @@ impl App { let id = anicraft_engine::doc::SoundId(v["sound"].as_u64().unwrap_or(0)); self.library_sel = Some(LibraryItem::Sound(id)); let name = v["name"].as_str().unwrap_or(""); - let secs = v["seconds"].as_f64().unwrap_or(0.0); + let secs = format!("{:.2}", v["seconds"].as_f64().unwrap_or(0.0)); self.status_ok(if v.get("layer").is_some() { - format!("{name} ({secs:.2} s) is on a new layer from frame {}. Set its sync in Properties. Ctrl+Z to undo.", self.s.frame + 1) + tr!("{name} ({secs} s) is on a new layer from frame {frame}. Set its sync in Properties. {undo} to undo.", name = name, secs = secs, frame = self.s.frame + 1, undo = self.undo_key()) } else { - format!("{name} ({secs:.2} s) is in the Library. Select a keyframe and pick it under Sound in Properties.") + tr!("{name} ({secs} s) is in the Library. Select a keyframe and pick it under Sound in Properties.", name = name, secs = secs) }); } - "file.import_to_library" => self.status_ok("Image added to the Library"), + "file.import_to_library" => self.status_ok(tr!("Image added to the Library")), "file.export_audio" => { let n = v["sounds"].as_u64().unwrap_or(0); - let note = if n == 0 { " No sounds play in that range, so the file is silent." } else { "" }; - self.status_ok(format!("Exported {} ({:.2} s).{note}", v["written"].as_str().unwrap_or(""), v["seconds"].as_f64().unwrap_or(0.0))); + let (path, secs) = (v["written"].as_str().unwrap_or(""), format!("{:.2}", v["seconds"].as_f64().unwrap_or(0.0))); + self.status_ok(if n == 0 { tr!("Exported {path} ({secs} s). No sounds play in that range, so the file is silent.", path = path, secs = secs) } else { tr!("Exported {path} ({secs} s).", path = path, secs = secs) }); } - "sound.delete" => self.status_ok("Deleted sound — Ctrl+Z to undo"), + "sound.delete" => self.status_ok(tr!("Deleted sound — {undo} to undo", undo = self.undo_key())), "file.import" => { if let Some(b) = self.s.doc.bitmaps.last().filter(|b| v["bitmap"].as_u64() == Some(b.id.0)) { self.library_sel = Some(LibraryItem::Bitmap(b.id)); } let n = v["elements"].as_u64().unwrap_or(0); let report = v["report"].as_str().unwrap_or(""); - let what = if n == 1 { "element" } else { "elements" }; - let undo = platform::shortcut_label("Ctrl+Z"); + let undo = tr!("{undo} to undo.", undo = self.undo_key()); // A drawing with clip paths or masks comes in as a folder of layers (ADR 0021). - let place = match (v["layers"].as_u64().unwrap_or(1), v["masks"].as_u64().unwrap_or(0)) { - (0 | 1, _) => "on a new layer".to_string(), - (l, 1) => format!("in a new folder of {l} layers with a mask"), - (l, m) => format!("in a new folder of {l} layers with {m} masks"), + let placed = match (v["layers"].as_u64().unwrap_or(1), v["masks"].as_u64().unwrap_or(0)) { + (0 | 1, _) => trn!("{n} element on a new layer.", "{n} elements on a new layer.", n), + (l, 1) => trn!("{n} element in a new folder of {layers} layers with a mask.", "{n} elements in a new folder of {layers} layers with a mask.", n, layers = l), + (l, m) => trn!("{n} element in a new folder of {layers} layers with {masks} masks.", "{n} elements in a new folder of {layers} layers with {masks} masks.", n, layers = l, masks = m), }; - self.status_ok(format!("{n} {what} {place}. {report} {undo} to undo.")); + // Three sentences: what came in, the importer's report, how to undo. + self.status_ok(format!("{placed} {report} {undo}")); } - "file.export_sprite_sheet" => self.status_ok(format!("Exported {} frames to {} ({}×{} grid) and its frame map {}", v["frames"], v["written"].as_str().unwrap_or(""), v["columns"], v["rows"], v["map"].as_str().unwrap_or(""))), + "file.export_sprite_sheet" => self.status_ok(trn!( + "Exported {n} frame to {path} ({columns}×{rows} grid) and its frame map {map}", + "Exported {n} frames to {path} ({columns}×{rows} grid) and its frame map {map}", + v["frames"].as_u64().unwrap_or(0), + path = v["written"].as_str().unwrap_or(""), + columns = v["columns"], + rows = v["rows"], + map = v["map"].as_str().unwrap_or("") + )), "file.export_html" => { + // The exporter's report, when there is one, is a sentence of its own after. let report = v["report"].as_str().filter(|r| !r.is_empty()).map(|r| format!(" {r}")).unwrap_or_default(); let kb = v["bytes"].as_u64().unwrap_or(0).div_ceil(1024); - self.status_ok(format!("Exported {} ({} frames, {kb} KB): open it in a web browser.{report}", v["written"].as_str().unwrap_or(""), v["frames"])); + let done = trn!("Exported {path} ({n} frame, {kb} KB): open it in a web browser.", "Exported {path} ({n} frames, {kb} KB): open it in a web browser.", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), kb = kb); + self.status_ok(format!("{done}{report}")); } "file.export_lottie" => { let report = v["report"].as_str().filter(|r| !r.is_empty()).map(|r| format!(" {r}")).unwrap_or_default(); - self.status_ok(format!("Exported {} ({} frames, {} layers).{report}", v["written"].as_str().unwrap_or(""), v["frames"], v["layers"])); + let done = trn!("Exported {path} ({n} frame, {layers} layers).", "Exported {path} ({n} frames, {layers} layers).", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), layers = v["layers"]); + self.status_ok(format!("{done}{report}")); } - "file.export_png" | "file.export_png_sequence" | "file.export_gif" | "file.export_svg" | "file.export_video" => 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"), + "file.export_png" | "file.export_png_sequence" | "file.export_gif" | "file.export_svg" | "file.export_video" => self.status_ok(tr!("Exported {path}", path = v.get("written").or_else(|| v.get("dir")).and_then(Value::as_str).unwrap_or(""))), + // Undo labels are the engine's English, translated when a catalog has them. + "edit.undo" => self.status_ok(tr!("Undid {action}", action = crate::i18n::t_dyn(v["undone"].as_str().unwrap_or("")))), + "edit.redo" => self.status_ok(tr!("Redid {action}", action = crate::i18n::t_dyn(v["redone"].as_str().unwrap_or("")))), + "edit.delete" => self.status_ok(trn!("Deleted {n} element — {undo} to undo", "Deleted {n} elements — {undo} to undo", selected, undo = self.undo_key())), + "layer.delete" => self.status_ok(tr!("Deleted layer — {undo} to undo", undo = self.undo_key())), "draw.erase_all" => { let n = v["erased"].as_u64().unwrap_or(0); - self.status_ok(format!("Erased everything at frame {} ({n} {}). {} to undo.", self.s.frame + 1, if n == 1 { "element" } else { "elements" }, platform::shortcut_label("Ctrl+Z"))); + self.status_ok(trn!("Erased everything at frame {frame} ({n} element). {undo} to undo.", "Erased everything at frame {frame} ({n} elements). {undo} to undo.", n, frame = self.s.frame + 1, undo = self.undo_key())); } "scene.delete" => { self.frame_sel = None; - self.status_ok("Deleted scene — Ctrl+Z to undo"); + self.status_ok(tr!("Deleted scene — {undo} to undo", undo = self.undo_key())); } "scene.new" | "scene.duplicate" | "scene.select" | "scene.next" | "scene.prev" => { // Another scene's timeline: frame selections and scroll belong to the old one. @@ -1195,29 +1423,28 @@ impl App { self.tl_scroll = 0.0; self.playing = false; let (n, of) = (v["scene"].as_u64().unwrap_or(0) + 1, v["scenes"].as_u64().unwrap_or(1)); - self.status_ok(format!("{} (scene {n} of {of})", v["name"].as_str().unwrap_or(""))); + // The scene's name is document text, as written. + self.status_ok(tr!("{name} (scene {number} of {count})", name = v["name"].as_str().unwrap_or(""), number = n, count = of)); } "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") })); + self.status_ok(if n == 1 { tr!("Cleared keyframe — {undo} to undo", undo = self.undo_key()).to_string() } else { trn!("Cleared {n} keyframe — {undo} to undo", "Cleared {n} keyframes — {undo} to undo", n, undo = self.undo_key()) }); } "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.copy_frames" => trn!("Copied {n} frame", "Copied {n} frames", n), + "timeline.cut_frames" => trn!("Cut {n} frame — {undo} to undo", "Cut {n} frames — {undo} to undo", n, undo = self.undo_key()), + _ => trn!("Pasted {n} frame — {undo} to undo", "Pasted {n} frames — {undo} to undo", n, undo = self.undo_key()), }); } - "plugin.run" | "plugin.install" | "plugin.remove" | "plugin.reload" => crate::plugins_ui::status(self, id, &v), + "plugin.run" | "plugin.install" | "plugin.remove" | "plugin.reload" => crate::plugins_ui::status(self, id, v), "timeline.remove_frame" => { let n = v["removed"].as_u64().unwrap_or(1); - self.status_ok(format!("Removed {} — Ctrl+Z to undo", if n == 1 { "frame".to_string() } else { format!("{n} frames") })); + self.status_ok(if n == 1 { tr!("Removed frame — {undo} to undo", undo = self.undo_key()).to_string() } else { trn!("Removed {n} frame — {undo} to undo", "Removed {n} frames — {undo} to undo", n, undo = self.undo_key()) }); } _ => {} } - Some(v) } /// Invokes a command from a menu, shortcut, palette or context menu, asking for a path or @@ -1232,9 +1459,25 @@ impl App { other => other, }; if let Some(why) = platform::unavailable(id) { - self.status_err(why); + self.status_err(crate::i18n::t(why)); return; } + // Edit Multiple Frames (ADR 0047) selects on every keyframe between the markers. + if crate::onion::editing(self) { + match id { + "edit.select_all" => return crate::onion::select_all(self), + "edit.deselect" => { + self.onion_ui.sel.clear(); + return; + } + // This slice moves artwork across keyframes; other edits stay on one frame. + "edit.delete" | "edit.cut" | "edit.copy" | "edit.duplicate" if !self.onion_ui.sel.is_empty() => { + self.status_err(tr!("Edit Multiple Frames moves artwork on several keyframes; to delete, copy or duplicate it, turn Edit Multiple Frames off and work frame by frame.")); + return; + } + _ => {} + } + } if id == "timeline.paste_frames" && let Some(p) = timeline::paste_params(self) { @@ -1247,7 +1490,7 @@ impl App { } self.recovery.show = !self.recovery.found.is_empty(); if !self.recovery.show { - self.status_ok(if self.recovery.active() { "No autosaved work to recover" } else { "Autosave is off on this system, so there is nothing to recover" }); + self.status_ok(if self.recovery.active() { tr!("No autosaved work to recover") } else { tr!("Autosave is off on this system, so there is nothing to recover") }); } return; } @@ -1273,24 +1516,24 @@ impl App { 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()))), - "scene.rename" => Some(("Rename scene", "name", self.s.doc.scenes.get(self.s.scene).map_or_else(String::new, |s| s.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())), - "file.export_svg" => Some(("Export frame as SVG", "path", format!("frame_{:04}.svg", self.s.frame + 1))), - "file.export_sprite_sheet" => Some(("Export sprite sheet (PNG + JSON frame map)", "path", "sprites.png".to_string())), - "file.export_video" => Some(("Export video (.webm or .mp4, made with your ffmpeg)", "path", "animation.webm".to_string())), - "file.export_lottie" => Some(("Export Lottie animation (JSON, for web and apps)", "path", "animation.json".to_string())), - "file.export_html" => Some(("Export HTML canvas (one web page)", "path", "movie.html".to_string())), - "file.export_audio" => Some(("Export audio (the movie's soundtrack as a WAV)", "path", "soundtrack.wav".to_string())), - "file.import_to_library" => Some(("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)", "path", "sound.wav".to_string())), - "file.import" => Some(("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)", "path", "drawing.svg".to_string())), - "plugin.install" => Some(("Install plug-in (.wasm file)", "path", "plugin.wasm".to_string())), - "modify.convert_to_symbol" => Some(("Convert to symbol — name", "name", format!("Symbol {}", self.s.doc.library.len() + 1))), + "file.open" => Some((tr_noop!("Open document"), "path", "animation.anicraft".to_string())), + "file.save" if self.s.path.is_none() => Some((tr_noop!("Save document as"), "path", "animation.anicraft".to_string())), + "file.save_as" => Some((tr_noop!("Save document as"), "path", self.s.path.as_ref().map_or_else(|| "animation.anicraft".to_string(), |p| p.display().to_string()))), + "layer.rename" => Some((tr_noop!("Rename layer"), "name", self.s.active_layer().map_or_else(String::new, |l| l.name.clone()))), + "scene.rename" => Some((tr_noop!("Rename scene"), "name", self.s.doc.scenes.get(self.s.scene).map_or_else(String::new, |s| s.name.clone()))), + "file.export_png" => Some((tr_noop!("Export frame as PNG"), "path", format!("frame_{:04}.png", self.s.frame + 1))), + "file.export_png_sequence" => Some((tr_noop!("Export PNG sequence to folder"), "dir", "frames".to_string())), + "file.export_gif" => Some((tr_noop!("Export animated GIF"), "path", "animation.gif".to_string())), + "file.export_svg" => Some((tr_noop!("Export frame as SVG"), "path", format!("frame_{:04}.svg", self.s.frame + 1))), + "file.export_sprite_sheet" => Some((tr_noop!("Export sprite sheet (PNG + JSON frame map)"), "path", "sprites.png".to_string())), + "file.export_video" => Some((tr_noop!("Export video (.webm or .mp4, made with your ffmpeg)"), "path", "animation.webm".to_string())), + "file.export_lottie" => Some((tr_noop!("Export Lottie animation (JSON, for web and apps)"), "path", "animation.json".to_string())), + "file.export_html" => Some((tr_noop!("Export HTML canvas (one web page)"), "path", "movie.html".to_string())), + "file.export_audio" => Some((tr_noop!("Export audio (the movie's soundtrack as a WAV)"), "path", "soundtrack.wav".to_string())), + "file.import_to_library" => Some((tr_noop!("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)"), "path", "sound.wav".to_string())), + "file.import" => Some((tr_noop!("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)"), "path", "drawing.svg".to_string())), + "plugin.install" => Some((tr_noop!("Install plug-in (.wasm file)"), "path", "plugin.wasm".to_string())), + "modify.convert_to_symbol" => Some((tr_noop!("Convert to symbol — name"), "name", format!("Symbol {}", self.s.doc.library.len() + 1))), // i18n-exempt: a new symbol's default name is document text _ => None, }; if let Some((title, key, text)) = prompt { @@ -1306,7 +1549,7 @@ impl App { // The platform's own dialog (it blocks, as native dialogs do). Cancel = no-op. self.playing = false; #[cfg(not(target_arch = "wasm32"))] - match platform::file_dialog(id, title, &text) { + match platform::file_dialog(id, crate::i18n::t(title), &text) { Some(path) => self.request(id, json!({ key: path.display().to_string() })), None => self.close_after_save = false, } @@ -1365,7 +1608,7 @@ impl App { } // Said once: the device could not be opened, so playback is silent. if let Some(e) = self.sound.error.take() { - self.status_err(format!("Playing without sound: {e}")); + self.status_err(tr!("Playing without sound: {e}", e = e)); } } @@ -1458,9 +1701,10 @@ impl App { _ => {} } let next = self.keymap.primary("view.next_panel").map(platform::shortcut_label).unwrap_or_default(); - self.status_ok(format!("{}{}", region.label(), if next.is_empty() { String::new() } else { format!(" · {next} for the next panel") })); + let panel = crate::i18n::t(region.label()); + self.status_ok(if next.is_empty() { panel.to_string() } else { tr!("{panel} · {next} for the next panel", panel = panel, next = next) }); } - None => self.status_err("No panel to move to yet"), + None => self.status_err(tr!("No panel to move to yet")), } } @@ -1515,6 +1759,7 @@ impl App { crate::motion_path::consume_keys(self, ctx); pathtools::consume_keys(self, ctx); crate::widthtool::consume_keys(self, ctx); + crate::bone_tool::consume_keys(self, ctx); } let mut fire: Vec<&'static str> = Vec::new(); let mut tool = None; @@ -1549,10 +1794,10 @@ impl App { 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.onion" => crate::onion::toggle_ghosts(self), "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" }); + self.status_ok(if self.align_to_stage { tr!("Align: to stage") } else { tr!("Align: to the selection") }); } "view.select_all_frames" => { let layers = &self.s.doc.timeline(self.s.scene).layers; @@ -1576,11 +1821,13 @@ impl App { if play { self.toggle_play(); } - if nudge != egui::Vec2::ZERO && !self.s.selection.is_empty() { + if nudge != egui::Vec2::ZERO && crate::onion::editing(self) { + crate::onion::nudge(self, anicraft_engine::geom::Vec2::new(nudge.x, nudge.y)); + } else if nudge != egui::Vec2::ZERO && !self.s.selection.is_empty() { // One undo step: the move, and raw shapes merging where they land (ADR 0031). let own = !self.s.in_gesture(); if own { - self.s.begin_gesture("Move"); + self.s.begin_gesture(tr_noop!("Move")); // i18n-exempt: an undo label (the engine's English, translated where shown) } self.run("element.translate", json!({"dx": nudge.x, "dy": nudge.y})); self.drop_raw(); @@ -1628,8 +1875,8 @@ impl App { } 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 { "" }); + let name = self.s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned()); + let title = format!("AniCraft — {name}{}", if self.s.is_dirty() { " •" } else { "" }); // i18n-exempt: the product name and the file's if title != self.title { ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone())); self.title = title; @@ -1640,18 +1887,19 @@ impl App { 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| { + let title = crate::i18n::t(p.title); + egui::Window::new(title).id(egui::Id::new(("prompt", 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)).named(p.title); + let r = ui.add(egui::TextEdit::singleline(&mut p.text).desired_width(f32::INFINITY)).named(title); 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() { + if ui.button(tr!("OK")).clicked() { submit = true; } - if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { + if ui.button(tr!("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { cancel = true; } }); @@ -1669,16 +1917,16 @@ impl App { fn about_window(&mut self, ctx: &egui::Context) { let mut open = self.show_about; - let shown = egui::Window::new("About AniCraft").open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { + let shown = egui::Window::new(tr!("About AniCraft")).id(egui::Id::new("about_window")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { ui.add(egui::Image::new((app_mark(ctx).id(), egui::vec2(64.0, 64.0)))); ui.heading("AniCraft"); - ui.label(format!("Version {} · {RELEASE_STAGE}", env!("CARGO_PKG_VERSION"))); - ui.label("Open-source 2D vector animation studio, written in Rust."); - 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()))); + ui.label(tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(RELEASE_STAGE))); + ui.label(tr!("Open-source 2D vector animation studio, written in Rust.")); + ui.label(trn!("{n} engine command — all available headless via anicraft-cli.", "{n} engine commands — all available headless via anicraft-cli.", commands().len())); + ui.colored_label(T.text_dim, "MIT OR Apache-2.0"); // i18n-exempt: licence identifiers + ui.label(theme::text(theme::Type::Caption, tr!("Typefaces: {fonts}", fonts = theme::font_summary()))); }); - crate::a11y::name_title_bar(&shown, "About AniCraft"); + crate::a11y::name_title_bar(&shown, tr!("About AniCraft")); self.show_about = open; } @@ -1687,44 +1935,44 @@ impl App { 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")), + (tr!("Project folder"), root.clone()), + (tr!("Requirements & technology"), root.join("docs").join("requirements.md")), + (tr!("Architecture philosophy"), root.join("docs").join("architecture.md")), + (tr!("Roadmap"), root.join("docs").join("roadmap.md")), + (tr!("Performance & budgets"), root.join("docs").join("performance.md")), + (tr!("Decision records (ADRs)"), root.join("docs").join("adr")), + (tr!("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")), + (tr!("Agent / contributor guide"), root.join("AGENTS.md")), + (tr!("Engine crates (source)"), root.join("crates")), + (tr!("Desktop app (source)"), root.join("src")), + (tr!("Screenshots"), root.join("shots")), ]; let mut opened: Option> = None; - let shown = 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")); + let shown = egui::Window::new(tr!("Project Files")).id(egui::Id::new("files_window")).open(&mut open).collapsible(false).resizable(false).default_width(620.0).show(ctx, |ui| { + ui.label(theme::text(theme::Type::Label, tr!("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")).named(&format!("Open {label}")).clicked() { + if ui.add_enabled(path.exists(), egui::Button::new(tr!("Open"))).named(&tr!("Open {label}", label = label)).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()); + let doc = self.s.path.as_ref().map_or_else(|| tr!("not saved yet (File › Save)").to_string(), |p| p.display().to_string()); + ui.label(theme::text(theme::Type::Body, tr!("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.")); + ui.label(theme::text(theme::Type::Caption, tr!("Saved documents and exports go where you type in the save box; a plain name lands in the folder AniCraft was started from."))); }); - crate::a11y::name_title_bar(&shown, "Project Files"); + crate::a11y::name_title_bar(&shown, tr!("Project Files")); match opened { Some(Err(e)) => self.status_err(e), - Some(Ok(())) => self.status_ok("Opened in your system's file viewer"), + Some(Ok(())) => self.status_ok(tr!("Opened in your system's file viewer")), None => {} } self.show_files = open; @@ -1749,6 +1997,10 @@ fn app_mark(ctx: &egui::Context) -> egui::TextureHandle { /// Opens a file or folder with the operating system's default handler. pub(crate) fn open_in_system(path: &std::path::Path) -> Result<(), String> { + // Tests click every control (`i18n::tests`): they never start another program. + if cfg!(test) { + return Ok(()); + } let mut cmd = if cfg!(target_os = "windows") { let mut c = std::process::Command::new("explorer"); c.arg(path); @@ -1762,7 +2014,7 @@ pub(crate) fn open_in_system(path: &std::path::Path) -> Result<(), String> { c.arg(path); c }; - cmd.spawn().map(|_| ()).map_err(|e| format!("could not open {}: {e}", path.display())) + cmd.spawn().map(|_| ()).map_err(|e| tr!("could not open {path}: {e}", path = path.display(), e = e)) } impl eframe::App for App { @@ -1800,10 +2052,13 @@ impl App { } if self.tool != Tool::Subselect { self.points.clear(); + self.raw_anchors.clear(); + self.raw_ends.clear(); } pathtools::upkeep(self); crate::motion_path::upkeep(self); crate::widthtool::upkeep(self); + crate::bone_tool::upkeep(self); self.tick_playback(&ctx); self.scrub_sound(); self.update_title(&ctx); @@ -1826,8 +2081,8 @@ impl App { egui::Panel::right("properties").resizable(true).default_size(dock_w).max_size((room.x * 0.5).max(220.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(timeline_h).max_size((room.y * 0.6).max(200.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)); - crate::a11y::name_splitter(&ctx, "properties", "Resize the right-hand panels"); - crate::a11y::name_splitter(&ctx, "timeline", "Resize the timeline"); + crate::a11y::name_splitter(&ctx, "properties", tr!("Resize the right-hand panels")); + crate::a11y::name_splitter(&ctx, "timeline", tr!("Resize the timeline")); self.prompt_window(&ctx); self.about_window(&ctx); diff --git a/src/autosave.rs b/src/autosave.rs index 782c1c13..61b8e7c5 100644 --- a/src/autosave.rs +++ b/src/autosave.rs @@ -72,7 +72,7 @@ impl Recovery { r.scanning = Some(false); (r, None) } - Err(e) => (r, Some(format!("Autosave is off: {e}"))), + Err(e) => (r, Some(tr!("Autosave is off: {error}", error = e))), } } #[cfg(not(target_arch = "wasm32"))] @@ -80,7 +80,7 @@ impl Recovery { if shot_mode && !crate::platform::recovery_dir_overridden() { return (r, None); } - let Some(dir) = crate::platform::recovery_dir() else { return (r, Some("Autosave is off: this system has no settings folder".into())) }; + let Some(dir) = crate::platform::recovery_dir() else { return (r, Some(tr!("Autosave is off: this system has no settings folder").into())) }; recovery::prune(&dir); r.found = recovery::scan(&dir, None); r.show = !r.found.is_empty(); @@ -89,7 +89,7 @@ impl Recovery { r.saver = Some(s); None } - Err(e) => Some(format!("Autosave is off: {e}")), + Err(e) => Some(tr!("Autosave is off: {error}", error = e)), }; r.dir = Some(dir); (r, err) @@ -170,7 +170,7 @@ fn poll_scan(app: &mut App) { r.found = found; r.show = !r.found.is_empty(); if asked && !r.show { - app.status_ok("No autosaved work to recover"); + app.status_ok(tr!("No autosaved work to recover")); } } @@ -194,15 +194,15 @@ fn restore(app: &mut App, id: String) { #[cfg(target_arch = "wasm32")] { let Some((json, meta)) = crate::web::load(&id) else { - app.status_err("That autosaved copy is gone"); + app.status_err(tr!("That autosaved copy is gone")); app.recovery.discarded(&id); return; }; - let name = meta.original.as_deref().and_then(std::path::Path::file_name).map_or_else(|| "Untitled.anicraft".to_string(), |n| n.to_string_lossy().into_owned()); + let name = meta.original.as_deref().and_then(std::path::Path::file_name).map_or_else(|| "Untitled.anicraft".to_string(), |n| n.to_string_lossy().into_owned()); // i18n-exempt: a file name let path = std::path::Path::new(RESTORED_DIR).join(&id).join(&name); match anicraft_engine::vfs::put(&path, json.into_bytes()) { Ok(()) => app.request("file.open", json!({"path": path.display().to_string(), "unsaved": true, "untitled": meta.original.is_none()})), - Err(e) => app.status_err(format!("Could not restore {name}: {e}")), + Err(e) => app.status_err(tr!("Could not restore {name}: {error}", name = name, error = e)), } } #[cfg(not(target_arch = "wasm32"))] @@ -218,7 +218,7 @@ fn discard(app: &mut App, id: String) { { crate::web::discard(&id); app.recovery.discarded(&id); - app.status_ok("Discarded the autosaved copy"); + app.status_ok(tr!("Discarded the autosaved copy")); } #[cfg(not(target_arch = "wasm32"))] { @@ -244,7 +244,7 @@ pub fn tick(app: &mut App, ctx: &egui::Context) { } Outcome::Failed { error, .. } => { if !app.recovery.failed { - app.status_err(format!("Autosave failed: {error}. Save your work to be safe; AniCraft will keep trying.")); + app.status_err(tr!("Autosave failed: {error}. Save your work to be safe; AniCraft will keep trying.", error = error)); } app.recovery.failed = true; app.recovery.written = None; @@ -289,12 +289,12 @@ pub fn tick(app: &mut App, ctx: &egui::Context) { /// "just now", "4 min ago", "2 h ago", "3 days ago". pub fn ago(secs: u64) -> String { match secs { - 0..60 => "just now".into(), - 60..3600 => format!("{} min ago", secs / 60), - 3600..86400 => format!("{} h ago", secs / 3600), + 0..60 => tr!("just now").into(), + 60..3600 => trn!("{n} min ago", "{n} min ago", secs / 60), + 3600..86400 => trn!("{n} h ago", "{n} h ago", secs / 3600), _ => { let d = secs / 86400; - if d == 1 { "yesterday".into() } else { format!("{d} days ago") } + if d == 1 { tr!("yesterday").into() } else { trn!("{n} day ago", "{n} days ago", d) } } } } @@ -305,7 +305,7 @@ pub fn status(app: &App, now: f64) -> Option { return None; } let at = app.recovery.last_copy_at?; - Some(format!("autosaved {}", ago((now - at).max(0.0) as u64))) + Some(tr!("autosaved {when}", when = ago((now - at).max(0.0) as u64))) } /// Two made-up left-behind documents, for `--open recovery` screenshots. @@ -318,6 +318,7 @@ pub fn sample_entries() -> Vec { bytes: 0, }; let walk = if crate::platform::OS == crate::platform::Os::Windows { "C:\\Users\\you\\Documents\\walk-cycle.anicraft" } else { "/home/you/Documents/walk-cycle.anicraft" }; + // i18n-exempt: document names, as the engine records them vec![entry("sample-1", "walk-cycle.anicraft", Some(walk), 240, 48, 2), entry("sample-2", "Untitled", None, 3 * 3600, 120, 1)] } @@ -342,7 +343,9 @@ pub fn window(app: &mut App, ctx: &egui::Context) { let n = app.recovery.found.len(); let confirm = app.recovery.confirm_discard.clone(); let btn = egui::vec2(96.0, crate::theme::TARGET + 4.0); - let shown = egui::Window::new("Recover unsaved work") + let title = tr!("Recover unsaved work"); + let shown = egui::Window::new(title) + .id(egui::Id::new("recover_window")) .open(&mut open) .collapsible(false) .resizable(false) @@ -351,11 +354,11 @@ pub fn window(app: &mut App, ctx: &egui::Context) { .default_width(520.0) .show(ctx, |ui| { ui.set_width(520.0); - let lead = if n == 1 { - "AniCraft didn't close properly last time. This document had changes that weren't saved:" - } else { - "AniCraft didn't close properly last time. These documents had changes that weren't saved:" - }; + let lead = trn!( + "AniCraft didn't close properly last time. This document had changes that weren't saved:", + "AniCraft didn't close properly last time. These documents had changes that weren't saved:", + n + ); ui.label(text(Type::Body, lead).color(T.text_dim)); ui.add_space(8.0); for e in &app.recovery.found { @@ -364,55 +367,60 @@ pub fn window(app: &mut App, ctx: &egui::Context) { ui.horizontal(|ui| { ui.vertical(|ui| { ui.label(text(Type::Body, e.meta.name.clone()).strong()); - let scenes = if e.meta.scenes > 1 { format!(" · {} scenes", e.meta.scenes) } else { String::new() }; - ui.label(text(Type::Caption, format!("Autosaved {} · {} frames{scenes}", ago(now.saturating_sub(e.meta.saved_at)), e.meta.frames))); + let when = ago(now.saturating_sub(e.meta.saved_at)); + let detail = if e.meta.scenes > 1 { + trn!("Autosaved {when} · {n} frame · {scenes} scenes", "Autosaved {when} · {n} frames · {scenes} scenes", e.meta.frames, when = when, scenes = e.meta.scenes) + } else { + trn!("Autosaved {when} · {n} frame", "Autosaved {when} · {n} frames", e.meta.frames, when = when) + }; + ui.label(text(Type::Caption, detail)); match &e.meta.original { Some(o) => { ui.label(text(Type::Path, o.display().to_string()).color(T.text_faint)); } None => { - ui.label(text(Type::Caption, "Never saved")); + ui.label(text(Type::Caption, tr!("Never saved"))); } } if e.original_is_newer() { - ui.label(text(Type::Caption, "The file was saved after this copy, so it opens as a new document and Save asks for a name.").color(T.error)); + ui.label(text(Type::Caption, tr!("The file was saved after this copy, so it opens as a new document and Save asks for a name.")).color(T.error)); } }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if confirm.as_deref() == Some(e.session.as_str()) { - let discard = egui::Button::new(text(Type::Body, "Discard").color(T.on_fill).strong()).fill(T.danger).min_size(btn); + let discard = egui::Button::new(text(Type::Body, tr!("Discard")).color(T.on_fill).strong()).fill(T.danger).min_size(btn); if ui.add(discard).clicked() { act = Some(Act::Discard(e.session.clone())); } - if ui.add(egui::Button::new("Keep").min_size(btn)).clicked() { + if ui.add(egui::Button::new(tr!("Keep")).min_size(btn)).clicked() { act = Some(Act::KeepIt); } } else { - let restore = egui::Button::new(text(Type::Body, "Restore").color(T.on_fill).strong()).fill(T.accent).min_size(btn); - if ui.add(restore).named(&format!("Restore {}", e.meta.name)).on_hover_text("Open it as unsaved work").clicked() { + let restore = egui::Button::new(text(Type::Body, tr!("Restore")).color(T.on_fill).strong()).fill(T.accent).min_size(btn); + if ui.add(restore).named(&tr!("Restore {name}", name = e.meta.name)).on_hover_text(tr!("Open it as unsaved work")).clicked() { act = Some(Act::Restore(e.session.clone())); } - if ui.add(egui::Button::new("Discard…").min_size(btn)).named(&format!("Discard {}…", e.meta.name)).on_hover_text("Delete this autosaved copy").clicked() { + if ui.add(egui::Button::new(tr!("Discard…")).min_size(btn)).named(&tr!("Discard {name}…", name = e.meta.name)).on_hover_text(tr!("Delete this autosaved copy")).clicked() { act = Some(Act::AskDiscard(e.session.clone())); } } }); }); if confirm.as_deref() == Some(e.session.as_str()) { - ui.label(text(Type::Caption, "Discarding deletes this work for good. This cannot be undone.").color(T.error)); + ui.label(text(Type::Caption, tr!("Discarding deletes this work for good. This cannot be undone.")).color(T.error)); } }); ui.add_space(6.0); } ui.add_space(4.0); ui.horizontal(|ui| { - if ui.add(egui::Button::new("Later").min_size(btn)).clicked() { + if ui.add(egui::Button::new(tr!("Later")).min_size(btn)).clicked() { act = Some(Act::Later); } - ui.label(text(Type::Caption, "Later keeps them: File › Recover Autosaved Documents… brings this back.")); + ui.label(text(Type::Caption, tr!("Later keeps them: File › Recover Autosaved Documents… brings this back."))); }); }); - crate::a11y::name_title_bar(&shown, "Recover unsaved work"); + crate::a11y::name_title_bar(&shown, title); if !open { act = Some(Act::Later); } @@ -428,7 +436,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) { Some(Act::Later) => { app.recovery.show = false; app.recovery.confirm_discard = None; - app.status_ok("Kept the autosaved work. File › Recover Autosaved Documents… brings it back."); + app.status_ok(tr!("Kept the autosaved work. File › Recover Autosaved Documents… brings it back.")); } None => {} } diff --git a/src/bone_tool.rs b/src/bone_tool.rs new file mode 100644 index 00000000..fff28374 --- /dev/null +++ b/src/bone_tool.rs @@ -0,0 +1,275 @@ +//! The Bone tool and armatures on the stage (ADR 0043). +//! +//! Bones show over the artwork of every visible armature layer as wedges, wide at the round +//! joint they turn about and narrowing to a smaller round end, in the layer's colour; the +//! selected bone in the selection colour. With the **Bone tool** a drag from one symbol +//! instance to another adds a bone (a drag starting on a bone's end continues the chain from +//! it), and a click picks a bone. With the **Selection tool** a drag on a bone, or on an +//! instance a bone moves, poses the armature by inverse kinematics; a drag on the root instance +//! moves the whole armature. Each drag is one undo step, and the pose keys the frame. + +use crate::app::{App, Drag, Tool}; +use crate::pathtools::Xf; +use crate::theme::{T, to_color32}; +use anicraft_engine::doc::armature::{self, BoneAt}; +use anicraft_engine::doc::{BoneId, ElementId, ElementKind, LayerId, LayerKind, evaluate_layer_elements}; +use anicraft_engine::geom::Vec2; +use egui::{Color32, Key, Modifiers, Pos2, Stroke, pos2}; +use serde_json::json; + +/// How close (screen points) a press must be to a bone's end to grab it, or to its wedge. +const GRAB_END: f32 = 8.0; +const GRAB_BODY: f32 = 6.0; +/// Joint radius on screen, and the widest a wedge gets. +const JOINT: f32 = 5.0; +const END: f32 = 3.5; +const WIDE: f32 = 9.0; + +/// One armature as the stage shows it at the playhead. +pub struct Shown { + pub layer: LayerId, + pub color: egui::Color32, + pub locked: bool, + pub bones: Vec, +} + +/// Every visible armature on the scene at the playhead, bottom layer first. +pub fn shown(app: &App) -> Vec { + let tl = app.s.doc.timeline(app.s.scene); + tl.layers + .iter() + .enumerate() + .rev() + .filter(|(i, l)| l.kind == LayerKind::Armature && l.visible && !tl.hidden_by_folder(*i)) + .filter_map(|(_, l)| { + let arm = l.armature.as_deref()?; + let (_, els) = evaluate_layer_elements(l, app.s.frame)?; + let pose = armature::pose_at(l, app.s.frame).unwrap_or_default(); + Some(Shown { layer: l.id, color: to_color32(l.color), locked: l.locked || tl.locked_by_folder(l.id), bones: armature::bones_at(arm, &els, &pose) }) + }) + .collect() +} + +/// What part of a bone a point is on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Part { + End, + Body, +} + +/// The bone under screen point `p` (ends before bodies, top layer first) on an unlocked +/// armature. +pub fn hit(app: &App, xf: Xf, p: Pos2) -> Option<(LayerId, BoneId, Part)> { + let all = shown(app); + let open = || all.iter().rev().filter(|s| !s.locked); + for s in open() { + if let Some(b) = s.bones.iter().find(|b| xf.to_screen(b.tail).distance(p) <= GRAB_END) { + return Some((s.layer, b.id, Part::End)); + } + } + for s in open() { + if let Some(b) = s.bones.iter().find(|b| segment_distance(p, xf.to_screen(b.head), xf.to_screen(b.tail)) <= GRAB_BODY) { + return Some((s.layer, b.id, Part::Body)); + } + } + None +} + +fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 { + let (ab, ap) = (b - a, p - a); + let t = if ab.length_sq() > 0.0 { (ap.dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + (a + ab * t).distance(p) +} + +/// The topmost symbol instance under stage point `sp` other than `skip`, on an unlocked layer: +/// its layer and id. +fn instance_at(app: &App, sp: Vec2, slop: f32, skip: Option) -> Option<(LayerId, ElementId)> { + let dl = app.s.display_list(); + let tl = app.s.doc.timeline(app.s.scene); + for item in dl.items.iter().rev() { + if Some(item.element) == skip || item.guide || item.masks.is_some() { + continue; + } + let Some(layer) = tl.layer(item.layer).filter(|l| !l.locked && !tl.locked_by_folder(l.id)) else { continue }; + if item.clip.is_some_and(|c| !dl.clip_contains(c, sp)) { + continue; + } + let hw = item.stroke.as_ref().map_or(0.0, |s| s.reach() * item.transform.mean_scale()); + let inside = item.fill.is_some() && item.path.contains(sp, &item.transform, item.fill_rule); + if !(inside || item.path.distance_to_edge(sp, &item.transform) <= hw + slop) { + continue; + } + let is_instance = evaluate_layer_elements(layer, app.s.frame).is_some_and(|(_, els)| els.iter().any(|e| e.id == item.element && matches!(e.kind, ElementKind::Symbol { .. }))); + if is_instance { + return Some((layer.id, item.element)); + } + } + None +} + +/// Selects bone `bone` on armature layer `layer` (its layer becomes the active one). +pub fn select(app: &mut App, layer: LayerId, bone: Option) { + app.bone_sel = bone; + if bone.is_some() && app.s.layer != layer { + app.run("layer.select", json!({"layer": layer.0})); + } +} + +/// A Bone tool drag starting at screen point `press`: a new bone from the instance there (or +/// from the end of the bone there). +pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag { + let sp = xf.to_stage(press); + if let Some((layer, id, Part::End)) = hit(app, xf, press) + && let Some(child) = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(id)).map(|b| b.child) + && let Some(b) = shown(app).into_iter().find(|s| s.layer == layer).and_then(|s| s.bones.into_iter().find(|b| b.id == id)) + { + // A chain joins end to start. + let head = pos2(b.tail.x, b.tail.y); + return Drag::Bone { from: child, head, cur: head }; + } + match instance_at(app, sp, 3.0 / xf.zoom.max(1e-3), None) { + Some((_, from)) => Drag::Bone { from, head: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) }, + None => { + app.status_ok(tr!("Start a bone on a symbol instance (convert artwork with F8), then drag to the instance it moves.")); + Drag::None + } + } +} + +/// Ends a Bone tool drag: adds the bone if it ends on another instance. +pub fn drag_end(app: &mut App, xf: Xf, from: ElementId, head: Pos2, cur: Pos2) { + let tail = Vec2::new(cur.x, cur.y); + let Some((_, to)) = instance_at(app, tail, 3.0 / xf.zoom.max(1e-3), Some(from)) else { + app.status_ok(tr!("A bone ends on another symbol instance: release over the instance it should move.")); + return; + }; + if let Some(v) = app.run("bone.add", json!({"from": from.0, "to": to.0, "head": [head.x, head.y], "tail": [tail.x, tail.y]})) { + let (layer, bone) = (LayerId(v["layer"].as_u64().unwrap_or(0)), v["bone"].as_u64().map(BoneId)); + select(app, layer, bone); + app.status_ok("Added a bone. Drag a bone or an instance with the Selection tool to pose the armature. Ctrl+Z to undo."); + } +} + +/// A Bone tool click: picks the bone there (or none). +pub fn click(app: &mut App, xf: Xf, p: Pos2) { + match hit(app, xf, p) { + Some((layer, id, _)) => select(app, layer, Some(id)), + None => app.bone_sel = None, + } +} + +/// A Selection tool drag starting at screen point `press` on an armature: posing (on a bone, or +/// an instance a bone moves) or moving the whole armature (on its root). `None` when the press +/// isn't on an armature. +pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option { + let sp = xf.to_stage(press); + let tl = app.s.doc.timeline(app.s.scene); + let (layer, bone, local) = match hit(app, xf, press) { + Some((layer, id, _)) => (layer, Some(id), None), + None => { + let (layer, el) = instance_at(app, sp, 3.0 / xf.zoom.max(1e-3), None).filter(|(l, _)| tl.layer(*l).is_some_and(|l| l.kind == LayerKind::Armature))?; + let l = tl.layer(layer)?; + let into = l.armature.as_ref().and_then(|a| a.bone_into(el)).map(|b| b.id); + // The point grabbed, in the instance's own space: it follows the pointer. + let w = evaluate_layer_elements(l, app.s.frame).and_then(|(_, els)| els.iter().find(|e| e.id == el).map(|e| e.transform))?; + (layer, into, w.inverse().map(|m| m.apply(sp))) + } + }; + match bone { + Some(id) => { + select(app, layer, Some(id)); + let arm = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.clone())?; + if armature::movable_chain(&arm, id).is_empty() { + app.status_ok(tr!("That bone is pinned (or hangs from a pinned bone): unpin it in Properties to drag it.")); + return Some(Drag::None); + } + app.s.begin_gesture(tr_noop!("Pose Armature")); + let local = local.or_else(|| arm.bone(id).map(|b| b.tail)).unwrap_or(Vec2::new(0.0, 0.0)); + Some(Drag::BonePose { bone: id, local: pos2(local.x, local.y) }) + } + None => { + select(app, layer, None); + app.run("layer.select", json!({"layer": layer.0})); + app.s.begin_gesture(tr_noop!("Move Armature")); + Some(Drag::ArmatureMove { layer, last: pos2(sp.x, sp.y) }) + } + } +} + +/// Continues a pose or armature drag to stage point `c`. +pub fn drag_to(app: &mut App, drag: &mut Drag, c: Pos2) { + match drag { + Drag::BonePose { bone, local } => { + app.run("bone.solve", json!({"bone": bone.0, "x": c.x, "y": c.y, "local": [local.x, local.y]})); + } + Drag::ArmatureMove { layer, last } => { + let d = c - *last; + if d.length_sq() > 0.0 { + *last = c; + app.run("bone.pose", json!({"layer": layer.0, "dx": d.x, "dy": d.y})); + } + } + Drag::Bone { cur, .. } => *cur = c, + _ => {} + } +} + +/// Delete removes the selected bone (and those below it); Esc deselects it. +pub fn consume_keys(app: &mut App, ctx: &egui::Context) { + let Some(id) = app.bone_sel else { return }; + if !matches!(app.tool, Tool::Bone | Tool::Select) { + return; + } + let take = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); + if take(Key::Delete) || take(Key::Backspace) { + app.request("bone.remove", json!({"bone": id.0})); + } else if take(Key::Escape) { + app.bone_sel = None; + } +} + +/// Drops a selected bone that no longer exists. +pub fn upkeep(app: &mut App) { + if let Some(id) = app.bone_sel { + let tl = app.s.doc.timeline(app.s.scene); + if !tl.layers.iter().any(|l| l.kind == LayerKind::Armature && l.armature.as_ref().is_some_and(|a| a.bone(id).is_some())) { + app.bone_sel = None; + } + } +} + +/// The bones of every visible armature, and the bone being drawn. +pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) { + let tool = matches!(app.tool, Tool::Bone | Tool::Select); + for s in shown(app) { + for b in &s.bones { + let picked = app.bone_sel == Some(b.id); + let color = if picked { T.selection } else { s.color }; + // Bones fade when they can't be edited (another tool, a locked layer). + let color = if tool && !s.locked { color } else { color.gamma_multiply(0.5) }; + wedge(painter, xf.to_screen(b.head), xf.to_screen(b.tail), color, picked); + } + } + if let Drag::Bone { head, cur, .. } = app.drag { + let (a, b) = (xf.to_screen(Vec2::new(head.x, head.y)), xf.to_screen(Vec2::new(cur.x, cur.y))); + wedge(painter, a, b, T.selection, true); + } +} + +/// A bone from joint `a` to end `b` on screen: a wedge, widest just past the joint, with a +/// round joint and a smaller round end. +fn wedge(painter: &egui::Painter, a: Pos2, b: Pos2, color: Color32, strong: bool) { + let d = b - a; + let len = d.length(); + let edge = Stroke::new(if strong { 1.5 } else { 1.0 }, color); + if len > JOINT * 2.0 { + let dir = d / len; + let n = egui::vec2(-dir.y, dir.x); + let w = (len * 0.12).clamp(JOINT, WIDE); + let shoulder = a + dir * (w * 1.2).min(len * 0.3); + let pts = vec![a, shoulder + n * w, b, shoulder - n * w]; + painter.add(egui::Shape::convex_polygon(pts, color.gamma_multiply(if strong { 0.55 } else { 0.35 }), edge)); + } + painter.circle(a, JOINT, Color32::WHITE, edge); + painter.circle(b, END, Color32::WHITE, edge); +} diff --git a/src/brushtool.rs b/src/brushtool.rs index 8a0eafc6..71d2e272 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -68,11 +68,11 @@ pub fn resize(app: &mut App, larger: bool) { match app.tool { Tool::Brush => { app.brush.size = step_size(app.brush.size, larger); - app.status_ok(format!("Brush size {} px", app.brush.size)); + app.status_ok(tr!("Brush size {size} px", size = app.brush.size)); } Tool::Eraser => { app.eraser.size = step_size(app.eraser.size, larger); - app.status_ok(format!("Eraser size {} px", app.eraser.size)); + app.status_ok(tr!("Eraser size {size} px", size = app.eraser.size)); } _ => {} } @@ -133,7 +133,7 @@ pub fn commit(app: &mut App, xf: Xf) { if let Some(v) = app.run("draw.brush", params) && v["elements"].as_array().is_some_and(Vec::is_empty) { - app.status_ok("Nothing to paint behind there: Paint Behind only paints empty areas."); + app.status_ok(tr!("Nothing to paint behind there: Paint Behind only paints empty areas.")); } } diff --git a/src/camera_tool.rs b/src/camera_tool.rs index cb2dfea6..fb322a87 100644 --- a/src/camera_tool.rs +++ b/src/camera_tool.rs @@ -49,7 +49,7 @@ pub fn previewing(app: &App) -> bool { /// pick: undoing the add leaves the tool in hand without adding it again. pub fn on_tool_change(app: &mut App) { if app.tool == Tool::Camera && app.last_tool != Tool::Camera && app.s.doc.timeline(app.s.scene).camera_layer().is_none() && app.run("camera.add", json!({})).is_some() { - app.status_ok("Added a camera. Drag on the stage to pan it, turn it with the round handle, zoom with the wheel. Ctrl+Z to undo."); + app.status_ok(tr!("Added a camera. Drag on the stage to pan it, turn it with the round handle, zoom with the wheel. {undo} to undo.", undo = app.undo_key())); } app.last_tool = app.tool; } @@ -78,11 +78,12 @@ pub fn drag_start(app: &mut App, g: &Geo, press: Pos2) -> Drag { let Some(cam) = camera(app) else { return Drag::None }; let (centre, _, _) = handles(&cam, app, g); if on_knob(app, g, press) { - app.s.begin_gesture("Rotate Camera"); + // Undo labels stay English in the history and are translated where they show. + app.s.begin_gesture(tr_noop!("Rotate Camera")); let d = press - centre; Drag::CameraRotate { last: d.y.atan2(d.x) } } else { - app.s.begin_gesture("Move Camera"); + app.s.begin_gesture(tr_noop!("Move Camera")); Drag::CameraPan { last: press } } } @@ -128,7 +129,7 @@ pub fn wheel(app: &mut App, scroll_y: f32, now: f64) { return; } if !matches!(app.drag, Drag::CameraWheel { .. }) { - app.s.begin_gesture("Zoom Camera"); + app.s.begin_gesture(tr_noop!("Zoom Camera")); } app.drag = Drag::CameraWheel { until: now + WHEEL_BURST }; let by = (scroll_y * 0.0025).clamp(-0.5, 0.5).exp(); diff --git a/src/dialogs.rs b/src/dialogs.rs index 9c25539f..30041185 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -44,28 +44,29 @@ fn confirm_modal(app: &mut App, ctx: &egui::Context) { 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())); + // The engine's English, translated when a catalog has that exact text. + ui.label(text(Type::Title, crate::i18n::t_dyn(&p.conf.title))); ui.add_space(6.0); - ui.label(text(Type::Body, p.conf.message.clone()).color(T.text_dim)); + ui.label(text(Type::Body, crate::i18n::t_dyn(&p.conf.message)).color(T.text_dim)); ui.add_space(4.0); if irreversible { - ui.label(text(Type::Caption, "This cannot be undone.").color(T.error)); + ui.label(text(Type::Caption, tr!("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)); + crate::theme::checkbox(ui, &mut p.dont_ask, text(Type::Caption, tr!("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() { + if ui.add(egui::Button::new(tr!("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() { + if ui.add(danger_button(&crate::i18n::t_dyn(&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" }; + let hint = if irreversible { tr!("Esc cancels · click the red button to proceed") } else { tr!("Enter confirms · Esc cancels") }; ui.label(text(Type::Caption, hint)); }); // Irreversible actions are never one keystroke away: Enter does not confirm them. @@ -91,7 +92,7 @@ fn confirm_modal(app: &mut App, ctx: &egui::Context) { Some(false) => { app.confirm = None; app.close_after_save = false; - app.status_ok("Cancelled"); + app.status_ok(tr!("Cancelled")); } None => {} } @@ -108,27 +109,27 @@ fn close_modal(app: &mut App, ctx: &egui::Context) { 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()); + let name = app.s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| tr!("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.label(text(Type::Title, tr!("Save changes to “{name}” before closing?", name = name))); 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.label(text(Type::Body, tr!("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() { + if ui.add(danger_button(tr!("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(T.on_fill)).fill(T.accent).min_size(egui::vec2(96.0, crate::theme::TARGET + 4.0))).clicked() { + if ui.add(egui::Button::new(text(Type::Body, tr!("Save")).strong().color(T.on_fill)).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() { + if ui.add(egui::Button::new(tr!("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")); + ui.label(text(Type::Caption, tr!("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 { @@ -168,18 +169,24 @@ enum Entry { } impl Entry { - fn title(&self) -> String { + /// The menu path to the entry, in the interface language (`local`) or in English, so + /// either finds it. + fn title(&self, local: bool) -> String { + let t = |s: &'static str| if local { crate::i18n::t(s) } else { s }; + let path = |parts: &[&'static str], last: &str| { + let mut v: Vec<&str> = parts.iter().map(|p| t(p)).collect(); + v.push(last); + v.join(" › ") + }; match self { Entry::Command(c) => { - if c.menu.is_empty() { - c.label.to_string() - } else { - format!("{} › {}", c.menu.replace('/', " › "), c.label) - } + let label = if local { crate::i18n::t_cmd(c.id, c.label) } else { c.label }; + path(&c.menu.split('/').filter(|m| !m.is_empty()).collect::>(), label) } - Entry::Tool(t) => format!("Tool › {}", t.label()), - Entry::View(name, _, _) => format!("View › {name}"), - Entry::Plugin(_, label) => format!("Commands › Plug-ins › {label}"), + Entry::Tool(tool) => path(&[tr_noop!("Tool")], t(tool.label())), + Entry::View(name, _, _) => path(&[tr_noop!("View")], t(name)), + // The plug-in's own name: not ours to translate. + Entry::Plugin(_, label) => path(&[tr_noop!("Commands"), tr_noop!("Plug-ins")], label), } } fn shortcut(&self, km: &crate::keymap::Keymap) -> String { @@ -204,14 +211,15 @@ fn runnable(c: &CommandSpec) -> bool { 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("Preview Through Camera", "", App::toggle_camera_preview)); - 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)); + // English keys, translated where they are drawn (`Entry::title`). + v.push(Entry::View(tr_noop!("Play / Stop"), "Enter", App::toggle_play)); + v.push(Entry::View(tr_noop!("Onion Skin"), "", crate::onion::toggle_ghosts)); + v.push(Entry::View(tr_noop!("Preview Through Camera"), "", App::toggle_camera_preview)); + v.push(Entry::View(tr_noop!("Fit Stage in Window"), "Ctrl+0", |a| a.view.fit = true)); + v.push(Entry::View(tr_noop!("Keyboard Shortcuts"), "F1", |a| a.show_shortcuts = true)); + v.push(Entry::View(tr_noop!("Project Files & Docs"), "", |a| a.show_files = true)); + v.push(Entry::View(tr_noop!("Licenses & Notices"), "", |a| a.show_licenses = true)); + v.push(Entry::View(tr_noop!("Preferences"), "Ctrl+U", App::open_prefs)); v } @@ -237,10 +245,13 @@ fn palette(app: &mut App, ctx: &egui::Context) { let Some(p) = &mut app.palette else { return }; let mut all = entries(); all.extend(app.s.plugins.list().filter(|p| crate::plugins_ui::is_command(p)).map(|p| Entry::Plugin(p.id().to_string(), crate::plugins_ui::label(p)))); + // Found by its name in the interface language or in English, whichever matches better. 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)) + let local = fuzzy(&p.query, &format!("{} {key}", e.title(true))); + let english = if crate::i18n::code() == crate::i18n::ENGLISH { None } else { fuzzy(&p.query, &format!("{} {key}", e.title(false))) }; + local.max(english).map(|s| (s, e, key)) }).collect(); matches.sort_by_key(|m| std::cmp::Reverse(m.0)); matches.truncate(14); @@ -265,20 +276,20 @@ fn palette(app: &mut App, ctx: &egui::Context) { 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)).named("Command palette"); + let r = ui.add(egui::TextEdit::singleline(&mut p.query).hint_text(tr!("Type a command, tool or setting…")).desired_width(f32::INFINITY).font(egui::TextStyle::Heading)).named(tr!("Command palette")); 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")); + ui.label(text(Type::Caption, tr!("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()); + let lab = ui.selectable_label(sel, e.title(true)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.label(text(Type::Key, crate::platform::shortcut_label(key))); }); @@ -290,7 +301,7 @@ fn palette(app: &mut App, ctx: &egui::Context) { } } ui.add_space(4.0); - ui.label(text(Type::Caption, "Up/Down choose · Enter run · Esc close")); + ui.label(text(Type::Caption, tr!("Up/Down choose · Enter run · Esc close"))); }); }); if enter { @@ -318,21 +329,21 @@ fn font_picker(ui: &mut egui::Ui, id: &str, name: &str, current: &FontChoice, fa let mut picked = None; let filter_id = egui::Id::new(("font_filter", id)); let shown = match current { - FontChoice::Bundled => format!("Default ({bundled})"), + FontChoice::Bundled => tr!("Default ({font})", font = 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() { + if ui.selectable_label(*current == FontChoice::Bundled, text(Type::Body, tr!("Default (bundled: {font})", font = bundled))).clicked() { picked = Some(FontChoice::Bundled); } ui.separator(); match families { None => { - ui.label(text(Type::Caption, "Scanning installed fonts…")); + ui.label(text(Type::Caption, tr!("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)).set_name("Filter fonts"); + ui.add(egui::TextEdit::singleline(&mut filter).hint_text(tr!("Filter fonts…")).desired_width(240.0)).set_name(tr!("Filter fonts")); 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)) { @@ -360,8 +371,10 @@ fn preferences(app: &mut App, ctx: &egui::Context) { 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" }; + let title = if crate::platform::OS == crate::platform::Os::Mac { tr!("Settings") } else { tr!("Preferences") }; let shown = egui::Window::new(title) + // An id of its own: the window keeps its place when the language changes. + .id(egui::Id::new("prefs_window")) .open(&mut open) .collapsible(false) .resizable(false) @@ -379,41 +392,63 @@ fn preferences(app: &mut App, ctx: &egui::Context) { // (`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, "Theme", |ui| { + section(ui, "prefs_appearance", Section::Rule, tr!("Appearance"), None, |ui| { + // The interface language (ADR 0040): first, so someone who can't read the + // current one finds it at the top. Each language is named in itself. + form_row(ui, LW, tr!("Language"), |ui| { + let auto = crate::i18n::AUTO; + let current = if p.language == auto { tr!("System language ({name})", name = crate::i18n::system_choice()) } else { crate::i18n::name_of(&p.language).into_owned() }; + egui::ComboBox::from_id_salt("pref_language").width(260.0).selected_text(text(Type::Body, current)).show_ui(ui, |ui| { + ui.selectable_value(&mut p.language, auto.to_string(), text(Type::Body, tr!("System language ({name})", name = crate::i18n::system_choice()))); + ui.separator(); + for (code, name) in crate::i18n::offered() { + ui.selectable_value(&mut p.language, code.to_string(), text(Type::Body, name)); + } + }) + .response + .set_name(tr!("Interface language")); + }); + let note = if crate::i18n::offered().len() <= 2 { + tr!("This build has the interface in English only. Builds with translations list their languages here.") + } else { + tr!("Menus, panels and dialogs. Your documents, layer names and the command line stay as they are.") + }; + form_note(ui, LW, text(Type::Caption, note)); + ui.add_space(4.0); + form_row(ui, LW, tr!("Theme"), |ui| { ui.vertical(|ui| { for (palette, name, tip) in crate::theme::Palette::ALL { - crate::theme::radio_value(ui, &mut p.theme, palette, text(Type::Body, name)); - form_note(ui, toggle_indent, text(Type::Caption, tip)); + crate::theme::radio_value(ui, &mut p.theme, palette, text(Type::Body, crate::i18n::t(name))); + form_note(ui, toggle_indent, text(Type::Caption, crate::i18n::t(tip))); ui.add_space(2.0); } }); }); ui.add_space(4.0); - form_row(ui, LW, "Interface font", |ui| { - if let Some(c) = font_picker(ui, "pref_ui_font", "Interface font", &p.ui_font, sys.as_ref().map(|s| s.families.as_slice()), bundled_ui) { + form_row(ui, LW, tr!("Interface font"), |ui| { + if let Some(c) = font_picker(ui, "pref_ui_font", tr!("Interface 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| { + form_row(ui, LW, tr!("Data font"), |ui| { let list = sys.as_ref().map(|s| s.monospace.as_slice()); - if let Some(c) = font_picker(ui, "pref_data_font", "Data font", &p.data_font, list, bundled_mono) { + if let Some(c) = font_picker(ui, "pref_data_font", tr!("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.")); + form_note(ui, LW, text(Type::Caption, tr!("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| { + form_row(ui, LW, tr!("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.label(text(Type::Body, tr!("Layer names, menus and dialog text read like this."))); + ui.label(text(Type::Data, tr!("Frame {frame} · {seconds} s · X {x} Y {y} · {keys}", frame = "0042", seconds = "1.75", x = "1280.5", y = "720.0", keys = crate::platform::shortcut_label("Ctrl+Shift+S")))); }); }); ui.add_space(4.0); - form_row(ui, LW, "Interface scale", |ui| { + form_row(ui, LW, tr!("Interface scale"), |ui| { let mut pct = p.ui_scale * 100.0; let r = with_type(ui, Type::Data, |ui| { - a11y::slider(ui, &mut pct, (crate::prefs::SCALE_RANGE.start() * 100.0)..=(crate::prefs::SCALE_RANGE.end() * 100.0), "Interface scale", a11y::SliderLook { suffix: " %", step: Some(5.0), max_decimals: Some(0), ..Default::default() }) + a11y::slider(ui, &mut pct, (crate::prefs::SCALE_RANGE.start() * 100.0)..=(crate::prefs::SCALE_RANGE.end() * 100.0), tr!("Interface scale"), a11y::SliderLook { suffix: " %", step: Some(5.0), max_decimals: Some(0), ..Default::default() }) }); // Apply on release so the slider doesn't move under the pointer while dragging. if r.drag_stopped() || (r.changed() && !r.dragged()) { @@ -422,23 +457,23 @@ fn preferences(app: &mut App, ctx: &egui::Context) { }); }); - section(ui, "prefs_stage", Section::Rule, "Stage", None, |ui| { - form_row(ui, LW, "Rendering", |ui| { + section(ui, "prefs_stage", Section::Rule, tr!("Stage"), None, |ui| { + form_row(ui, LW, tr!("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)); + crate::theme::radio_value(ui, &mut p.render_mode, mode, text(Type::Body, crate::i18n::t(name))); + form_note(ui, toggle_indent, text(Type::Caption, crate::i18n::t(tip))); ui.add_space(2.0); } }); }); if crate::gpu_stage::AVAILABLE { ui.add_space(4.0); - form_row(ui, LW, "Renderer", |ui| { + form_row(ui, LW, tr!("Renderer"), |ui| { ui.vertical(|ui| { for (choice, name, tip) in StageRenderer::ALL { - crate::theme::radio_value(ui, &mut p.stage_renderer, choice, text(Type::Body, name)); - form_note(ui, toggle_indent, text(Type::Caption, tip)); + crate::theme::radio_value(ui, &mut p.stage_renderer, choice, text(Type::Body, crate::i18n::t(name))); + form_note(ui, toggle_indent, text(Type::Caption, crate::i18n::t(tip))); ui.add_space(2.0); } }); @@ -446,13 +481,13 @@ fn preferences(app: &mut App, ctx: &egui::Context) { use crate::gpu_stage::State; let status = match app.stage_cache.gpu.state() { State::Off => None, - State::Starting => Some("Starting the graphics card…".to_string()), - State::Running { adapter, direct: true } => Some(format!("Drawing on {adapter}, straight into the window.")), - State::Running { adapter, direct: false } => Some(format!("Drawing on {adapter}, then copied to the window (slower: the window's graphics device can't be shared).")), - State::Failed(why) => Some(format!("The graphics card can't draw the stage, so the CPU does: {why}")), + State::Starting => Some(tr!("Starting the graphics card…").to_string()), + State::Running { adapter, direct: true } => Some(tr!("Drawing on {adapter}, straight into the window.", adapter = adapter)), + State::Running { adapter, direct: false } => Some(tr!("Drawing on {adapter}, then copied to the window (slower: the window's graphics device can't be shared).", adapter = adapter)), + State::Failed(why) => Some(tr!("The graphics card can't draw the stage, so the CPU does: {why}", why = why)), }; if crate::gpu_stage::wanted(p.stage_renderer) != p.stage_renderer { - form_note(ui, LW, text(Type::Caption, "ANICRAFT_STAGE_RENDERER is set, and it takes precedence over this choice.")); + form_note(ui, LW, text(Type::Caption, tr!("ANICRAFT_STAGE_RENDERER is set, and it takes precedence over this choice."))); } if let Some(s) = status { form_note(ui, LW, text(Type::Caption, s)); @@ -460,66 +495,66 @@ fn preferences(app: &mut App, ctx: &egui::Context) { } }); - section(ui, "prefs_timeline", Section::Rule, "Timeline", None, |ui| { - form_row(ui, LW, "Extra start gap", |ui| { + section(ui, "prefs_timeline", Section::Rule, tr!("Timeline"), None, |ui| { + form_row(ui, LW, tr!("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")).set_name("Extra start gap"); + ui.add(egui::DragValue::new(&mut p.timeline_start_gap).range(crate::prefs::GAP_RANGE).speed(0.5).max_decimals(0).suffix(" pt")).set_name(tr!("Extra start gap")); }); }); - 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.")); + form_note(ui, LW, text(Type::Caption, tr!("The timeline always leaves room before frame 1 for the playhead; this adds more. It stays the same at every zoom."))); }); - section(ui, "prefs_files", Section::Rule, "Files", None, |ui| { - form_row(ui, LW, "File dialogs", |ui| { + section(ui, "prefs_files", Section::Rule, tr!("Files"), None, |ui| { + form_row(ui, LW, tr!("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.")); + crate::theme::checkbox(ui, &mut p.native_dialogs, text(Type::Body, tr!("Use the system's open and save dialogs"))); + form_note(ui, toggle_indent, text(Type::Caption, tr!("Turn off on Linux desktops without an XDG desktop portal; AniCraft then asks for a path instead."))); }); }); ui.add_space(4.0); - form_row(ui, LW, "Autosave", |ui| { + form_row(ui, LW, tr!("Autosave"), |ui| { ui.vertical(|ui| { - crate::theme::checkbox(ui, &mut p.autosave, text(Type::Body, "Keep a recovery copy of unsaved work")); + crate::theme::checkbox(ui, &mut p.autosave, text(Type::Body, tr!("Keep a recovery copy of unsaved work"))); form_note( ui, toggle_indent, - text(Type::Caption, "If AniCraft closes unexpectedly, the next start offers to restore it. Copies stay in the settings folder, never over your files, and go away when you save."), + text(Type::Caption, tr!("If AniCraft closes unexpectedly, the next start offers to restore it. Copies stay in the settings folder, never over your files, and go away when you save.")), ); }); }); ui.add_enabled_ui(p.autosave, |ui| { - form_row(ui, LW, "Every", |ui| { - let shown = crate::prefs::AUTOSAVE_INTERVALS.iter().find(|(s, _)| *s == p.autosave_secs).map_or_else(|| format!("{} seconds", p.autosave_secs), |(_, l)| (*l).to_string()); + form_row(ui, LW, tr!("Every"), |ui| { + let shown = crate::prefs::AUTOSAVE_INTERVALS.iter().find(|(s, _)| *s == p.autosave_secs).map_or_else(|| trn!("{n} second", "{n} seconds", p.autosave_secs), |(_, l)| crate::i18n::t(l).to_string()); egui::ComboBox::from_id_salt("pref_autosave_secs").width(160.0).selected_text(text(Type::Body, shown)).show_ui(ui, |ui| { for (secs, label) in crate::prefs::AUTOSAVE_INTERVALS { - ui.selectable_value(&mut p.autosave_secs, secs, text(Type::Body, label)); + ui.selectable_value(&mut p.autosave_secs, secs, text(Type::Body, crate::i18n::t(label))); } }) .response - .set_name("Autosave every"); + .set_name(tr!("Autosave every")); }); - form_row(ui, LW, "Or after", |ui| { + form_row(ui, LW, tr!("Or after"), |ui| { with_type(ui, Type::Data, |ui| { - ui.add(egui::DragValue::new(&mut p.autosave_edits).range(crate::prefs::AUTOSAVE_EDITS_RANGE).speed(0.5).suffix(" changes")).set_name("Autosave after this many changes"); + ui.add(egui::DragValue::new(&mut p.autosave_edits).range(crate::prefs::AUTOSAVE_EDITS_RANGE).speed(0.5).suffix(format!(" {}", tr!("changes")))).set_name(tr!("Autosave after this many changes")); }); }); - form_note(ui, LW, text(Type::Caption, "Whichever comes first. 0 changes: by time only. Copies are written in the background, so drawing never waits.")); + form_note(ui, LW, text(Type::Caption, tr!("Whichever comes first. 0 changes: by time only. Copies are written in the background, so drawing never waits."))); }); }); - section(ui, "prefs_safety", Section::Rule, "Safety", None, |ui| { - form_row(ui, LW, "Confirmations", |ui| { + section(ui, "prefs_safety", Section::Rule, tr!("Safety"), None, |ui| { + form_row(ui, LW, tr!("Confirmations"), |ui| { let n = app.skip_confirm.len(); - if ui.add_enabled(n > 0, egui::Button::new(text(Type::Body, "Show all again"))).clicked() { + if ui.add_enabled(n > 0, egui::Button::new(text(Type::Body, tr!("Show all again")))).clicked() { reset_confirms = true; } - ui.label(text(Type::Caption, format!("{n} silenced this session"))); + ui.label(text(Type::Caption, trn!("{n} silenced this session", "{n} silenced this session", n))); }); }); }); ui.separator(); - ui.label(text(Type::Caption, format!("{} · settings stored in {}", crate::platform::OS.name(), crate::platform::settings_place()))); + ui.label(text(Type::Caption, tr!("{os} · settings stored in {place}", os = crate::platform::OS.name(), place = crate::platform::settings_place()))); }); a11y::name_title_bar(&shown, title); if reset_confirms { @@ -537,16 +572,17 @@ fn preferences(app: &mut App, ctx: &egui::Context) { // ----- licences --------------------------------------------------------------------------------- /// Licence texts compiled into the binary, so every copy of the app carries its notices. +/// Titles are English keys, translated where they are drawn; the licence texts stay as written. 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")), + (tr_noop!("NOTICE"), include_str!("../NOTICE")), + (tr_noop!("AniCraft: MIT License"), include_str!("../LICENSE-MIT")), + (tr_noop!("AniCraft: Apache License 2.0"), include_str!("../LICENSE-APACHE")), + (tr_noop!("Font: Ubuntu Light (Ubuntu Font Licence 1.0)"), include_str!("../licenses/fonts/UFL-1.0-Ubuntu-font.txt")), + (tr_noop!("Font: Hack (MIT, Bitstream Vera)"), include_str!("../licenses/fonts/LICENSE-Hack.txt")), + (tr_noop!("Font: Noto Emoji (SIL OFL 1.1)"), include_str!("../licenses/fonts/OFL-1.1-NotoEmoji.txt")), + (tr_noop!("Font: emoji-icon-font (MIT)"), include_str!("../licenses/fonts/LICENSE-emoji-icon-font.txt")), + (tr_noop!("Icons: Lucide (ISC)"), include_str!("../licenses/icons/LICENSE-lucide.txt")), + (tr_noop!("Rust crates: licence inventory"), include_str!("../docs/legal/third-party-inventory.txt")), ]; fn licenses(app: &mut App, ctx: &egui::Context) { @@ -554,7 +590,9 @@ fn licenses(app: &mut App, ctx: &egui::Context) { return; } let mut open = true; - let shown = egui::Window::new("Licenses & Notices") + let title = tr!("Licenses & Notices"); + let shown = egui::Window::new(title) + .id(egui::Id::new("licenses_window")) .open(&mut open) .collapsible(false) .pivot(egui::Align2::CENTER_CENTER) @@ -562,21 +600,21 @@ fn licenses(app: &mut App, ctx: &egui::Context) { .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, tr!("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.") + text(Type::Body, tr!("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| { + egui::CollapsingHeader::new(crate::i18n::t(title)).id_salt(("notice", *title)).default_open(*title == "NOTICE").show(ui, |ui| { ui.add(egui::Label::new(text(Type::Path, *body)).wrap()); }); } }); }); - a11y::name_title_bar(&shown, "Licenses & Notices"); + a11y::name_title_bar(&shown, title); if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { open = false; } @@ -598,6 +636,7 @@ pub struct KeyCapture { struct SheetState { filter: String, notice: Option<(String, bool)>, + /// The capture, the chord, and the id of the action that has it now. steal: Option<(KeyCapture, String, &'static str)>, confirm_reset_all: bool, } @@ -611,29 +650,63 @@ enum SheetAct { Dismiss, } -/// Fixed keys: handled before the shortcut map, shown read-only. +/// Fixed keys: handled before the shortcut map, shown read-only. Groups and names are English +/// keys (groups match [`GROUP_ORDER`]), translated where they are drawn. fn fixed_rows() -> Vec<(&'static str, &'static str, Vec<&'static str>)> { - let quit = if crate::platform::OS == crate::platform::Os::Mac { "Quit" } else { "Exit" }; + let quit = if crate::platform::OS == crate::platform::Os::Mac { tr_noop!("Quit") } else { tr_noop!("Exit") }; + let (essentials, view, editing) = (tr_noop!("Essentials"), tr_noop!("View"), tr_noop!("Editing")); + // Keys in registry notation; the words among them are translated by `fixed_key`. 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"]), + (essentials, tr_noop!("Command palette"), vec!["Ctrl+K"]), + (essentials, tr_noop!("Keyboard shortcuts (this editor)"), vec!["F1", "Ctrl+Alt+Shift+K"]), + (essentials, tr_noop!("Play / Stop"), vec!["Enter"]), + (essentials, tr_noop!("Preferences"), vec!["Ctrl+U", "Ctrl+,"]), + (essentials, quit, vec!["Ctrl+Q"]), + (view, tr_noop!("Zoom in / out"), vec!["Ctrl+=", "Ctrl+-"]), + (view, tr_noop!("Fit stage in window"), vec!["Ctrl+0"]), + (view, tr_noop!("Actual size (100%)"), vec!["Ctrl+1"]), + (view, tr_noop!("Zoom at the cursor"), vec!["Ctrl+Wheel"]), + (view, tr_noop!("Pan with any tool"), vec!["Space+Drag", "Middle-drag"]), // i18n-exempt: keys, see fixed_key + (editing, tr_noop!("Nudge selection 1 px"), vec!["Arrow keys"]), // i18n-exempt: keys, see fixed_key + (editing, tr_noop!("Nudge selection 10 px"), vec!["Shift+Arrow keys"]), + (editing, tr_noop!("Add to / remove from selection"), vec!["Shift+Click"]), + (editing, tr_noop!("Constrain shape / 45° line"), vec!["Shift+Drag"]), + (editing, tr_noop!("Context actions"), vec!["Right-click"]), // i18n-exempt: keys, see fixed_key ] } -const GROUP_ORDER: [&str; 13] = ["Essentials", "Tools", "File", "Edit", "View", "Insert", "Modify", "Commands", "Control", "Window", "Help", "Other", "Editing"]; +/// A fixed key as shown: the platform's modifier names, and the pointer gestures and key +/// groups that are words (not key names) in the interface language. +fn fixed_key(k: &str) -> String { + let (mods, last) = k.rsplit_once('+').unwrap_or(("", k)); + let word = match last { + "Wheel" => tr!("Wheel"), + "Drag" => tr!("Drag"), + "Middle-drag" => tr!("Middle-drag"), + "Arrow keys" => tr!("Arrow keys"), + "Click" => tr!("Click"), + "Right-click" => tr!("Right-click"), + other => other, + }; + crate::platform::shortcut_label(&if mods.is_empty() { word.to_string() } else { format!("{mods}+{word}") }) +} + +/// Section order, by group key (English; the titles are translated where they are drawn). +const GROUP_ORDER: [&str; 13] = [ + tr_noop!("Essentials"), + tr_noop!("Tools"), + tr_noop!("File"), + tr_noop!("Edit"), + tr_noop!("View"), + tr_noop!("Insert"), + tr_noop!("Modify"), + tr_noop!("Commands"), + tr_noop!("Control"), + tr_noop!("Window"), + tr_noop!("Help"), + tr_noop!("Other"), + tr_noop!("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) { @@ -643,8 +716,13 @@ fn name_cell(ui: &mut egui::Ui, label: &str) { }); } +/// An action's name in the interface language (a command's as in the menus). +fn action_name(a: &crate::keymap::Action) -> &'static str { + crate::i18n::t_cmd(a.id, a.label) +} + 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) + km.actions.iter().find(|a| a.id == id).map_or_else(|| tr!("this action"), action_name) } /// The next key press while recording, with every other key event taken out of the frame. @@ -685,17 +763,17 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { 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)); + st.notice = Some((tr!("{action}: {key}", action = action_label(&app.keymap, cap.id), key = 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::Taken { id, label }) => { + st.notice = Some((tr!("{key} is already used by {action}.", key = key(&chord), action = crate::i18n::t_cmd(id, label)), true)); + st.steal = Some((cap, chord, id)); } - 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)), + Err(crate::keymap::Refusal::Reserved(why)) => st.notice = Some((tr!("{key} is kept for {purpose}; choose another key.", key = key(&chord), purpose = crate::i18n::t(why)), true)), + Err(crate::keymap::Refusal::TooMany) => st.notice = Some((trn!("An action can have up to {n} key.", "An action can have up to {n} keys.", crate::keymap::MAX_KEYS), true)), } } } @@ -704,7 +782,9 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { let mut acts: Vec = Vec::new(); let capture = app.key_capture; let changed = app.prefs.shortcuts.len(); - let shown = egui::Window::new("Keyboard Shortcuts") + let title = tr!("Keyboard Shortcuts"); + let shown = egui::Window::new(title) + .id(egui::Id::new("shortcuts_window")) .open(&mut open) .collapsible(false) .pivot(egui::Align2::CENTER_CENTER) @@ -713,22 +793,22 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { .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)).set_name("Filter shortcuts"); - let reset_all = ui.add_enabled(changed > 0, egui::Button::new("Reset all…")).on_hover_text("Put every shortcut back to the defaults"); + ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(tr!("Filter by name or key…")).desired_width(ui.available_width() - 120.0)).set_name(tr!("Filter shortcuts")); + let reset_all = ui.add_enabled(changed > 0, egui::Button::new(tr!("Reset all…"))).on_hover_text(tr!("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_text)); + ui.label(text(Type::Label, tr!("Press the new keys for {action}. Esc cancels.", action = action_label(&app.keymap, cap.id))).color(T.accent_text)); } 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() { + ui.label(text(Type::Label, trn!("Reset {n} changed shortcut to the defaults?", "Reset {n} changed shortcuts to the defaults?", changed))); + if ui.add(danger_button(tr!("Reset all"))).clicked() { acts.push(SheetAct::ResetAll); } - if ui.button("Cancel").clicked() { + if ui.button(tr!("Cancel")).clicked() { acts.push(SheetAct::Dismiss); } }); @@ -736,21 +816,23 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { 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() { + if ui.button(tr!("Use it for {action}", action = action_label(&app.keymap, cap.id))).clicked() { acts.push(SheetAct::Steal); } - if ui.button("Cancel").clicked() { + if ui.button(tr!("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.label(text(Type::Caption, tr!("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); + // Names match in the interface language and in English. let f = st.filter.to_lowercase(); let hit = |s: &str| f.is_empty() || s.to_lowercase().contains(&f); + let named = |s: &'static str| hit(s) || hit(crate::i18n::t(s)); let fixed = fixed_rows(); egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { for group in GROUP_ORDER { @@ -759,57 +841,62 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { .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)))) + .filter(|a| hit(a.label) || hit(action_name(a)) || named(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(); + let fixed: Vec<_> = fixed.iter().filter(|(g, l, ks)| *g == group && (named(l) || named(g) || ks.iter().any(|k| hit(k) || hit(&fixed_key(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| { + crate::theme::section(ui, &format!("sheet_{group}"), crate::theme::Section::Rule, crate::i18n::t(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); + name_cell(ui, crate::i18n::t(label)); ui.horizontal(|ui| { - ui.label(text(Type::Key, keys.iter().map(|k| key(k)).collect::>().join(" · ")).color(T.text_dim)); + ui.label(text(Type::Key, keys.iter().map(|k| fixed_key(k)).collect::>().join(" · ")).color(T.text_dim)); ui.add_space(6.0); - ui.label(text(Type::Caption, "fixed")); + ui.label(text(Type::Caption, tr!("fixed"))); }); // An empty cell (an empty label would be an empty, clickable node for screen readers). ui.allocate_space(egui::Vec2::ZERO); ui.end_row(); } for a in actions { - name_cell(ui, a.label); + let name = action_name(a); + name_cell(ui, name); 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(T.on_fill)).fill(T.accent) + egui::Button::new(text(Type::Key, tr!("Press keys…")).color(T.on_fill)).fill(T.accent) } else { egui::Button::new(text(Type::Key, key(k)).color(T.text)) }; - let r = ui.add(chip).named(&format!("{} shortcut {}", a.label, key(k))).on_hover_text("Click to change · right-click to remove"); + let r = ui.add(chip).named(&tr!("{action} shortcut {key}", action = name, key = key(k))).on_hover_text(tr!("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() { + if ui.button(tr!("Change…")).clicked() { acts.push(SheetAct::Capture(KeyCapture { id: a.id, replace: Some(i) })); ui.close(); } - if ui.button("Remove").clicked() { + if ui.button(tr!("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(T.on_fill)).fill(T.accent)); + ui.add(egui::Button::new(text(Type::Key, tr!("Press keys…")).color(T.on_fill)).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))).named(&format!("{tip} for {}", a.label)).on_hover_text(tip).clicked() { + let (tip, a11y_name) = if keys.is_empty() { + (tr!("Add a shortcut"), tr!("Add a shortcut for {action}", action = name)) + } else { + (tr!("Add another shortcut"), tr!("Add another shortcut for {action}", action = name)) + }; + if ui.add(egui::Button::new("+").min_size(egui::vec2(crate::theme::TARGET, crate::theme::TARGET))).named(&a11y_name).on_hover_text(tip).clicked() { acts.push(SheetAct::Capture(KeyCapture { id: a.id, replace: None })); } } @@ -817,8 +904,11 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { if app.keymap.is_default(a.id) { // An empty cell (an empty label would be an empty, clickable node for screen readers). ui.allocate_space(egui::Vec2::ZERO); - } else if ui.button("Reset").named(&format!("Reset {}", a.label)).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)); + } else { + let defaults = if a.defaults.is_empty() { tr!("none").to_string() } else { a.defaults.iter().map(|k| key(k)).collect::>().join(" · ") }; + if ui.button(tr!("Reset")).named(&tr!("Reset {action}", action = name)).on_hover_text(tr!("Back to the default ({keys})", keys = defaults)).clicked() { + acts.push(SheetAct::Reset(a.id)); + } } ui.end_row(); } @@ -827,7 +917,7 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { } }); }); - a11y::name_title_bar(&shown, "Keyboard Shortcuts"); + a11y::name_title_bar(&shown, title); for act in acts { let mut p = app.prefs.clone(); @@ -841,25 +931,25 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { } 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)); + st.notice = Some((tr!("{action}: key removed", action = 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)); + st.notice = Some((tr!("{action}: back to the default", action = 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)); + st.notice = Some((tr!("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)); + st.notice = Some((tr!("{action}: {key} (removed from {other})", action = action_label(&app.keymap, cap.id), key = key(&chord), other = action_label(&app.keymap, from)), false)); } - Err(_) => st.notice = Some((format!("{} could not be moved.", key(&chord)), true)), + Err(_) => st.notice = Some((tr!("{key} could not be moved.", key = key(&chord)), true)), } } SheetAct::Dismiss => { diff --git a/src/envelope.rs b/src/envelope.rs index 713204b4..ab2125f4 100644 --- a/src/envelope.rs +++ b/src/envelope.rs @@ -45,7 +45,7 @@ pub struct EnvelopeEditor { pub fn open(app: &mut App) { let Some(layer) = app.s.active_layer() else { return }; let Some(k) = layer.keyframe_at(app.s.frame).filter(|k| k.sound.is_some()) else { - app.status_err("Select a keyframe with a sound to edit its envelope"); + app.status_err(tr!("Select a keyframe with a sound to edit its envelope")); return; }; let (layer, frame) = (layer.id, k.start); @@ -87,7 +87,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) { // Closed when its keyframe or sound goes away (undo, delete). let Some(t) = target(app, &ed) else { return }; let mut open = true; - let title = format!("Edit Envelope — {}", t.sound.name); + let title = tr!("Edit Envelope — {name}", name = t.sound.name); let shown = egui::Window::new(title.clone()) .id(egui::Id::new("envelope_editor")) .open(&mut open) @@ -138,46 +138,46 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { let mut pts = points_of(t); // ---- effect, preview, zoom, units ---- ui.horizontal(|ui| { - ui.label(text(Type::Label, "Effect")); - egui::ComboBox::from_id_salt("envelope_effect").width(160.0).selected_text(t.fs.effect.label()).show_ui(ui, |ui| { + ui.label(text(Type::Label, tr!("Effect"))); + egui::ComboBox::from_id_salt("envelope_effect").width(160.0).selected_text(crate::i18n::t(t.fs.effect.label())).show_ui(ui, |ui| { for e in SoundEffect::PRESETS { - if ui.selectable_label(t.fs.effect == e, e.label()).on_hover_text(e.hint()).clicked() && t.fs.effect != e { + if ui.selectable_label(t.fs.effect == e, crate::i18n::t(e.label())).on_hover_text(crate::i18n::t(e.hint())).clicked() && t.fs.effect != e { app.run("sound.set", json!({"layer": ed.layer.0, "frame": ed.frame, "effect": e.key()})); ed.selected = None; } } let custom = matches!(t.fs.effect, SoundEffect::Custom(_)); - if ui.selectable_label(custom, "Custom").on_hover_text(SoundEffect::Custom(Vec::new()).hint()).clicked() && !custom { + if ui.selectable_label(custom, tr!("Custom")).on_hover_text(crate::i18n::t(SoundEffect::Custom(Vec::new()).hint())).clicked() && !custom { app.run("sound.set", json!({"layer": ed.layer.0, "frame": ed.frame, "effect": "custom"})); } }) .response - .set_name("Sound effect"); + .set_name(tr!("Sound effect")); ui.add_space(8.0); - if crate::timeline::icon_button(ui, "Play the sound with this envelope", None, Icon::Play).clicked() { + if crate::timeline::icon_button(ui, tr!("Play the sound with this envelope"), None, Icon::Play).clicked() { preview(app, t); } - if ui.small_button("Stop").on_hover_text("Stop the preview").clicked() { + if ui.small_button(tr!("Stop")).on_hover_text(tr!("Stop the preview")).clicked() { app.sound.stop(); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.selectable_label(ed.frames, "Frames").on_hover_text("Read times in frames").clicked() { + if ui.selectable_label(ed.frames, tr!("Frames")).on_hover_text(tr!("Read times in frames")).clicked() { ed.frames = true; } - if ui.selectable_label(!ed.frames, "Seconds").on_hover_text("Read times in seconds").clicked() { + if ui.selectable_label(!ed.frames, tr!("Seconds")).on_hover_text(tr!("Read times in seconds")).clicked() { ed.frames = false; } ui.add_space(8.0); let total = total_seconds(t, &pts); let shown = ed.window.unwrap_or(total); - if ui.small_button("Fit").on_hover_text("Show the whole sound").named("Zoom to fit").clicked() { + if ui.small_button(tr!("Fit")).on_hover_text(tr!("Show the whole sound")).named(tr!("Zoom to fit")).clicked() { ed.window = None; ed.from = 0.0; } - if ui.small_button("+").on_hover_text("Zoom in").named("Zoom in").clicked() { + if ui.small_button("+").on_hover_text(tr!("Zoom in")).named(tr!("Zoom in")).clicked() { ed.window = Some((shown * 0.5).max(1.0 / f64::from(fps) / 4.0)); } - if ui.small_button("−").on_hover_text("Zoom out").named("Zoom out").clicked() { + if ui.small_button("−").on_hover_text(tr!("Zoom out")).named(tr!("Zoom out")).clicked() { let w = shown * 2.0; ed.window = if w >= total { None } else { Some(w) }; } @@ -201,9 +201,9 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { let p = ui.painter_at(area); let mut changed: Option<(&str, bool)> = None; for (c, lane) in lanes.iter().enumerate() { - let name = if c == 0 { "Left channel" } else { "Right channel" }; + let name = if c == 0 { tr!("Left channel") } else { tr!("Right channel") }; let bg = ui.interact(*lane, ui.id().with(("env_lane", c)), Sense::click()); - crate::a11y::surface(ui, &bg, &format!("{name}: click to add a volume point")); + crate::a11y::surface(ui, &bg, &tr!("{channel}: click to add a volume point", channel = name)); p.rect_filled(*lane, crate::theme::SQUARE, T.field); p.line_segment([pos2(lane.left(), lane.center().y), pos2(lane.right(), lane.center().y)], Stroke::new(1.0, T.separator)); if let Some(pk) = &peaks @@ -211,7 +211,7 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { { draw_wave(&p, *lane, pk, &t.sound, t, from, window); } - p.text(lane.left_top() + vec2(6.0, 4.0), Align2::LEFT_TOP, if c == 0 { "L" } else { "R" }, font(Type::Label), T.text_dim); + p.text(lane.left_top() + vec2(6.0, 4.0), Align2::LEFT_TOP, if c == 0 { trc!("left channel", "L") } else { trc!("right channel", "R") }, font(Type::Label), T.text_dim); // The envelope: its level before the first point and after the last, lines between. let level = |q: &EnvelopePoint| if c == 0 { q.left } else { q.right }; let mut line: Vec = Vec::new(); @@ -235,7 +235,7 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { pts.push(EnvelopePoint::new(when, l, r)); pts = clean_points(&pts); ed.selected = pts.iter().position(|q| q.at == when); - changed = Some(("Add Envelope Point", false)); + changed = Some((tr_noop!("Add Envelope Point"), false)); } // The points' handles: drag to move, right-click to delete. let mut remove = None; @@ -248,12 +248,12 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { let hit = Rect::from_center_size(centre, vec2(2.0 * REACH, 2.0 * REACH)); let r = ui.interact(hit, ui.id().with(("env_point", c, i)), Sense::click_and_drag()); let secs = time_label(q.at, ed.frames, fps); - crate::a11y::control(ui, &r, WidgetType::Slider, &format!("Point {} of {}, {name}: {:.0} % at {secs}", i + 1, pts.len(), level(&q) * 100.0), None); + crate::a11y::control(ui, &r, WidgetType::Slider, &tr!("Point {index} of {count}, {channel}: {level} % at {time}", index = i + 1, count = pts.len(), channel = name, level = format!("{:.0}", level(&q) * 100.0), time = secs), None); let hot = r.hovered() || r.dragged() || ed.selected == Some(i); let h = Rect::from_center_size(centre, vec2(2.0 * HANDLE, 2.0 * HANDLE)); p.rect_filled(h, crate::theme::SQUARE, if hot { T.accent } else { T.panel }); p.rect_stroke(h, crate::theme::SQUARE, Stroke::new(1.5, T.accent), egui::StrokeKind::Inside); - let r = r.on_hover_text(format!("{:.0} % at {secs} · drag to move, right-click to delete", level(&q) * 100.0)); + let r = r.on_hover_text(tr!("{level} % at {time} · drag to move, right-click to delete", level = format!("{:.0}", level(&q) * 100.0), time = secs)); if r.clicked() { ed.selected = Some(i); } @@ -269,7 +269,7 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { if c == 0 { q.left = v } else { q.right = v } } ed.selected = Some(i); - changed = Some(("Move Envelope Point", true)); + changed = Some((tr_noop!("Move Envelope Point"), true)); } if r.secondary_clicked() && pts.len() > 1 { remove = Some(i); @@ -278,7 +278,7 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { if let Some(i) = remove { pts.remove(i); ed.selected = None; - changed = Some(("Delete Envelope Point", false)); + changed = Some((tr_noop!("Delete Envelope Point"), false)); } } // The ruler: times under the lanes' x positions. @@ -295,22 +295,22 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { let sel = ed.selected.filter(|&i| i < pts.len()); match sel.and_then(|i| pts.get(i).copied().map(|q| (i, q))) { Some((i, mut q)) => { - ui.label(text(Type::Label, format!("Point {} of {}", i + 1, pts.len()))); + ui.label(text(Type::Label, tr!("Point {index} of {count}", index = i + 1, count = pts.len()))); let lo = i.checked_sub(1).and_then(|j| pts.get(j)).map_or(0.0, |n| n.at); let hi = pts.get(i + 1).map_or(MAX_ENVELOPE_SECONDS, |n| n.at); let mut edit = false; with_type(ui, Type::Data, |ui| { if ed.frames { let mut f = q.at * f64::from(fps); - edit |= ui.add(egui::DragValue::new(&mut f).range(lo * f64::from(fps)..=hi * f64::from(fps)).speed(0.1).max_decimals(1).suffix(" f")).named("Point time").changed(); + edit |= ui.add(egui::DragValue::new(&mut f).range(lo * f64::from(fps)..=hi * f64::from(fps)).speed(0.1).max_decimals(1).suffix(" f")).named(tr!("Point time")).changed(); q.at = f / f64::from(fps); } else { - edit |= ui.add(egui::DragValue::new(&mut q.at).range(lo..=hi).speed(0.005).max_decimals(3).suffix(" s")).named("Point time").changed(); + edit |= ui.add(egui::DragValue::new(&mut q.at).range(lo..=hi).speed(0.005).max_decimals(3).suffix(" s")).named(tr!("Point time")).changed(); } - for (name, v) in [("Left", &mut q.left), ("Right", &mut q.right)] { - ui.label(text(Type::Label, name)); + for (left, v) in [(true, &mut q.left), (false, &mut q.right)] { + ui.label(text(Type::Label, if left { tr!("Left") } else { tr!("Right") })); let mut pct = f64::from(*v) * 100.0; - if ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix(" %")).named(&format!("{name} channel volume")).changed() { + if ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix(" %")).named(if left { tr!("Left channel volume") } else { tr!("Right channel volume") }).changed() { *v = (pct / 100.0) as f32; edit = true; } @@ -318,21 +318,21 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { }); if edit && let Some(slot) = pts.get_mut(i) { *slot = q; - changed = Some(("Envelope Point", true)); + changed = Some((tr_noop!("Envelope Point"), true)); } - if ui.add_enabled(pts.len() > 1, egui::Button::new("Delete Point")).on_hover_text("A sound keeps at least one point").clicked() { + if ui.add_enabled(pts.len() > 1, egui::Button::new(tr!("Delete Point"))).on_hover_text(tr!("A sound keeps at least one point")).clicked() { pts.remove(i); ed.selected = None; - changed = Some(("Delete Envelope Point", false)); + changed = Some((tr_noop!("Delete Envelope Point"), false)); } } None => { - ui.label(text(Type::Caption, format!("Click a channel to add a point (up to {MAX_ENVELOPE_POINTS}), drag a point to shape the volume, right-click it to delete it. {} points.", pts.len()))); + ui.label(text(Type::Caption, trn!("Click a channel to add a point (up to {max}), drag a point to shape the volume, right-click it to delete it. {n} point.", "Click a channel to add a point (up to {max}), drag a point to shape the volume, right-click it to delete it. {n} points.", pts.len(), max = MAX_ENVELOPE_POINTS))); } } }); - let span = if ed.frames { format!("{} frames", (t.heard * f64::from(fps)).round()) } else { format!("{:.2} s", t.heard) }; - ui.label(text(Type::Caption, format!("Heard for {span} ({}). Presets are shaped over this time; editing one makes it Custom.", heard_reason(&t.fs, t.span, t.rest)))); + let span = if ed.frames { let n = (t.heard * f64::from(fps)).round().max(0.0) as u64; trn!("{n} frame", "{n} frames", n) } else { format!("{:.2} s", t.heard) }; + ui.label(text(Type::Caption, tr!("Heard for {time} ({why}). Presets are shaped over this time; editing one makes it Custom.", time = span, why = heard_reason(&t.fs, t.span, t.rest)))); if let Some((label, live)) = changed { set_points(app, ed, label, &pts, live); } @@ -342,11 +342,11 @@ fn body(app: &mut App, ed: &mut EnvelopeEditor, ui: &mut egui::Ui, t: &Target) { fn heard_reason(fs: &FrameSound, span: u32, rest: u32) -> String { use anicraft_engine::doc::SoundSync; match (fs.sync, fs.looping) { - (SoundSync::Stream, true) => format!("a stream looping over its {span}-frame span"), - (SoundSync::Stream, false) => format!("a stream, within its {span}-frame span"), - (_, true) => format!("looping to the end of the movie, {rest} frames on"), - (_, false) if fs.repeat > 1 => format!("played {} times", fs.repeat), - _ => "played once".to_string(), + (SoundSync::Stream, true) => trn!("a stream looping over its {n}-frame span", "a stream looping over its {n}-frame span", span), + (SoundSync::Stream, false) => trn!("a stream, within its {n}-frame span", "a stream, within its {n}-frame span", span), + (_, true) => trn!("looping to the end of the movie, {n} frame on", "looping to the end of the movie, {n} frames on", rest), + (_, false) if fs.repeat > 1 => trn!("played {n} time", "played {n} times", fs.repeat), + _ => tr!("played once").to_string(), } } @@ -357,7 +357,7 @@ fn total_seconds(t: &Target, pts: &[EnvelopePoint]) -> f64 { } fn time_label(at: f64, frames: bool, fps: f32) -> String { - if frames { format!("frame {:.1}", at * f64::from(fps) + 1.0) } else { format!("{at:.3} s") } + if frames { tr!("frame {number}", number = format!("{:.1}", at * f64::from(fps) + 1.0)) } else { format!("{at:.3} s") } } /// The sound's channels summarised apart (once per sound; a mono sound is one channel twice). @@ -441,7 +441,7 @@ fn preview(app: &mut App, t: &Target) { v.envelope = t.fs.effect.envelope(heard, rate); app.sound.preview_voice(v); if let Some(e) = app.sound.error.take() { - app.status_err(format!("No sound: {e}")); + app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e))); } } diff --git a/src/erasertool.rs b/src/erasertool.rs index 8d270b4b..9a36c67f 100644 --- a/src/erasertool.rs +++ b/src/erasertool.rs @@ -52,12 +52,13 @@ pub fn commit(app: &mut App, xf: Xf) { } let o = app.eraser; let params = json!({"points": points(&samples), "size": o.size, "shape": shape_key(o.shape), "mode": o.mode.key(), "unit": xf.unit()}); - let undo = crate::platform::shortcut_label("Ctrl+Z"); + let undo = app.undo_key(); match app.run("draw.erase", params) { - Some(v) if v["erased"] == true => app.status_ok(format!("Erased. {undo} to undo.")), + Some(v) if v["erased"] == true => app.status_ok(tr!("Erased. {undo} to undo.", undo = undo)), Some(v) => { - let why = v["reason"].as_str().unwrap_or("nothing to erase there"); - app.status_ok(format!("Nothing erased: {why}. The eraser works on lines and fills drawn with Object Drawing off; drawing objects and symbols are kept.")); + // The engine's reason is English from below the shell. + let why = v["reason"].as_str().map_or(std::borrow::Cow::Borrowed(tr!("nothing to erase there")), crate::i18n::t_dyn); + app.status_ok(tr!("Nothing erased: {why}. The eraser works on lines and fills drawn with Object Drawing off; drawing objects and symbols are kept.", why = why)); } None => {} } @@ -66,8 +67,8 @@ pub fn commit(app: &mut App, xf: Xf) { /// The Faucet: deletes the whole fill or line under the click. pub fn faucet(app: &mut App, p: Vec2, zoom: f32) { if let Some(v) = app.run("draw.faucet", json!({"x": p.x, "y": p.y, "slop": 4.0 / zoom.max(1e-3)})) { - let what = if v["kind"] == "line" { "line" } else { "fill" }; - app.status_ok(format!("Deleted the {what}. {} to undo.", crate::platform::shortcut_label("Ctrl+Z"))); + let undo = app.undo_key(); + app.status_ok(if v["kind"] == "line" { tr!("Deleted the line. {undo} to undo.", undo = undo) } else { tr!("Deleted the fill. {undo} to undo.", undo = undo) }); } } @@ -75,7 +76,7 @@ pub fn faucet(app: &mut App, p: Vec2, zoom: f32) { pub fn erase_everything(app: &mut App) { // The engine asks only when there is something to erase. if app.s.confirmation("draw.erase_all", &json!({})).is_none() { - app.status_ok("Nothing to erase: the visible, unlocked layers are empty at this frame."); + app.status_ok(tr!("Nothing to erase: the visible, unlocked layers are empty at this frame.")); return; } app.request("draw.erase_all", json!({})); @@ -106,26 +107,36 @@ pub fn eyedropper(app: &mut App, p: Vec2, shift: bool, zoom: f32) { let color = v["color"].as_str().unwrap_or("").to_string(); let into_fill = v["into"] == "fill"; if shift { - app.status_ok(format!("Picked {color} into the {} colour.", if into_fill { "fill" } else { "stroke" })); + app.status_ok(if into_fill { tr!("Picked {color} into the fill colour.", color = color) } else { tr!("Picked {color} into the stroke colour.", color = color) }); return; } - let what = match v["paint"].as_str() { - Some("linear") => "linear gradient".to_string(), - Some("radial") => "radial gradient".to_string(), - Some("bitmap") => "bitmap fill".to_string(), - _ if into_fill => format!("fill {color}"), - _ => format!("line {color}, {} px", v["width"].as_f64().map_or(String::new(), |w| format!("{w:.1}"))), - }; - let sel = &app.s.selection; - let shapes = app.s.visible_elements().iter().filter(|e| sel.contains(&e.id) && matches!(e.kind, ElementKind::Shape(_))).count(); + // One whole sentence per kind of paint, so each translates as a sentence. + let paint = v["paint"].as_str(); + let width = v["width"].as_f64().map_or(String::new(), |w| format!("{w:.1}")); + // The selected shapes on every layer (ADR 0044). + let shapes = app.s.selected_elements().iter().filter(|(_, e)| matches!(e.kind, ElementKind::Shape(_))).count(); if shapes > 0 { if let Some(r) = app.run("paint.apply_style", json!({"fill": into_fill, "stroke": !into_fill})) { let n = r["changed"].as_u64().unwrap_or(0); - app.status_ok(format!("Applied the picked {what} to {n} {}. {} to undo.", if n == 1 { "shape" } else { "shapes" }, crate::platform::shortcut_label("Ctrl+Z"))); + let undo = app.undo_key(); + app.status_ok(match paint { + Some("linear") => trn!("Applied the picked linear gradient to {n} shape. {undo} to undo.", "Applied the picked linear gradient to {n} shapes. {undo} to undo.", n, undo = undo), + Some("radial") => trn!("Applied the picked radial gradient to {n} shape. {undo} to undo.", "Applied the picked radial gradient to {n} shapes. {undo} to undo.", n, undo = undo), + Some("bitmap") => trn!("Applied the picked bitmap fill to {n} shape. {undo} to undo.", "Applied the picked bitmap fill to {n} shapes. {undo} to undo.", n, undo = undo), + _ if into_fill => trn!("Applied the picked fill {color} to {n} shape. {undo} to undo.", "Applied the picked fill {color} to {n} shapes. {undo} to undo.", n, color = color, undo = undo), + _ => trn!("Applied the picked line {color}, {width} px to {n} shape. {undo} to undo.", "Applied the picked line {color}, {width} px to {n} shapes. {undo} to undo.", n, color = color, width = width, undo = undo), + }); } } else { - let next = if into_fill { "Click a fill or an enclosed area to pour it" } else { "Click a shape to give it this line" }; - app.status_ok(format!("Picked the {what}. {next}.")); + let picked = match paint { + Some("linear") => tr!("Picked the linear gradient.").to_string(), + Some("radial") => tr!("Picked the radial gradient.").to_string(), + Some("bitmap") => tr!("Picked the bitmap fill.").to_string(), + _ if into_fill => tr!("Picked the fill {color}.", color = color), + _ => tr!("Picked the line {color}, {width} px.", color = color, width = width), + }; + let next = if into_fill { tr!("Click a fill or an enclosed area to pour it.") } else { tr!("Click a shape to give it this line.") }; + app.status_ok(format!("{picked} {next}")); } app.tool = if into_fill { Tool::PaintBucket } else { Tool::InkBottle }; } diff --git a/src/gpu_stage.rs b/src/gpu_stage.rs index 1085d80d..fc7ea519 100644 --- a/src/gpu_stage.rs +++ b/src/gpu_stage.rs @@ -144,7 +144,8 @@ mod imp { None => None, }; GpuRenderer::new().map_err(|e| match shared { - Some(s) => format!("{s}; and on a device of its own: {e}"), + // Shown in Preferences: the driver's English, joined in the interface language. + Some(s) => tr!("{shared}; and on a device of its own: {e}", shared = s, e = e), None => e.to_string(), }) } diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs index 08f535b6..02dc4682 100644 --- a/src/guidelines_tests.rs +++ b/src/guidelines_tests.rs @@ -1,6 +1,6 @@ //! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values. -const SOURCES: [(&str, &str); 19] = [ +const SOURCES: [(&str, &str); 20] = [ ("actions_panel.rs", include_str!("actions_panel.rs")), ("test_movie.rs", include_str!("test_movie.rs")), ("autosave.rs", include_str!("autosave.rs")), @@ -19,6 +19,7 @@ const SOURCES: [(&str, &str); 19] = [ ("widthtool.rs", include_str!("widthtool.rs")), ("motion_editor.rs", include_str!("motion_editor.rs")), ("shape_hints.rs", include_str!("shape_hints.rs")), + ("bone_tool.rs", include_str!("bone_tool.rs")), ("main.rs", ""), ]; diff --git a/src/i18n/catalog.rs b/src/i18n/catalog.rs new file mode 100644 index 00000000..adee2b77 --- /dev/null +++ b/src/i18n/catalog.rs @@ -0,0 +1,285 @@ +//! Interface catalogs in the craft-i18n format (`docs/catalog-format.md` in +//! storytold/craft-i18n): one row per string, `contextEnglishtranslation`, keyed by the +//! English source text. Read here by our own small parser, so the app depends on no outside +//! crate for it, and a row it can't use is skipped (that string shows in English), never an +//! error. + +use std::collections::HashMap; + +/// Lines longer than this are skipped: no interface string is anywhere near it. +const MAX_LINE: usize = 16 * 1024; +/// Rows read per catalog at most (craft-i18n's largest shared catalog has about 1 300). +const MAX_ROWS: usize = 100_000; + +/// One usable row. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Row { + /// Empty, a plain word (`menu`) or one of `@plural`, `@id`. + pub context: String, + pub source: String, + pub translation: String, +} + +/// A row that was skipped, and why (for the stale and missing report, never shown to users). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Problem { + pub line: usize, + pub why: String, +} + +/// `\n`, `\t` and `\\`; any other escape makes the row unusable. +fn unescape(s: &str) -> Option { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('\\') => out.push('\\'), + _ => return None, + } + } + Some(out) +} + +/// The `{name}` placeholders of a string, sorted (each once). `None` when the braces don't +/// pair up, so the row is skipped. +pub fn placeholders(s: &str) -> Option> { + let mut out = Vec::new(); + let mut rest = s; + while let Some(open) = rest.find('{') { + let after = rest.get(open + 1..)?; + let close = after.find('}')?; + let name = after.get(..close)?; + if name.is_empty() || name.contains('{') || !name.chars().all(|c| c.is_alphanumeric() || c == '_') { + return None; + } + out.push(name); + rest = after.get(close + 1..)?; + } + if rest.contains('}') { + return None; + } + out.sort_unstable(); + out.dedup(); + Some(out) +} + +/// Why a row can't be used, if it can't. +fn check(context: &str, source: &str, translation: &str) -> Result<(), String> { + if translation.is_empty() { + return Err("empty translation".into()); + } + if source.is_empty() { + return Err("empty source text".into()); + } + match context { + "@id" | "@msg" => return Ok(()), + "@plural" => { + let forms: Vec<&str> = source.split('|').collect(); + if forms.len() != 2 { + return Err("an @plural source needs exactly `one|other`".into()); + } + let want = placeholders(source).ok_or("unpaired braces")?; + for form in translation.split('|') { + if form.is_empty() { + return Err("an empty plural form".into()); + } + if placeholders(form).as_ref() != Some(&want) { + return Err(format!("plural form {form:?} has other placeholders than {source:?}")); + } + } + return Ok(()); + } + c if c.starts_with('@') => return Err(format!("unknown context {c}")), + _ => {} + } + let (a, b) = (placeholders(source).ok_or("unpaired braces in the source")?, placeholders(translation).ok_or("unpaired braces in the translation")?); + if a != b { + return Err(format!("placeholders differ: {a:?} and {b:?}")); + } + if source.ends_with('…') != translation.ends_with('…') { + return Err("a trailing … in one column needs one in the other".into()); + } + Ok(()) +} + +/// Every usable row of a catalog file, and the problems with the others. +pub fn parse(text: &str) -> (Vec, Vec) { + let mut rows = Vec::new(); + let mut problems = Vec::new(); + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + for (i, line) in text.lines().enumerate() { + let line = line.strip_suffix('\r').unwrap_or(line); + if line.trim().is_empty() || line.starts_with('#') { + continue; + } + let mut problem = |why: String| problems.push(Problem { line: i + 1, why }); + if rows.len() >= MAX_ROWS { + problem(format!("more than {MAX_ROWS} rows; the rest are skipped")); + break; + } + if line.len() > MAX_LINE { + problem("line too long".into()); + continue; + } + let cols: Vec<&str> = line.split('\t').collect(); + let [context, source, translation] = cols.as_slice() else { + problem(format!("{} columns, not 3", cols.len())); + continue; + }; + let (Some(context), Some(source), Some(translation)) = (unescape(context), unescape(source), unescape(translation)) else { + problem("an escape other than \\n, \\t or \\\\".into()); + continue; + }; + match check(&context, &source, &translation) { + Ok(()) => rows.push(Row { context, source, translation }), + Err(why) => problem(why), + } + } + (rows, problems) +} + +/// The translations of one interface language, merged from its catalogs (later wins). +#[derive(Default, Debug)] +pub struct Catalog { + /// Source text → translation without a context. + plain: HashMap, + /// Source text → (context, translation) for rows with a plain-word context. + contextual: HashMap>, + /// English `one` form → (English `other` form, the language's forms). + plural: HashMap)>>, + /// `@id` rows: a command id (or `language.name`) → its label. + ids: HashMap, +} + +impl Catalog { + /// Adds rows over what is there: a row for the same key replaces the earlier one. + pub fn merge(&mut self, rows: Vec) { + for r in rows { + match r.context.as_str() { + "" => { + self.plain.insert(r.source, r.translation); + } + "@id" => { + self.ids.insert(r.source, r.translation); + } + // Templates for longer messages are not matched yet (docs/localisation.md). + "@msg" => {} + "@plural" => { + let Some((one, other)) = r.source.split_once('|') else { continue }; + let forms = r.translation.split('|').map(str::to_string).collect(); + let list = self.plural.entry(one.to_string()).or_default(); + list.retain(|(o, _)| o != other); + list.push((other.to_string(), forms)); + } + _ => { + let list = self.contextual.entry(r.source).or_default(); + list.retain(|(c, _)| *c != r.context); + list.push((r.context, r.translation)); + } + } + } + } + + /// The translation of `source` in `context` (falling back to the plain row), if any. + pub fn get(&self, context: &str, source: &str) -> Option<&str> { + if !context.is_empty() + && let Some((_, t)) = self.contextual.get(source).and_then(|l| l.iter().find(|(c, _)| c == context)) + { + return Some(t); + } + self.plain.get(source).map(String::as_str) + } + + /// The label of a command id (`@id` rows). + pub fn id(&self, id: &str) -> Option<&str> { + self.ids.get(id).map(String::as_str) + } + + /// The forms of an `@plural` row. + pub fn plural(&self, one: &str, other: &str) -> Option<&[String]> { + self.plural.get(one)?.iter().find(|(o, _)| o == other).map(|(_, f)| f.as_slice()) + } + + #[cfg(test)] + pub fn len(&self) -> usize { + self.plain.len() + self.contextual.values().map(Vec::len).sum::() + self.plural.values().map(Vec::len).sum::() + self.ids.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &str = "\u{feff}# Header line\r\n\ + @id\tlanguage.name\tTestisch\r\n\ + \tSave\tSpeichern\r\n\ + menu\tOpen\tÖffnen (Menü)\n\ + \tOpen\tÖffnen\n\ + \tLine one\\nLine two\tZeile eins\\nZeile zwei\n\ + @plural\t{n} frame|{n} frames\t{n} Bild|{n} Bilder\n\ + \tSaved {path}\t{path} gespeichert\n\ + \tExport…\tExportieren…\n\ + @id\tedit.undo\tRückgängig\n\ + @msg\tCould not open {name}\t{name} lässt sich nicht öffnen\n\ + \n\ + \tBroken\t\n\ + \tTwo columns\n\ + \tSaved {path}x\t{file} gespeichert\n\ + \tExport…\tExportieren\n\ + \tBad \\q escape\tx\n\ + @future\tThing\tDing\n\ + @plural\t{n} layer\t{n} Ebene\n\ + @plural\t{n} key|{n} keys\t{n} Taste|{count} Tasten\n\ + \tOdd {brace\tx {brace\n"; + + #[test] + fn rows_are_read_and_bad_ones_skipped_with_a_reason() { + let (rows, problems) = parse(SAMPLE); + assert_eq!(rows.len(), 10, "{rows:#?}"); + assert_eq!(problems.len(), 9, "{problems:#?}"); + assert!(problems.iter().all(|p| p.line > 11)); + let mut c = Catalog::default(); + c.merge(rows); + assert_eq!(c.get("", "Save"), Some("Speichern")); + assert_eq!(c.get("menu", "Open"), Some("Öffnen (Menü)")); + assert_eq!(c.get("", "Open"), Some("Öffnen")); + assert_eq!(c.get("toolbar", "Open"), Some("Öffnen"), "an unknown context falls back to the plain row"); + assert_eq!(c.get("", "Line one\nLine two"), Some("Zeile eins\nZeile zwei")); + assert_eq!(c.plural("{n} frame", "{n} frames"), Some(&["{n} Bild".to_string(), "{n} Bilder".to_string()][..])); + assert_eq!(c.id("edit.undo"), Some("Rückgängig")); + assert_eq!(c.id("language.name"), Some("Testisch")); + assert_eq!(c.get("", "Export…"), Some("Exportieren…")); + assert_eq!(c.get("", "Missing"), None); + } + + #[test] + fn later_catalogs_override_earlier_ones() { + let mut c = Catalog::default(); + c.merge(parse("\tSave\tA\nmenu\tOpen\tB\n@plural\t{n} x|{n} xs\t{n} a|{n} b\n").0); + c.merge(parse("\tSave\tC\nmenu\tOpen\tD\n@plural\t{n} x|{n} xs\t{n} c|{n} d\n").0); + assert_eq!(c.get("", "Save"), Some("C")); + assert_eq!(c.get("menu", "Open"), Some("D")); + assert_eq!(c.plural("{n} x", "{n} xs").map(<[String]>::len), Some(2)); + assert_eq!(c.plural("{n} x", "{n} xs").and_then(|f| f.first()).map(String::as_str), Some("{n} c")); + assert_eq!(c.len(), 3); + } + + #[test] + fn hostile_input_never_panics() { + for text in ["", "\t", "\t\t", "\t\t\t", "{\t{\t{", "}\t}\t}", "@plural\t|\t|", "@plural\t{n}|{n}\t", "\\", "\t\\\tx", "\u{feff}", "\r\n\r\n", "\t{é}\t{é}"] { + let _ = parse(text); + } + let long = format!("\t{}\tx", "a".repeat(MAX_LINE + 1)); + assert_eq!(parse(&long).0.len(), 0); + assert_eq!(placeholders("{a} and {b} and {a}"), Some(vec!["a", "b"])); + assert_eq!(placeholders("{a"), None); + assert_eq!(placeholders("a}"), None); + assert_eq!(placeholders("{}"), None); + } +} diff --git a/src/i18n/mod.rs b/src/i18n/mod.rs new file mode 100644 index 00000000..fe04cb2b --- /dev/null +++ b/src/i18n/mod.rs @@ -0,0 +1,412 @@ +//! Interface languages (ADR 0040, docs/localisation.md). +//! +//! Strings stay English in the code and are the lookup keys, as in craft-i18n's catalogs: +//! `tr!("Save")` is the text in the interface language, `tr!("Saved {path}", path = p)` fills +//! placeholders after the lookup, `trn!("{n} frame", "{n} frames", n)` picks a plural form by +//! CLDR rules, `trc!("menu", "Open")` tells two meanings of the same English apart, and +//! `tr_noop!("Graphite")` marks a string in a table for the extractor, to be translated where it +//! is drawn with [`t`]. A missing translation is the English itself: nothing here fails. +//! +//! Catalogs come from the Craft family's shared craft-i18n repository, embedded at build time +//! from `CRAFT_I18N_DIR` (build.rs); without it the interface is English, plus the pseudo-locale +//! that tests layout. Command ids, document text, file names, the CLI, `serve` and MCP never see +//! translated text; menus translate the registry's labels when they are drawn. + +pub mod catalog; +pub mod plural; +pub mod pseudo; +#[cfg(test)] +pub mod scan; + +use std::borrow::Cow; +use std::cell::Cell; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{LazyLock, Mutex}; + +use catalog::Catalog; + +// `CRAFT_I18N: &[(&str, &str, &str)]`: (locale, its shared `common.tsv`, AniCraft's +// `anicraft.tsv`), `""` for a missing file; empty without `CRAFT_I18N_DIR`. +include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); + +/// The `language` preference that follows the system's language. +pub const AUTO: &str = "auto"; +pub const ENGLISH: &str = "en"; +/// Accented, longer English (`pseudo.rs`), for checking layout and missed strings. +pub const PSEUDO: &str = "pseudo"; + +/// Languages the interface can be drawn in today: written left to right, in scripts the bundled +/// faces cover and egui lays out a letter at a time (Latin, Greek, Cyrillic). A catalog for any +/// other locale is embedded but not offered (docs/localisation.md › Scripts and direction). +/// A regional variant (`es-mx`) is ready when its language is. +pub const READY: &[&str] = &[ + "az", "bg", "bs", "ca", "cs", "da", "de", "el", "es", "et", "fi", "fr", "gl", "hr", "hu", "id", "it", "kk", "lt", "lv", "nb", "nl", "pl", "pt", "pt-br", "ro", "ru", "sk", "sl", "sq", "sr", "sr-latn", "sv", "tr", "uk", +]; + +enum Kind { + English, + Pseudo, + Catalog(Catalog), +} + +struct Language { + code: String, + name: String, + kind: Kind, +} + +/// The last subtag is a region (`br`, `419`): the locale falls back to its base language. +fn regional_base(code: &str) -> Option<&str> { + let (base, region) = code.rsplit_once('-')?; + let is_region = (region.len() == 2 && region.chars().all(|c| c.is_ascii_alphabetic())) || (region.len() == 3 && region.chars().all(|c| c.is_ascii_digit())); + is_region.then_some(base) +} + +fn ready(code: &str, ready: &[&str]) -> bool { + ready.contains(&code) || regional_base(code).is_some_and(|b| ready.contains(&b)) +} + +/// Every language this build offers, English first and the pseudo-locale last. +pub struct Languages { + list: Vec, +} + +impl Languages { + /// From embedded `(locale, common, app)` catalogs. A locale is offered when it has its own + /// AniCraft catalog and is [`READY`]; one with only shared strings, or a base language + /// embedded for its regional variants' sake, is a fallback only. Returns the skipped rows + /// too, as `locale/file:line: why`. + pub fn new(embedded: &[(&str, &str, &str)], ready_codes: &[&str]) -> (Languages, Vec) { + let mut problems = Vec::new(); + let mut parsed: HashMap, Vec, bool)> = HashMap::new(); + for (code, common, app) in embedded { + let code = code.to_ascii_lowercase(); + let mut read = |file: &str, text: &str| { + let (rows, bad) = catalog::parse(text); + problems.extend(bad.into_iter().map(|p| format!("{code}/{file}:{}: {}", p.line, p.why))); + rows + }; + let entry = (read("common.tsv", common), read("anicraft.tsv", app), !app.is_empty()); + parsed.insert(code, entry); + } + let mut list = vec![Language { code: ENGLISH.into(), name: "English".into(), kind: Kind::English }]; + let mut codes: Vec<&String> = parsed.keys().filter(|c| parsed.get(*c).is_some_and(|e| e.2) && ready(c, ready_codes)).collect(); + codes.sort(); + for code in codes { + // pt-br: pt shared, pt app, pt-br shared, pt-br app (each later one wins), so an app + // row overrides the shared one in its own locale only. + let mut cat = Catalog::default(); + let mut chain = vec![code.as_str()]; + if let Some(base) = regional_base(code) { + chain.insert(0, base); + } + for c in chain { + if let Some((common, app, _)) = parsed.get(c) { + cat.merge(common.clone()); + cat.merge(app.clone()); + } + } + let name = cat.id("language.name").unwrap_or(code).to_string(); + list.push(Language { code: code.clone(), name, kind: Kind::Catalog(cat) }); + } + list.push(Language { code: PSEUDO.into(), name: "Pseudo-locale (layout test)".into(), kind: Kind::Pseudo }); + (Languages { list }, problems) + } + + fn get(&self, i: usize) -> &Language { + // Index 0 is always English. + self.list.get(i).or(self.list.first()).unwrap_or(&ENGLISH_LANGUAGE) + } + + fn find(&self, code: &str) -> Option { + let code = code.trim().to_ascii_lowercase().replace('_', "-"); + self.list.iter().position(|l| l.code == code) + } + + /// The language a preference stands for: an offered code, else ([`AUTO`], or a code this + /// build doesn't have) the system's language, which is English when none fits. + fn resolve(&self, pref: &str, system: Option<&str>) -> usize { + if !pref.eq_ignore_ascii_case(AUTO) + && let Some(i) = self.find(pref) + { + return i; + } + system.and_then(|s| self.match_system(s)).unwrap_or(0) + } + + /// The best offered language for a system locale (`de-AT`, `pt_BR.UTF-8`, `zh-Hans-CN`). + fn match_system(&self, locale: &str) -> Option { + let locale = locale.split(['.', '@']).next().unwrap_or(locale).to_ascii_lowercase().replace('_', "-"); + let tags: Vec<&str> = locale.split('-').filter(|t| !t.is_empty()).collect(); + let lang = *tags.first()?; + let mut candidates = vec![locale.clone()]; + if let Some(second) = tags.get(1) { + candidates.push(format!("{lang}-{second}")); + } + if lang == "zh" { + let traditional = tags.iter().any(|t| matches!(*t, "hant" | "tw" | "hk" | "mo")); + candidates.push(if traditional { "zh-hant".into() } else { "zh-hans".into() }); + } + candidates.push(lang.to_string()); + // The pseudo-locale is never the system's. + candidates.iter().filter_map(|c| self.find(c)).find(|i| self.get(*i).code != PSEUDO) + } + + #[cfg(test)] + fn lookup<'a>(&'a self, i: usize, context: &str, source: &'a str) -> Option<&'a str> { + match &self.get(i).kind { + Kind::Catalog(c) => c.get(context, source), + _ => None, + } + } + + fn plural<'a>(&'a self, i: usize, one: &'a str, other: &'a str, n: u64) -> &'a str { + let lang = self.get(i); + let english = if n == 1 { one } else { other }; + let Kind::Catalog(c) = &lang.kind else { return english }; + match c.plural(one, other) { + Some(forms) if forms.len() == plural::forms(&lang.code).len() => forms.get(plural::index(&lang.code, n)).map_or(english, String::as_str), + // A row with the wrong number of forms is skipped (English), as craft-i18n's apps do. + _ => english, + } + } +} + +/// Stands in for the list's English entry, which `Languages::new` always makes. +static ENGLISH_LANGUAGE: Language = Language { code: String::new(), name: String::new(), kind: Kind::English }; + +static LANGUAGES: LazyLock = LazyLock::new(|| { + let (languages, problems) = Languages::new(CRAFT_I18N, READY); + for p in problems { + eprintln!("interface catalog: {p} (shown in English)"); + } + languages +}); + +/// The interface language, an index into [`LANGUAGES`]. +static CURRENT: AtomicUsize = AtomicUsize::new(0); + +thread_local! { + // Tests draw on threads of their own: each picks its language without changing the + // others' (`set_language` writes here under `cfg(test)`). + static OVERRIDE: Cell> = const { Cell::new(None) }; +} + +fn current() -> usize { + OVERRIDE.with(Cell::get).unwrap_or_else(|| CURRENT.load(Ordering::Relaxed)) +} + +fn set_current(i: usize) { + if cfg!(test) { + OVERRIDE.with(|o| o.set(Some(i))); + } else { + CURRENT.store(i, Ordering::Relaxed); + } +} + +/// `--lang`: the language for this run, over the preference (not saved). +static FORCED: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Holds the interface language at `code` for the rest of the run, whatever the preference +/// says (`--lang`; set once, before the window opens). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub fn force(code: Option<&str>) { + if let Some(c) = code { + let _ = FORCED.set(c.to_string()); + set_language(c); + } +} + +/// Sets the interface language from the `language` preference and returns the code it +/// resolved to (`--lang`, when given, wins). Takes effect on the next string drawn, so the +/// same frame. +pub fn set_language(pref: &str) -> &'static str { + let system = if cfg!(test) { None } else { crate::platform::system_locale() }; + let pref = FORCED.get().map_or(pref, String::as_str); + let i = LANGUAGES.resolve(pref, system.as_deref()); + set_current(i); + code() +} + +/// The interface language's code (`en`, `de`, `pseudo`). +pub fn code() -> &'static str { + LANGUAGES.get(current()).code.as_str() +} + +/// Whether a `--lang` / preference value names a language this build has (or is [`AUTO`]). +pub fn known(pref: &str) -> bool { + pref.eq_ignore_ascii_case(AUTO) || LANGUAGES.find(pref).is_some() +} + +/// `(code, name in that language)` for the Preferences picker, English first. The +/// pseudo-locale is listed in debug builds and while it is in use. +pub fn offered() -> Vec<(&'static str, &'static str)> { + let now = current(); + LANGUAGES.list.iter().enumerate().filter(|(i, l)| !matches!(l.kind, Kind::Pseudo) || cfg!(debug_assertions) || *i == now).map(|(_, l)| (l.code.as_str(), l.name.as_str())).collect() +} + +/// The name of the language [`AUTO`] picks on this computer, for the picker's first entry. +pub fn system_choice() -> &'static str { + let system = if cfg!(test) { None } else { crate::platform::system_locale() }; + LANGUAGES.get(LANGUAGES.resolve(AUTO, system.as_deref())).name.as_str() +} + +/// A language's own name, for the picker (the code itself when unknown). +pub fn name_of(code: &str) -> Cow<'static, str> { + LANGUAGES.find(code).map_or_else(|| Cow::Owned(code.to_string()), |i| Cow::Borrowed(LANGUAGES.get(i).name.as_str())) +} + +// ----- lookups ---------------------------------------------------------------------------------- + +/// Pseudo-locale strings, made once each. Keys are the program's own `'static` strings, so the +/// cache is bounded by the strings the program has. +static PSEUDO_CACHE: LazyLock>> = LazyLock::new(Default::default); + +fn pseudo_static(source: &'static str) -> &'static str { + let mut cache = PSEUDO_CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.entry(source).or_insert_with(|| Box::leak(pseudo::transform(source).into_boxed_str())) +} + +impl Languages { + /// `source` in language `i` (English is the key itself: no lookup). + fn text<'a>(&'a self, i: usize, context: &str, source: &'static str) -> &'a str { + match &self.get(i).kind { + Kind::English => source, + Kind::Pseudo => pseudo_static(source), + Kind::Catalog(c) => c.get(context, source).unwrap_or(source), + } + } + + /// Run-time English in language `i`, translated on an exact match. + fn text_dyn<'a>(&'a self, i: usize, source: &'a str) -> Cow<'a, str> { + match &self.get(i).kind { + Kind::English => Cow::Borrowed(source), + Kind::Pseudo => Cow::Owned(pseudo::transform(source)), + Kind::Catalog(c) => Cow::Borrowed(c.get("", source).unwrap_or(source)), + } + } + + /// A command's label in language `i`: its `@id` row, else its label's row. + fn command<'a>(&'a self, i: usize, id: &str, label: &'static str) -> &'a str { + match &self.get(i).kind { + Kind::Catalog(c) => c.id(id).unwrap_or_else(|| c.get("", label).unwrap_or(label)), + _ => self.text(i, "", label), + } + } + + /// The plural form for `n` in language `i`. + fn count<'a>(&'a self, i: usize, one: &'static str, other: &'static str, n: u64) -> &'a str { + match self.get(i).kind { + Kind::English => { + if n == 1 { one } else { other } + } + Kind::Pseudo => pseudo_static(if n == 1 { one } else { other }), + Kind::Catalog(_) => self.plural(i, one, other, n), + } + } +} + +fn translate(context: &'static str, source: &'static str) -> &'static str { + let languages: &'static Languages = &LANGUAGES; + languages.text(current(), context, source) +} + +/// `source` in the interface language. Use [`tr!`] for literals; this is for `'static` strings +/// from tables marked with [`tr_noop!`] (tool names, menu titles, the registry's labels). +pub fn t(source: &'static str) -> &'static str { + translate("", source) +} + +/// `source` with a context word, falling back to its plain translation. +pub fn tc(context: &'static str, source: &'static str) -> &'static str { + translate(context, source) +} + +/// English that arrives at run time from below the shell (an undo step's label, a +/// confirmation's title): translated when a catalog has that exact text. +pub fn t_dyn(source: &str) -> Cow<'_, str> { + let languages: &'static Languages = &LANGUAGES; + languages.text_dyn(current(), source) +} + +/// A registry command's label: an `@id` row for its id first, else the label's own translation. +pub fn t_cmd(id: &str, label: &'static str) -> &'static str { + let languages: &'static Languages = &LANGUAGES; + languages.command(current(), id, label) +} + +/// The plural form for `n`, placeholders not yet filled (see [`trn!`]). +pub fn tn(one: &'static str, other: &'static str, n: u64) -> &'static str { + let languages: &'static Languages = &LANGUAGES; + languages.count(current(), one, other, n) +} + +/// `template` with its `{name}` placeholders filled from `args`, in one pass: a value that +/// itself contains `{name}` stays as written. A placeholder without a value stays too. +pub fn fill(template: &str, args: &[(&str, &dyn std::fmt::Display)]) -> String { + use std::fmt::Write; + let mut out = String::with_capacity(template.len() + 16); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(rest.get(..open).unwrap_or("")); + let after = rest.get(open + 1..).unwrap_or(""); + let value = after.find('}').and_then(|close| { + let name = after.get(..close)?; + args.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v, close)) + }); + match value { + Some((v, close)) => { + let _ = write!(out, "{v}"); + rest = after.get(close + 1..).unwrap_or(""); + } + None => { + out.push('{'); + rest = after; + } + } + } + out.push_str(rest); + out +} + +/// `tr!("Save")`: the literal in the interface language (`&'static str`). +/// `tr!("Saved {path}", path = p)`: the same with placeholders filled (`String`). +/// Only literals: the extractor (`scripts/i18n-extract.sh`) finds every key in the source. +macro_rules! tr { + ($s:literal) => { + $crate::i18n::t($s) + }; + ($s:literal, $($k:ident = $v:expr),+ $(,)?) => { + $crate::i18n::fill($crate::i18n::t($s), &[$((stringify!($k), &$v as &dyn std::fmt::Display)),+]) + }; +} + +/// `trc!("menu", "Open")`: a literal with a context word (craft-i18n's first column). +macro_rules! trc { + ($c:literal, $s:literal) => { + $crate::i18n::tc($c, $s) + }; +} + +/// `trn!("{n} frame", "{n} frames", count)`: the plural form for `count`, `{n}` filled with +/// it; more placeholders as in [`tr!`]. `String`. +macro_rules! trn { + ($one:literal, $other:literal, $n:expr $(, $k:ident = $v:expr)* $(,)?) => {{ + let n = $n; + let count = u64::try_from(n).unwrap_or(u64::MAX); + $crate::i18n::fill($crate::i18n::tn($one, $other, count), &[("n", &n as &dyn std::fmt::Display) $(, (stringify!($k), &$v as &dyn std::fmt::Display))*]) + }}; +} + +/// `tr_noop!("Graphite")`: the literal unchanged, marked for the extractor. For strings in +/// tables that are translated where they are drawn, with [`t`]. +macro_rules! tr_noop { + ($s:literal) => { + $s + }; +} + +// After the macros: `macro_rules!` are in scope only below their definition. +#[cfg(test)] +mod tests; diff --git a/src/i18n/plural.rs b/src/i18n/plural.rs new file mode 100644 index 00000000..5140152c --- /dev/null +++ b/src/i18n/plural.rs @@ -0,0 +1,232 @@ +//! CLDR cardinal plural rules for whole numbers, written from the public Unicode CLDR +//! `plurals.xml` rules (Unicode-3.0 data; credited in ATTRIBUTION.md). Only what a count of +//! things needs: integers, no fractions, so the operands `v`, `f` and `t` are always 0. +//! +//! A craft-i18n `@plural` row lists a language's forms in CLDR order (`zero`, `one`, `two`, +//! `few`, `many`, `other`), leaving out those whole numbers from 0 to 1000 never reach +//! (`docs/catalog-format.md` there). [`forms`] gives that list, [`index`] the form a count takes. + +/// A CLDR plural category. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Category { + Zero, + One, + Two, + Few, + Many, + Other, +} + +use Category::{Few, Many, One, Other, Two, Zero}; + +/// The rule family a language follows (several languages share each). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Rule { + /// No plural forms: Japanese, Chinese, Korean, Thai, Vietnamese, Indonesian, Lao. + None, + /// `one` for exactly 1: English, German, Spanish, Italian, the Nordic languages, Greek, … + OneIsOne, + /// `one` for 0 and 1: French, Brazilian Portuguese, Hindi, Bengali, Persian. + OneIsZeroOrOne, + /// Russian, Ukrainian: one, few, many. + EastSlavic, + /// Serbian, Croatian, Bosnian: one, few, other. + SouthSlavic, + /// Polish: one, few, many. + Polish, + /// Czech, Slovak: one, few, other (their `many` is for fractions). + CzechSlovak, + /// Lithuanian: one, few, other (its `many` is for fractions). + Lithuanian, + /// Latvian: zero, one, other. + Latvian, + /// Romanian: one, few, other. + Romanian, + /// Slovenian: one, two, few, other. + Slovenian, + /// Hebrew: one, two, other. + Hebrew, + /// Arabic: zero, one, two, few, many, other. + Arabic, +} + +/// The language part of a locale code: `pt-br` → `pt`, `sr-latn` → `sr`. +fn language(code: &str) -> &str { + code.split(['-', '_']).next().unwrap_or(code) +} + +fn rule(code: &str) -> Rule { + match language(&code.to_ascii_lowercase()) { + "ja" | "zh" | "ko" | "th" | "vi" | "id" | "lo" | "ms" | "my" | "km" => Rule::None, + "fr" | "pt" | "hi" | "bn" | "fa" | "gu" | "kn" | "zu" | "am" | "as" => { + // European Portuguese counts only 1 as `one`. + if code.eq_ignore_ascii_case("pt-pt") { Rule::OneIsOne } else { Rule::OneIsZeroOrOne } + } + "ru" | "uk" | "be" => Rule::EastSlavic, + "sr" | "hr" | "bs" | "sh" => Rule::SouthSlavic, + "pl" => Rule::Polish, + "cs" | "sk" => Rule::CzechSlovak, + "lt" => Rule::Lithuanian, + "lv" => Rule::Latvian, + "ro" | "mo" => Rule::Romanian, + "sl" => Rule::Slovenian, + "he" | "iw" => Rule::Hebrew, + "ar" => Rule::Arabic, + // English and most others: one for 1 (also the guess for a language not listed here). + _ => Rule::OneIsOne, + } +} + +/// The category whole number `n` takes in the language `code`. +pub fn category(code: &str, n: u64) -> Category { + let (m10, m100) = (n % 10, n % 100); + match rule(code) { + Rule::None => Other, + Rule::OneIsOne => { + if n == 1 { One } else { Other } + } + Rule::OneIsZeroOrOne => { + if n <= 1 { One } else { Other } + } + Rule::EastSlavic => { + if m10 == 1 && m100 != 11 { + One + } else if (2..=4).contains(&m10) && !(12..=14).contains(&m100) { + Few + } else { + Many + } + } + Rule::SouthSlavic => { + if m10 == 1 && m100 != 11 { + One + } else if (2..=4).contains(&m10) && !(12..=14).contains(&m100) { + Few + } else { + Other + } + } + Rule::Polish => { + if n == 1 { + One + } else if (2..=4).contains(&m10) && !(12..=14).contains(&m100) { + Few + } else { + Many + } + } + Rule::CzechSlovak => match n { + 1 => One, + 2..=4 => Few, + _ => Other, + }, + Rule::Lithuanian => { + if m10 == 1 && !(11..=19).contains(&m100) { + One + } else if (2..=9).contains(&m10) && !(11..=19).contains(&m100) { + Few + } else { + Other + } + } + Rule::Latvian => { + if m10 == 0 || (11..=19).contains(&m100) { + Zero + } else if m10 == 1 && m100 != 11 { + One + } else { + Other + } + } + Rule::Romanian => { + if n == 1 { + One + } else if n == 0 || (1..=19).contains(&m100) { + Few + } else { + Other + } + } + Rule::Slovenian => match m100 { + 1 => One, + 2 => Two, + 3 | 4 => Few, + _ => Other, + }, + Rule::Hebrew => match n { + 1 => One, + 2 => Two, + _ => Other, + }, + Rule::Arabic => match (n, m100) { + (0, _) => Zero, + (1, _) => One, + (2, _) => Two, + (_, 3..=10) => Few, + (_, 11..=99) => Many, + _ => Other, + }, + } +} + +/// The forms a catalog lists for `code`, in CLDR order: the categories 0 to 1000 reach. +pub fn forms(code: &str) -> &'static [Category] { + match rule(code) { + Rule::None => &[Other], + Rule::OneIsOne | Rule::OneIsZeroOrOne => &[One, Other], + Rule::EastSlavic | Rule::Polish => &[One, Few, Many], + Rule::SouthSlavic | Rule::CzechSlovak | Rule::Lithuanian | Rule::Romanian => &[One, Few, Other], + Rule::Latvian => &[Zero, One, Other], + Rule::Slovenian => &[One, Two, Few, Other], + Rule::Hebrew => &[One, Two, Other], + Rule::Arabic => &[Zero, One, Two, Few, Many, Other], + } +} + +/// Which of a catalog's forms (`forms(code)`) the count `n` takes. A category the list leaves +/// out (Spanish `many` at a million) uses the last form, `other`'s place. +pub fn index(code: &str, n: u64) -> usize { + let list = forms(code); + let c = category(code, n); + list.iter().position(|f| *f == c).unwrap_or(list.len().saturating_sub(1)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The categories 0..=1000 reach, in CLDR order, for a language. + fn reached(code: &str) -> Vec { + let all = [Zero, One, Two, Few, Many, Other]; + all.into_iter().filter(|c| (0..=1000).any(|n| category(code, n) == *c)).collect() + } + + #[test] + fn form_lists_are_exactly_the_categories_whole_numbers_reach() { + // The craft-i18n checker counts forms the same way; a mismatch would make every plural + // row of that language fall back to English. + for code in ["en", "de", "fr", "pt-br", "pt-pt", "es", "ja", "zh-hans", "ru", "uk", "sr", "sr-latn", "hr", "bs", "pl", "cs", "sk", "lt", "lv", "ro", "sl", "he", "ar", "hi", "xx"] { + assert_eq!(reached(code), forms(code).to_vec(), "{code}"); + } + // The counts craft-i18n's docs name: 1 Japanese, 2 French, 3 Russian, 6 Arabic. + assert_eq!([forms("ja").len(), forms("fr").len(), forms("ru").len(), forms("ar").len()], [1, 2, 3, 6]); + } + + #[test] + fn counts_pick_their_forms() { + assert_eq!([0, 1, 2].map(|n| category("en", n)), [Other, One, Other]); + assert_eq!([0, 1, 2].map(|n| category("fr", n)), [One, One, Other]); + assert_eq!([1, 2, 5, 11, 21, 22, 25, 112].map(|n| category("ru", n)), [One, Few, Many, Many, One, Few, Many, Many]); + assert_eq!([1, 2, 5, 12, 22, 25].map(|n| category("pl", n)), [One, Few, Many, Many, Few, Many]); + assert_eq!([1, 3, 5].map(|n| category("cs", n)), [One, Few, Other]); + assert_eq!([0, 1, 2, 3, 11, 100, 102].map(|n| category("ar", n)), [Zero, One, Two, Few, Many, Other, Other]); + assert_eq!([1, 2, 3, 5, 101, 102].map(|n| category("sl", n)), [One, Two, Few, Other, One, Two]); + assert_eq!([0, 1, 2, 19, 20, 101].map(|n| category("ro", n)), [Few, One, Few, Few, Other, Few]); + assert_eq!([0, 1, 11, 21].map(|n| category("lv", n)), [Zero, One, Zero, One]); + // Huge counts never overflow or panic. + assert_eq!(category("ar", u64::MAX), Many); + assert_eq!(index("es", 1_000_000), 1, "Spanish `many` falls to `other`"); + assert_eq!(index("ja", 1), 0); + assert_eq!(index("ru", 5), 2); + } +} diff --git a/src/i18n/pseudo.rs b/src/i18n/pseudo.rs new file mode 100644 index 00000000..6f595062 --- /dev/null +++ b/src/i18n/pseudo.rs @@ -0,0 +1,106 @@ +//! The pseudo-locale: English made to look foreign, to test the interface without a real +//! translation. Letters take accents (text that skips translation stays plain and stands out), +//! every string grows by about a third (German and Finnish run that much longer than English) +//! and is bracketed (a cut-off label loses its `]`). `{name}` placeholders are kept, so values +//! still fill in. Only Latin-1 and Latin Extended-A letters are used: every bundled face has them. + +/// The accented form of an ASCII letter (itself when Latin Extended-A has none). +fn accent(c: char) -> char { + match c { + 'a' => 'à', + 'c' => 'ç', + 'd' => 'ď', + 'e' => 'é', + 'g' => 'ğ', + 'h' => 'ĥ', + 'i' => 'î', + 'j' => 'ĵ', + 'k' => 'ķ', + 'l' => 'ľ', + 'n' => 'ñ', + 'o' => 'ö', + 'r' => 'ŕ', + 's' => 'š', + 't' => 'ţ', + 'u' => 'ü', + 'w' => 'ŵ', + 'y' => 'ý', + 'z' => 'ž', + 'A' => 'Å', + 'C' => 'Ç', + 'D' => 'Ď', + 'E' => 'É', + 'G' => 'Ğ', + 'H' => 'Ĥ', + 'I' => 'Î', + 'J' => 'Ĵ', + 'K' => 'Ķ', + 'L' => 'Ľ', + 'N' => 'Ñ', + 'O' => 'Ö', + 'R' => 'Ŕ', + 'S' => 'Š', + 'T' => 'Ţ', + 'U' => 'Ü', + 'W' => 'Ŵ', + 'Y' => 'Ý', + 'Z' => 'Ž', + other => other, + } +} + +/// Whether `c` is one of the accented letters [`transform`] writes (the audits' test). +#[cfg(test)] +pub fn is_accented(c: char) -> bool { + !c.is_ascii() && ('a'..='z').chain('A'..='Z').any(|a| accent(a) == c) +} + +/// `Save` → `[Šàvé ~~]`; `Saved {path}` → `[Šàvéď {path} ~~~~]`. Line breaks are kept. +pub fn transform(s: &str) -> String { + let mut out = String::with_capacity(s.len() * 2 + 4); + out.push('['); + let mut letters = 0usize; + let mut in_placeholder = false; + for c in s.chars() { + match c { + '{' => in_placeholder = true, + '}' => in_placeholder = false, + _ => {} + } + if in_placeholder || !c.is_ascii_alphabetic() { + out.push(c); + } else { + letters += 1; + out.push(accent(c)); + } + } + // About a third longer, at least one mark, and never absurdly long for a paragraph. + let pad = (letters.div_ceil(3)).clamp(1, 40); + out.push(' '); + out.extend(std::iter::repeat_n('~', pad)); + out.push(']'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn letters_take_accents_and_placeholders_survive() { + assert_eq!(transform("Save"), "[Šàvé ~~]"); + assert_eq!(transform("Saved {path}"), "[Šàvéď {path} ~~]"); + assert_eq!(transform("{n} frames"), "[{n} fŕàméš ~~]"); + assert!(transform("A\nB").contains('\n')); + assert!(transform("Export…").ends_with("~~]") && transform("Export…").contains('…')); + assert!(transform("Save").chars().any(is_accented)); + assert!(!"Save".chars().any(is_accented)); + assert!(!"ß".chars().any(is_accented), "only our own marks count"); + // Every letter we write is in Latin-1 Supplement or Latin Extended-A (U+00C0..U+017F). + for c in ('a'..='z').chain('A'..='Z').map(accent).filter(|c| !c.is_ascii()) { + assert!(('\u{c0}'..='\u{17f}').contains(&c), "{c}"); + } + // A paragraph grows, but not without bound. + assert!(transform(&"word ".repeat(200)).len() < "word ".repeat(200).len() * 2 + 50); + } +} diff --git a/src/i18n/scan.rs b/src/i18n/scan.rs new file mode 100644 index 00000000..94e645cc --- /dev/null +++ b/src/i18n/scan.rs @@ -0,0 +1,356 @@ +//! A small Rust lexer for the shell's sources (tests only): finds every string literal, with +//! what comes before and after it, so one pass serves both the guideline that interface text +//! is translated (`tests.rs`) and the extractor that lists strings for translators. +//! +//! It knows comments, strings with escapes and line continuations, raw strings, byte strings, +//! and char literals versus lifetimes; it never panics on odd input. + +/// A string literal in the source. +#[derive(Clone, Debug)] +pub struct Literal { + /// 1-based line of the opening quote. + pub line: usize, + /// The literal's value (escapes resolved). + pub value: String, + /// The code between the previous literal (or the start of the file) and this one, with + /// comments left out. + pub before: String, + /// The rest of the line after the closing quote. + pub after: String, + /// The line up to the opening quote. + pub line_before: String, + /// A byte string (`b"…"`): never interface text. + pub bytes: bool, +} + +/// How a literal reaches the interface, from the macro around it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + /// `tr!("…")`, `tr_noop!("…")`: a source text. + Source, + /// `trc!("menu", …)`: the context word. + Context, + /// `trc!(…, "Open")`: a source text with the context before it. + ContextSource, + /// `trn!("{n} frame", …)`: a plural's `one` form. + One, + /// `trn!(…, "{n} frames", n)`: a plural's `other` form. + Other, + /// Not in a translation macro. + Plain, +} + +/// Every literal in `src`, in order. +pub fn literals(src: &str) -> Vec { + let chars: Vec = src.chars().collect(); + let mut out = Vec::new(); + let mut before = String::new(); + let mut line = 1usize; + let mut line_start = 0usize; + let mut i = 0usize; + let at = |k: usize| chars.get(k).copied().unwrap_or('\0'); + let slice = |a: usize, b: usize| chars.get(a..b.min(chars.len())).map(|s| s.iter().collect::()).unwrap_or_default(); + let rest_of_line = |from: usize| { + let end = (from..chars.len()).find(|k| at(*k) == '\n').unwrap_or(chars.len()); + slice(from, end) + }; + while i < chars.len() { + let c = at(i); + // Comments. + if c == '/' && at(i + 1) == '/' { + while i < chars.len() && at(i) != '\n' { + i += 1; + } + continue; + } + if c == '/' && at(i + 1) == '*' { + let mut depth = 0usize; + while i < chars.len() { + if at(i) == '/' && at(i + 1) == '*' { + depth += 1; + i += 2; + } else if at(i) == '*' && at(i + 1) == '/' { + depth = depth.saturating_sub(1); + i += 2; + if depth == 0 { + break; + } + } else { + if at(i) == '\n' { + line += 1; + line_start = i + 1; + } + i += 1; + } + } + continue; + } + let ident_before = i > 0 && (at(i - 1).is_alphanumeric() || at(i - 1) == '_'); + // Raw strings: r"…", r#"…"#, br"…". + let raw_start = if c == 'r' && !ident_before && (at(i + 1) == '"' || at(i + 1) == '#') { + Some((i + 1, false)) + } else if c == 'b' && !ident_before && at(i + 1) == 'r' && (at(i + 2) == '"' || at(i + 2) == '#') { + Some((i + 2, true)) + } else { + None + }; + if let Some((mut k, bytes)) = raw_start { + let mut hashes = 0usize; + while at(k) == '#' { + hashes += 1; + k += 1; + } + if at(k) == '"' { + let (start_line, line_before) = (line, slice(line_start, i)); + let body = k + 1; + let mut j = body; + loop { + if j >= chars.len() { + break; + } + if at(j) == '"' && (1..=hashes).all(|h| at(j + h) == '#') { + break; + } + if at(j) == '\n' { + line += 1; + line_start = j + 1; + } + j += 1; + } + let value = slice(body, j); + let end = (j + 1 + hashes).min(chars.len()); + out.push(Literal { line: start_line, value, before: std::mem::take(&mut before), after: rest_of_line(end), line_before, bytes }); + i = end; + continue; + } + } + // Ordinary and byte strings. + if c == '"' { + let bytes = ident_before && at(i - 1) == 'b' && (i < 2 || !(at(i - 2).is_alphanumeric() || at(i - 2) == '_')); + if bytes { + before.pop(); + } + let (start_line, line_before) = (line, slice(line_start, i)); + let mut value = String::new(); + let mut j = i + 1; + while j < chars.len() && at(j) != '"' { + let ch = at(j); + if ch == '\n' { + line += 1; + line_start = j + 1; + } + if ch != '\\' { + value.push(ch); + j += 1; + continue; + } + let e = at(j + 1); + j += 2; + match e { + 'n' => value.push('\n'), + 't' => value.push('\t'), + 'r' => value.push('\r'), + '0' => value.push('\0'), + '\\' | '"' | '\'' => value.push(e), + 'x' => { + let hex = slice(j, j + 2); + value.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)); + j += 2; + } + 'u' => { + // \u{…} + let close = (j..chars.len().min(j + 10)).find(|k| at(*k) == '}').unwrap_or(j); + let hex = slice(j + 1, close); + value.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)); + j = close + 1; + } + '\n' => { + // A line continuation: the newline and the next line's indent go. + line += 1; + line_start = j; + while at(j) == ' ' || at(j) == '\t' { + j += 1; + } + } + _ => {} + } + } + let end = (j + 1).min(chars.len()); + out.push(Literal { line: start_line, value, before: std::mem::take(&mut before), after: rest_of_line(end), line_before, bytes }); + i = end; + continue; + } + // Char literals ('x', '\n', '"') and lifetimes ('a, 'static). + if c == '\'' { + if at(i + 1) == '\\' { + // Past the backslash and the escaped character, to the closing quote. + let mut j = i + 3; + while j < chars.len() && at(j) != '\'' && at(j) != '\n' { + j += 1; + } + before.push_str("' '"); + i = j + 1; + continue; + } + if at(i + 2) == '\'' { + before.push_str("' '"); + i += 3; + continue; + } + } + if c == '\n' { + line += 1; + line_start = i + 1; + } + before.push(c); + // Only the end of the gap matters (which macro opened); keep it short. + if before.len() > 400 { + let cut = before.char_indices().nth(before.chars().count().saturating_sub(200)).map_or(0, |(k, _)| k); + before = before.split_off(cut); + } + i += 1; + } + out +} + +/// What each literal is to the translation macros, in the same order. +pub fn roles(lits: &[Literal]) -> Vec { + let mut out: Vec = Vec::with_capacity(lits.len()); + for l in lits { + let b = l.before.trim_end(); + let prev = out.last().copied(); + // The macro's name, not the end of a longer one (`include_str!(`). + let opens = |m: &str| b.strip_suffix(m).is_some_and(|rest| !rest.ends_with(|c: char| c.is_alphanumeric() || c == '_')); + let role = if opens("tr!(") || opens("tr_noop!(") { + Role::Source + } else if opens("trc!(") { + Role::Context + } else if opens("trn!(") { + Role::One + } else if b.trim() == "," && prev == Some(Role::Context) { + Role::ContextSource + } else if b.trim() == "," && prev == Some(Role::One) { + Role::Other + } else { + Role::Plain + }; + out.push(role); + } + out +} + +/// A translatable key found in the source: `(context, source)`, or a plural's `one|other`. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Key { + Text { context: String, source: String }, + Plural { one: String, other: String }, +} + +/// Every key the macros in `src` use. +pub fn keys(src: &str) -> Vec { + let lits = literals(src); + let roles = roles(&lits); + let mut out = Vec::new(); + for (k, (l, r)) in lits.iter().zip(&roles).enumerate() { + let prev = k.checked_sub(1).and_then(|p| lits.get(p)).map(|p| p.value.clone()).unwrap_or_default(); + match r { + Role::Source => out.push(Key::Text { context: String::new(), source: l.value.clone() }), + Role::ContextSource => out.push(Key::Text { context: prev, source: l.value.clone() }), + Role::Other => out.push(Key::Plural { one: prev, other: l.value.clone() }), + Role::Context | Role::One | Role::Plain => {} + } + } + out +} + +/// Key names and combinations: data, not prose (ADR 0005), and shown through +/// `platform::shortcut_label`. +fn is_key_name(s: &str) -> bool { + const KEYS: [&str; 20] = ["Enter", "Escape", "Esc", "Space", "Tab", "Delete", "Backspace", "Home", "End", "PageUp", "PageDown", "Insert", "Up", "Down", "Left", "Right", "Shift", "Ctrl", "Alt", "Cmd"]; + KEYS.contains(&s) || ["Ctrl+", "Shift+", "Alt+", "Cmd+", "Option+"].iter().any(|m| s.contains(m)) +} + +/// Whether a literal reads as interface prose: words a person reads, rather than an id, a +/// path, a key, a number or a format. +pub fn is_prose(s: &str) -> bool { + let has_word = s.as_bytes().windows(2).any(|w| w.iter().all(u8::is_ascii_lowercase)); + if !has_word || is_key_name(s.trim()) { + return false; + } + // Units and formats (` pt`, `{s} fps`, `{n} ms`): what is left without the placeholders is + // a short symbol, data rather than prose. + let mut bare = s.to_string(); + while let (Some(a), Some(b)) = (bare.find('{'), bare.find('}')) { + if b < a { + break; + } + bare.replace_range(a..=b, ""); + } + let bare = bare.trim(); + if !bare.contains(' ') && bare.chars().count() <= 3 && !bare.starts_with(|c: char| c.is_ascii_uppercase()) { + return false; + } + let spaced = s.contains(' '); + if !spaced && s.contains(['/', '\\', '.', '_', ':', '=', '#', '<', '>']) && !s.ends_with('…') { + return false; + } + spaced || s.starts_with(|c: char| c.is_ascii_uppercase()) || s.ends_with('…') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn literals_comments_raw_strings_and_chars() { + let src = r####" +// "in a comment" +/* "block /* nested */ comment" */ +let a = tr!("Save"); +let b = 'x'; let q = '"'; let e = '\''; fn f<'a>(x: &'a str) {} +let c = r#"raw "quoted""#; +let d = b"bytes"; +let m = trn!("{n} frame", + "{n} frames", n); +let t = trc!("menu", "Open"); +let s = "a \"quote\" and \u{2026} and \ + continued"; +let n = tr_noop!("Graphite"); +let f = include_str!("../NOTICE"); let g = crate::i18n::tr!("Path"); +"####; + let lits = literals(src); + let values: Vec<&str> = lits.iter().map(|l| l.value.as_str()).collect(); + assert_eq!(values, ["Save", "raw \"quoted\"", "bytes", "{n} frame", "{n} frames", "menu", "Open", "a \"quote\" and … and continued", "Graphite", "../NOTICE", "Path"]); + assert!(lits.get(2).is_some_and(|l| l.bytes)); + assert_eq!(lits.first().map(|l| l.line), Some(4)); + assert_eq!(lits.get(4).map(|l| l.line), Some(9)); + let keys = keys(src); + assert_eq!( + keys, + [ + Key::Text { context: String::new(), source: "Save".into() }, + Key::Plural { one: "{n} frame".into(), other: "{n} frames".into() }, + Key::Text { context: "menu".into(), source: "Open".into() }, + Key::Text { context: String::new(), source: "Graphite".into() }, + Key::Text { context: String::new(), source: "Path".into() }, + ] + ); + } + + #[test] + fn odd_input_never_panics() { + for src in ["\"", "r#\"", "'", "'\\", "/*", "\"\\u{", "\"\\x", "b", "r", "br#", "\"\\", "é\"é\\\né"] { + let _ = literals(src); + } + } + + #[test] + fn prose_is_told_from_ids_keys_and_paths() { + for s in ["Save", "Add", "Save As…", "Could not open {name}: {e}", "Zoom in", "Export…"] { + assert!(is_prose(s), "{s}"); + } + for s in ["edit.undo", "prefs_ui_font", "Ctrl+K", "Enter", "{}", "{n} %", "F1", "file.anicraft", "Insert/Timeline", "x", "OK", "wgpu", "#ff0000", " pt", "{s} fps"] { + assert!(!is_prose(s), "{s}"); + } + } +} diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs new file mode 100644 index 00000000..45096bc0 --- /dev/null +++ b/src/i18n/tests.rs @@ -0,0 +1,773 @@ +//! The localisation guideline (every interface string goes through `tr!`), the extractor that +//! lists strings for translators (`scripts/i18n-extract.sh`), and tests of the lookup. + +use super::scan::{self, Key, Literal, Role}; +use super::*; +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +fn src_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("src") +} + +/// Every shell source file the guideline covers: all of `src/` but the i18n module itself and +/// test-only files. Read from disk, so a new file is covered without a list to keep. +fn shell_sources() -> Vec<(String, String)> { + fn walk(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + if p.file_name().is_some_and(|n| n != "i18n") { + walk(&p, out); + } + } else if p.extension().is_some_and(|x| x == "rs") && !p.file_stem().is_some_and(|s| s.to_string_lossy().ends_with("_tests")) { + out.push(p); + } + } + } + let mut files = Vec::new(); + walk(&src_dir(), &mut files); + files.sort(); + let mut out = Vec::new(); + for f in files { + let name = f.strip_prefix(src_dir()).map_or_else(|_| f.display().to_string(), |p| p.display().to_string().replace('\\', "/")); + if let Ok(text) = std::fs::read_to_string(&f) { + out.push((name, without_tests(&text))); + } + } + assert!(out.len() > 25, "the shell's sources were not found under {}", src_dir().display()); + out +} + +/// A file without its `#[cfg(test)] mod … {` block at the end (tests aren't interface). +fn without_tests(src: &str) -> String { + let lines: Vec<&str> = src.lines().collect(); + let cut = lines.windows(2).position(|w| w.first().is_some_and(|l| l.trim() == "#[cfg(test)]") && w.get(1).is_some_and(|l| l.trim_start().starts_with("mod ") && l.trim_end().ends_with('{'))); + match cut { + Some(n) => lines.get(..n).unwrap_or_default().join("\n"), + None => src.to_string(), + } +} + +/// Code before a literal, on its line, that makes it something other than interface text: +/// logs and console output, ids and keys, commands and their parameters, attributes. +const NOT_UI: &[&str] = &[ + "eprintln!(", "println!(", "print!(", "panic!(", "assert", "unreachable!(", "Id::new(", "id_salt(", "persistent_id(", "json!(", "execute(", "perform(", "invoke(", ".run(", "find_command(", "#[", "env!(", "include_str!(", "include_bytes!(", "concat!(", "var(", + "contains(", "starts_with(", "ends_with(", "strip_prefix(", "strip_suffix(", "matches!(", "== ", "!= ", +]; + +/// Whether a prose literal outside the macros is allowed: not interface text by its context, +/// or marked `i18n-exempt` (with the reason) on its line or the line above. +fn exempt(l: &Literal, lines: &[&str]) -> bool { + let marked = |n: usize| n.checked_sub(1).and_then(|k| lines.get(k)).is_some_and(|t| t.contains("i18n-exempt")); + if marked(l.line) || marked(l.line.saturating_sub(1)) { + return true; + } + let after = l.after.trim_start(); + // A match arm's pattern (`"File" =>`, `"a" | "b"`, `"x" if …`). + if after.starts_with("=>") || after.starts_with('|') || after.starts_with("if ") { + return true; + } + NOT_UI.iter().any(|m| l.line_before.contains(m)) || l.value == "AniCraft" +} + +#[test] +fn every_interface_string_goes_through_tr() { + // docs/localisation.md › Writing interface text. Text a person reads is written + // `tr!("…")` (or `tr_noop!` in a table, `trn!` for counts); this finds prose literals that + // aren't, so a new label can't skip translation unnoticed. + let mut found = Vec::new(); + for (file, src) in shell_sources() { + let lines: Vec<&str> = src.lines().collect(); + let lits = scan::literals(&src); + let roles = scan::roles(&lits); + for (l, r) in lits.iter().zip(&roles) { + if *r == Role::Plain && !l.bytes && scan::is_prose(&l.value) && !exempt(l, &lines) { + let shown: String = l.value.chars().take(70).collect(); + found.push(format!("src/{file}:{}: {shown:?}", l.line)); + } + } + } + assert!( + found.is_empty(), + "{} interface strings not routed through tr!/trn!/tr_noop! (or marked `// i18n-exempt: why` when not interface text):\n{}", + found.len(), + found.join("\n") + ); +} + +/// Every key: the macros' literals in the shell, the registry's labels and menu names. +fn all_keys() -> BTreeSet { + let mut keys: BTreeSet = shell_sources().iter().flat_map(|(_, src)| scan::keys(src)).collect(); + let mut add = |s: &str| { + keys.insert(Key::Text { context: String::new(), source: s.to_string() }); + }; + for c in anicraft_engine::commands() { + add(c.label); + c.menu.split('/').filter(|p| !p.is_empty()).for_each(&mut add); + } + // Labels from below the shell that it translates where it draws them (`i18n::t`). + use anicraft_engine::doc::{self, actions}; + use anicraft_engine::{cmds_brush::PaintMode, cmds_erase::EraseMode}; + doc::BlendMode::ALL.iter().for_each(|m| add(m.label())); + doc::Filter::KINDS.iter().for_each(|(_, l)| add(l)); + doc::FilterSide::ALL.iter().for_each(|s| add(s.label())); + doc::Easing::PRESETS.iter().for_each(|(n, _)| add(n)); + for e in doc::SoundEffect::PRESETS.iter().chain([&doc::SoundEffect::Custom(Vec::new())]) { + add(e.label()); + add(e.hint()); + } + add(&doc::Easing::Linear.label()); + doc::Property::ALL.iter().for_each(|p| add(p.label())); + doc::ProfilePreset::ALL.iter().for_each(|p| add(p.label())); + doc::Cap::ALL.iter().for_each(|c| add(c.label())); + doc::Join::ALL.iter().for_each(|j| add(j.label())); + doc::DashKind::ALL.iter().for_each(|k| add(k.label())); + for s in doc::SoundSync::ALL { + add(s.label()); + add(s.hint()); + } + [doc::SoundFormat::Wav, doc::SoundFormat::Ogg, doc::SoundFormat::Mp3].iter().for_each(|f| add(f.label())); + for e in actions::ButtonEvent::ALL { + add(e.label()); + add(e.hint()); + } + actions::KINDS.iter().for_each(|(_, l)| add(l)); + actions::Property::ALL.iter().for_each(|p| add(p.label())); + actions::Language::ALL.iter().for_each(|l| add(l.label())); + for m in EraseMode::ALL { + add(m.label()); + add(m.hint()); + } + for m in PaintMode::ALL { + add(m.label()); + add(m.hint()); + } + keys +} + +#[test] +fn every_key_is_a_valid_catalog_source() { + // A key a catalog row could never match (unpaired braces, a plural whose forms disagree) + // would stay English in every language. + let keys = all_keys(); + assert!(keys.len() > 300, "only {} keys found", keys.len()); + let mut bad = Vec::new(); + for k in &keys { + let row = match k { + Key::Text { context, source } => format!("{context}\t{}\t{}", escape(source), escape(source)), + Key::Plural { one, other } => format!("@plural\t{}|{}\t{}|{}", escape(one), escape(other), escape(one), escape(other)), + }; + let (rows, problems) = catalog::parse(&row); + if rows.len() != 1 { + bad.push(format!("{k:?}: {problems:?}")); + } + } + assert!(bad.is_empty(), "keys no catalog row can translate:\n{}", bad.join("\n")); +} + +fn escape(s: &str) -> String { + s.replace('\\', "\\\\").replace('\n', "\\n").replace('\t', "\\t") +} + +fn row(k: &Key) -> (String, String) { + match k { + Key::Text { context, source } => (context.clone(), escape(source)), + Key::Plural { one, other } => ("@plural".into(), format!("{}|{}", escape(one), escape(other))), + } +} + +const HEADER: &str = "\ +# () interface catalog for AniCraft. +# Columns, separated by a TAB: context English source text translation +# context usually empty. `@plural`, `@id` and `@msg` mean something to the apps; any other +# word is a label that tells apart two meanings of the same English. +# escapes \\n \\t \\\\ inside a column. `{name}` placeholders must appear in both columns (in any +# order), and a trailing \"…\" in one needs one in the other. +# @plural English `one|other`; the translation lists this language's plural forms, `|`-separated. +# Lines starting with # and blank lines are ignored. A missing entry shows in English. +# +# Clean room: every entry was written from the plain meaning of the English text in ordinary +# computing vocabulary. No other product's localisation, string table or translated UI was +# consulted or copied; add entries the same way. +"; + +/// A craft-i18n locale's merged catalog, read from a checkout on disk: the base language's +/// files, then the locale's, shared before AniCraft's. +fn disk_catalog(locales: &Path, code: &str) -> (Catalog, Vec) { + let read = |c: &str, f: &str| std::fs::read_to_string(locales.join(c).join(f)).map(|t| catalog::parse(&t).0).unwrap_or_default(); + let mut cat = Catalog::default(); + let mut chain = vec![code.to_string()]; + if let Some(base) = regional_base(code) { + chain.insert(0, base.to_string()); + } + for c in &chain { + cat.merge(read(c, "common.tsv")); + cat.merge(read(c, "anicraft.tsv")); + } + (cat, read(code, "anicraft.tsv")) +} + +fn translated(cat: &Catalog, k: &Key) -> bool { + match k { + Key::Text { context, source } => cat.get(context, source).is_some(), + Key::Plural { one, other } => cat.plural(one, other).is_some(), + } +} + +#[test] +#[ignore = "a tool, run by scripts/i18n-extract.sh"] +fn extract() { + // Writes every interface string as a craft-i18n catalog template (each row commented out, + // as craft-i18n's starter files are) to $ANICRAFT_I18N_OUT, or prints it. With + // $CRAFT_I18N_DIR, prints how much of AniCraft each craft-i18n locale already translates + // (its shared catalog counts) and the stale rows of AniCraft's own catalogs; with + // $ANICRAFT_I18N_LOCALE too, the template lists only what that locale is missing. + let keys = all_keys(); + let checkout = std::env::var_os("CRAFT_I18N_DIR").map(|d| PathBuf::from(d).join("locales")); + let only = std::env::var("ANICRAFT_I18N_LOCALE").ok().map(|l| l.to_ascii_lowercase()); + let mut missing_in: Option = None; + if let Some(locales) = &checkout { + let mut codes: Vec = std::fs::read_dir(locales).map(|r| r.flatten().filter(|e| e.path().is_dir()).map(|e| e.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + codes.sort(); + println!("locale translated stale (of {} AniCraft strings; READY = offered once it has anicraft.tsv)", keys.len()); + for code in &codes { + let (cat, own) = disk_catalog(locales, code); + let n = keys.iter().filter(|k| translated(&cat, k)).count(); + let stale = own.iter().filter(|r| !r.context.starts_with('@') && !keys.contains(&Key::Text { context: r.context.clone(), source: r.source.clone() })).count(); + let ready = if super::ready(code, READY) { "READY" } else { "" }; + println!("{code:<10} {n:>5} ({:>3} %) {stale:>8} {ready}", n * 100 / keys.len().max(1)); + if only.as_deref() == Some(code.as_str()) { + missing_in = Some(cat); + } + } + } + let mut text = String::from(HEADER); + text.push('\n'); + let mut rows = 0; + for k in &keys { + if missing_in.as_ref().is_some_and(|c| translated(c, k)) { + continue; + } + let (context, source) = row(k); + text.push_str(&format!("#{context}\t{source}\t\n")); + rows += 1; + } + match std::env::var_os("ANICRAFT_I18N_OUT") { + Some(out) => { + let out = PathBuf::from(out); + if let Some(dir) = out.parent() { + let _ = std::fs::create_dir_all(dir); + } + std::fs::write(&out, text).unwrap_or_else(|e| panic!("could not write {}: {e}", out.display())); + println!("wrote {rows} strings to {}", out.display()); + } + None => print!("{text}"), + } +} + +// ----- lookup ----------------------------------------------------------------------------------- + +const DE_COMMON: &str = "@id\tlanguage.name\tDeutsch\n\tSave\tSpeichern\n\tOpen\tÖffnen\n@plural\t{n} frame|{n} frames\t{n} Bild|{n} Bilder\n"; +const DE_APP: &str = "\tOpen\tDatei öffnen\n\tSaved {path}\t{path} gespeichert\n@id\tedit.undo\tRückgängig\n"; +const PT_COMMON: &str = "@id\tlanguage.name\tPortuguês\n\tSave\tGuardar\n\tOpen\tAbrir\n"; +const PT_BR_APP: &str = "@id\tlanguage.name\tPortuguês (Brasil)\n\tSave\tSalvar\n@plural\t{n} frame|{n} frames\t{n} quadro|{n} quadros\n"; +const RU_APP: &str = "@id\tlanguage.name\tРусский\n@plural\t{n} frame|{n} frames\t{n} кадр|{n} кадра|{n} кадров\n@plural\t{n} layer|{n} layers\t{n} слой|{n} слоя\n"; + +fn fixture() -> Languages { + let embedded = [("de", DE_COMMON, DE_APP), ("pt", PT_COMMON, ""), ("pt-BR", "", PT_BR_APP), ("ru", "", RU_APP), ("ar", "\tSave\tحفظ\n", "\tOpen\tفتح\n"), ("fr", "\tSave\tEnregistrer\n", "")]; + let (l, problems) = Languages::new(&embedded, READY); + assert!(problems.is_empty(), "{problems:?}"); + l +} + +#[test] +fn offered_languages_have_their_own_catalog_and_a_ready_script() { + let l = fixture(); + let codes: Vec<&str> = l.list.iter().map(|x| x.code.as_str()).collect(); + // French has only shared strings and Portuguese is a fallback: neither is offered. Arabic + // needs right-to-left layout egui doesn't have yet. + assert_eq!(codes, ["en", "de", "pt-br", "ru", "pseudo"]); + let names: Vec<&str> = l.list.iter().map(|x| x.name.as_str()).collect(); + assert_eq!(names, ["English", "Deutsch", "Português (Brasil)", "Русский", "Pseudo-locale (layout test)"]); +} + +#[test] +fn lookups_fall_back_from_app_to_shared_to_base_language_to_english() { + let l = fixture(); + let (de, pt_br, ru) = (1, 2, 3); + assert_eq!(l.lookup(de, "", "Save"), Some("Speichern"), "shared"); + assert_eq!(l.lookup(de, "", "Open"), Some("Datei öffnen"), "the app's row wins over the shared one"); + assert_eq!(l.lookup(de, "menu", "Open"), Some("Datei öffnen"), "a context falls back to the plain row"); + assert_eq!(l.lookup(de, "", "Missing"), None); + assert_eq!(l.lookup(pt_br, "", "Save"), Some("Salvar")); + assert_eq!(l.lookup(pt_br, "", "Open"), Some("Abrir"), "from the base language"); + assert_eq!(l.lookup(0, "", "Save"), None, "English has no catalog"); + assert_eq!(l.lookup(99, "", "Save"), None, "an index out of range is English"); + // Plurals by each language's rules; a row with the wrong number of forms is English. + assert_eq!(l.plural(de, "{n} frame", "{n} frames", 1), "{n} Bild"); + assert_eq!(l.plural(de, "{n} frame", "{n} frames", 0), "{n} Bilder"); + assert_eq!(l.plural(pt_br, "{n} frame", "{n} frames", 0), "{n} quadro", "Portuguese counts 0 as one"); + assert_eq!([1, 3, 5, 21].map(|n| l.plural(ru, "{n} frame", "{n} frames", n)), ["{n} кадр", "{n} кадра", "{n} кадров", "{n} кадр"]); + assert_eq!(l.plural(ru, "{n} layer", "{n} layers", 5), "{n} layers", "two forms for Russian: skipped"); + assert_eq!(l.plural(0, "{n} frame", "{n} frames", 1), "{n} frame"); +} + +#[test] +fn every_lookup_kind_reads_the_catalog() { + // The same paths `tr!`, `t_dyn`, `t_cmd` and `trn!` take with a catalog built in. + let l = fixture(); + let (de, pseudo) = (1, l.list.len() - 1); + assert_eq!(l.text(de, "", "Save"), "Speichern"); + assert_eq!(l.text(de, "menu", "Nothing"), "Nothing"); + assert_eq!(l.text(0, "", "Save"), "Save"); + assert_eq!(l.text(pseudo, "", "Save"), "[Šàvé ~~]"); + assert_eq!(l.text_dyn(de, "Open"), "Datei öffnen"); + assert_eq!(l.text_dyn(de, "Delete Layer"), "Delete Layer"); + assert_eq!(l.text_dyn(0, "Open"), "Open"); + assert_eq!(l.text_dyn(pseudo, "Open"), "[Öpéñ ~~]"); + assert_eq!(l.command(de, "edit.undo", "Undo"), "Rückgängig", "an @id row first"); + assert_eq!(l.command(de, "file.save", "Save"), "Speichern", "then the label"); + assert_eq!(l.command(de, "file.other", "Other"), "Other"); + assert_eq!(l.command(0, "edit.undo", "Undo"), "Undo"); + assert_eq!(l.count(de, "{n} frame", "{n} frames", 2), "{n} Bilder"); + assert_eq!(l.count(0, "{n} frame", "{n} frames", 1), "{n} frame"); + assert_eq!(l.count(pseudo, "{n} frame", "{n} frames", 1), "[{n} fŕàmé ~~]"); +} + +#[test] +fn system_locales_and_preferences_resolve() { + let l = fixture(); + let code = |pref: &str, sys: Option<&str>| l.get(l.resolve(pref, sys)).code.clone(); + assert_eq!(code(AUTO, Some("de-DE")), "de"); + assert_eq!(code(AUTO, Some("de_AT.UTF-8")), "de"); + assert_eq!(code(AUTO, Some("pt-BR")), "pt-br"); + assert_eq!(code(AUTO, Some("pt-PT")), "en", "Portuguese itself isn't offered"); + assert_eq!(code(AUTO, Some("ru")), "ru"); + assert_eq!(code(AUTO, Some("ar-EG")), "en", "not offered yet"); + assert_eq!(code(AUTO, Some("C")), "en"); + assert_eq!(code(AUTO, Some("zh-TW")), "en", "Chinese isn't offered yet (it needs a font)"); + assert_eq!(code(AUTO, Some("zh_CN")), "en"); + assert_eq!(code(AUTO, Some("")), "en"); + assert_eq!(code(AUTO, None), "en"); + assert_eq!(code("DE", Some("ru-RU")), "de", "a chosen language wins over the system's"); + assert_eq!(code("pt_BR", None), "pt-br"); + assert_eq!(code("xx-new", Some("ru-RU")), "ru", "a code this build lacks follows the system"); + assert_eq!(code(PSEUDO, Some("de")), "pseudo"); + assert_eq!(code(AUTO, Some("pseudo")), "en", "the system never picks the pseudo-locale"); +} + +#[test] +fn the_interface_language_changes_lookups_on_this_thread() { + // Built without catalogs (tests don't set CRAFT_I18N_DIR): English and the pseudo-locale. + assert_eq!(set_language("xx"), "en"); + assert_eq!(tr!("Save"), "Save"); + assert_eq!(tr!("Saved {path}", path = "a.anicraft"), "Saved a.anicraft"); + assert_eq!(trn!("{n} frame", "{n} frames", 1), "1 frame"); + assert_eq!(trn!("{n} frame", "{n} frames", 3usize), "3 frames"); + assert_eq!(trc!("menu", "Open"), "Open"); + assert_eq!(tr_noop!("Graphite"), "Graphite"); + assert_eq!(t_cmd("edit.undo", "Undo"), "Undo"); + assert_eq!(t_dyn("Delete Layer"), "Delete Layer"); + assert!(known(AUTO) && known("en") && known("pseudo") && !known("xx")); + + assert_eq!(set_language(PSEUDO), "pseudo"); + assert_eq!(tr!("Save"), "[Šàvé ~~]"); + assert!(std::ptr::eq(tr!("Save"), tr!("Save")), "made once, then cached"); + assert_eq!(tr!("Saved {path}", path = "a.anicraft"), "[Šàvéď a.anicraft ~~]", "values are filled after the lookup, untouched"); + assert_eq!(trn!("{n} frame", "{n} frames", 2), "[2 fŕàméš ~~]"); + assert_eq!(t_dyn("Undo"), "[Üñďö ~~]"); + assert_eq!(t_cmd("edit.undo", "Undo"), "[Üñďö ~~]"); + assert!(offered().iter().any(|(c, _)| *c == PSEUDO), "listed while in use"); + assert_eq!(name_of("pseudo"), "Pseudo-locale (layout test)"); + assert_eq!(name_of("zz"), "zz"); + + set_language(AUTO); + assert_eq!(code(), "en", "tests always follow English as the system language"); + assert_eq!(offered().first(), Some(&("en", "English"))); +} + +#[test] +fn fill_is_one_pass_and_keeps_what_it_cannot_fill() { + assert_eq!(fill("{a} and {b}", &[("a", &"{b}"), ("b", &2)]), "{b} and 2"); + assert_eq!(fill("{missing} {", &[]), "{missing} {"); + assert_eq!(fill("}{x}{", &[("x", &"y")]), "}y{"); + assert_eq!(fill("", &[]), ""); + assert_eq!(fill("é{n}é", &[("n", &1)]), "é1é"); +} + +#[test] +fn lookups_are_cheap_enough_for_every_label_every_frame() { + // A busy frame draws a few hundred labels. Measured, not asserted tightly (CI machines vary): + // the bound only catches an accidental quadratic lookup. + let l = fixture(); + let start = web_time::Instant::now(); + let mut hits = 0usize; + for _ in 0..100_000 { + hits += usize::from(l.lookup(1, "", "Open").is_some()) + usize::from(l.lookup(1, "", "Not in the catalog").is_some()); + } + let catalog_ns = start.elapsed().as_nanos() / 200_000; + set_language(PSEUDO); + let start = web_time::Instant::now(); + for _ in 0..100_000 { + hits += tr!("Save").len(); + } + let pseudo_ns = start.elapsed().as_nanos() / 100_000; + set_language(ENGLISH); + let start = web_time::Instant::now(); + for _ in 0..100_000 { + hits += tr!("Save").len(); + } + let english_ns = start.elapsed().as_nanos() / 100_000; + eprintln!("lookup: catalog {catalog_ns} ns, pseudo (cached) {pseudo_ns} ns, English {english_ns} ns per string"); + assert!(hits > 0); + assert!(catalog_ns < 20_000 && pseudo_ns < 20_000, "lookups this slow would cost a frame"); +} + +// ----- the whole window in the pseudo-locale ------------------------------------------------------ + +/// What the document itself says (a document as JSON): its names, labels and text. +fn strings_in(v: &serde_json::Value, out: &mut BTreeSet) { + match v { + serde_json::Value::Array(a) => a.iter().for_each(|x| strings_in(x, out)), + serde_json::Value::Object(o) => { + for (k, x) in o { + match x { + serde_json::Value::String(s) if matches!(k.as_str(), "name" | "text" | "label") && s.chars().filter(char::is_ascii_alphabetic).count() >= 3 => { + out.insert(s.clone()); + } + _ => strings_in(x, out), + } + } + } + _ => {} + } +} + +/// Names egui gives its own parts. +const EGUI_OWN: [&str; 1] = ["Close window"]; + +/// Names a screen reader would announce that are still plain English in the pseudo-locale, +/// for the window after `setup` (a few frames to settle). +/// The app on a headless context with AccessKit on, in the pseudo-locale, after `setup`. +fn pseudo_app(setup: impl FnOnce(&mut crate::app::App, &egui::Context)) -> (crate::app::App, egui::Context) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let mut app = crate::app::App::with_context(&ctx, session, Some(PathBuf::from("unused.png"))); + // In the preferences (unsaved in screenshot mode), so a setup that changes them keeps it. + app.prefs.language = PSEUDO.into(); + app.apply_prefs(&ctx); + setup(&mut app, &ctx); + (app, ctx) +} + +fn screen() -> egui::RawInput { + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), ..Default::default() } +} + +/// Names in `nodes` that are ours and still plain English. +fn plain_names(what: &str, app: &crate::app::App, nodes: Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>) -> Vec { + // Document text is the document's (layer, symbol and scene names): not ours to translate. + let mut doc_text = BTreeSet::new(); + if let Ok(v) = serde_json::to_value(&app.s.doc) { + strings_in(&v, &mut doc_text); + } + let mut found = BTreeSet::new(); + for (_, n) in nodes { + for name in [n.label(), n.description()].into_iter().flatten() { + // egui names its own window close button; it offers no way to name it ourselves + // (docs/localisation.md › Not yet). + let translated = name.chars().any(pseudo::is_accented) || EGUI_OWN.contains(&name); + let ours = scan::is_prose(name) && !doc_text.contains(name) && !doc_text.iter().any(|d| name.contains(d.as_str())); + if ours && !translated { + found.insert(format!("[{what}] {:?} {name:?}", n.role())); + } + } + } + found.into_iter().collect() +} + +fn untranslated_names(what: &str, setup: impl FnOnce(&mut crate::app::App, &egui::Context)) -> Vec { + let (mut app, ctx) = pseudo_app(setup); + let mut update = None; + for _ in 0..3 { + let mut out = ctx.run_ui(screen(), |ui| app.frame(ui)); + out.textures_delta.clear(); + update = out.platform_output.accesskit_update; + } + plain_names(what, &app, update.map(|u| u.nodes).unwrap_or_default()) +} + +/// Clicks every control the window shows in `setup`'s state, one after another (through +/// AccessKit, as a screen reader would; number fields are stepped too), and returns the names +/// and status lines that came out in plain English. Prompts are dismissed after each click, +/// so nothing is written to disk. +fn click_everything(what: &str, setup: impl FnOnce(&mut crate::app::App, &egui::Context)) -> Vec { + use egui::accesskit::{Action, ActionRequest, Role, TreeId}; + let (mut app, ctx) = pseudo_app(setup); + let frame = |app: &mut crate::app::App, events: Vec| { + let mut input = screen(); + input.events = events; + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let mut nodes = Vec::new(); + for _ in 0..3 { + nodes = frame(&mut app, Vec::new()); + } + let mut done: BTreeSet = BTreeSet::new(); + let mut found = Vec::new(); + for _ in 0..90 { + // The next control not clicked yet (by role and name: ids change as panels redraw). + let next = nodes.iter().find_map(|(id, n)| { + let key = format!("{:?} {}", n.role(), n.label().unwrap_or_default()); + let steps = n.supports_action(Action::Increment); + let clickable = (steps || n.supports_action(Action::Click)) && !matches!(n.role(), Role::Window | Role::TitleBar | Role::ScrollBar); + (clickable && !done.contains(&key)).then_some((*id, key, steps)) + }); + let Some((id, key, steps)) = next else { break }; + done.insert(key); + let request = |action| egui::Event::AccessKitActionRequest(ActionRequest { action, target_tree: TreeId::ROOT, target_node: id, data: None }); + // A number field steps up (as an arrow key does); anything else is clicked. + let events = vec![request(if steps { Action::Increment } else { Action::Click })]; + app.status = None; + frame(&mut app, events); + app.prompt = None; + // Picking a language in Preferences is one of the controls: back to the pseudo-locale. + if app.prefs.language != PSEUDO { + app.prefs.language = PSEUDO.into(); + app.apply_prefs(&ctx); + } + nodes = frame(&mut app, Vec::new()); + if let Some(s) = &app.status + && !s.text.chars().any(pseudo::is_accented) + { + found.push(format!("[{what}] status {:?}", s.text)); + } + // Installed font families, and languages, are listed by their own names. + let mut fonts: BTreeSet = app.system_fonts.as_ref().map(|f| f.families.iter().cloned().collect()).unwrap_or_default(); + fonts.extend(offered().into_iter().map(|(_, name)| name.to_string())); + found.extend(plain_names(what, &app, nodes.clone()).into_iter().filter(|f| !fonts.iter().any(|name| f.ends_with(&format!("{name:?}"))))); + } + found.sort(); + found.dedup(); + found +} + +#[test] +fn every_control_can_be_used_in_the_pseudo_locale() { + // Pressing every button, opening every list and stepping every number in the main states + // of the window: nothing may panic, and what each one shows next (a popup, a status line, + // a dialog) is translated too. + let mut found = click_everything("default", |_, _| {}); + found.extend(click_everything("shape selected", |a, _| { + a.run("layer.select", serde_json::json!({"index": 0})); + a.run("edit.select_all", serde_json::json!({})); + })); + found.extend(click_everything("text selected", |a, _| { + a.run("text.create", serde_json::json!({"x": 40.0, "y": 40.0, "text": "Title"})); + a.run("edit.select_all", serde_json::json!({})); + })); + found.extend(click_everything("symbol with filters", |a, _| { + a.run("layer.select", serde_json::json!({"index": 0})); + a.run("edit.select_all", serde_json::json!({})); + let symbol = a.run("modify.convert_to_symbol", serde_json::json!({"name": "Clip"})).and_then(|v| v["symbol"].as_u64()); + a.run("symbol.set_kind", serde_json::json!({"symbol": symbol, "kind": "movie_clip"})); + a.run("element.set_filters", serde_json::json!({"filters": [{"type": "drop_shadow"}, {"type": "gradient_glow"}]})); + })); + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple"] { + found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); + } + for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { + found.extend(click_everything(&format!("{tool:?}"), |a, _| a.tool = tool)); + } + assert!(found.is_empty(), "{} things in plain English after using the controls:\n{}", found.len(), found.join("\n")); +} + +#[test] +fn status_lines_for_every_result_are_translated() { + // What the status bar says for results a test can't produce for real (saves, exports, + // imports, recovered work, plug-ins), from results shaped as the commands return them. + use serde_json::json; + let (mut app, _ctx) = pseudo_app(|_, _| {}); + let full = json!({ + "saved": "walk.anicraft", "written": "walk.png", "seconds": 1.5, "frames": 3, "columns": 2, "rows": 2, "map": "walk.json", + "kb": 12, "layers": 2, "masks": 1, "elements": 3, "report": "Imported walk.fla.", "copied": 2, "cut": 2, "pasted": 2, + "removed": 2, "cleared": 2, "original_newer": true, "sounds": 1, "name": "beat", "sound": 1, "log": ["Did it."], + "installed": [{"name": "Tint", "version": "1.0"}], "failed": ["bad.wasm: not a plug-in"], "replaced": "Tint 0.9", + "plugin": {"name": "Tint", "version": "1.0"}, "undone": "Move", "redone": "Move", + }); + let bare = json!({}); + let ids = [ + "file.new", "file.open", "file.recover", "file.discard_recovery", "file.save", "file.save_as", "file.import", "file.import_to_library", + "file.export_audio", "file.export_sprite_sheet", "file.export_html", "file.export_lottie", "file.export_png", "file.export_gif", + "sound.delete", "edit.undo", "edit.redo", "edit.delete", "layer.delete", "draw.erase_all", "scene.delete", "scene.new", + "timeline.clear_keyframe", "timeline.copy_frames", "timeline.cut_frames", "timeline.paste_frames", "timeline.remove_frame", + "plugin.run", "plugin.install", "plugin.remove", "plugin.reload", + ]; + let mut plain = Vec::new(); + for id in ids { + for (shape, v) in [("full", &full), ("bare", &bare)] { + app.status = None; + app.announce(id, v, 2); + if let Some(s) = &app.status + && !s.text.chars().any(pseudo::is_accented) + { + plain.push(format!("{id} ({shape}): {:?}", s.text)); + } + } + } + assert!(plain.is_empty(), "status lines in plain English:\n{}", plain.join("\n")); +} + +#[test] +fn tool_status_lines_are_translated() { + // The Eraser's and Eyedropper's results on the sample (on the sun and the hills, and on + // empty stage), as the status bar shows them. + let (mut app, _ctx) = pseudo_app(|_, _| {}); + let mut plain = Vec::new(); + let mut check = |app: &mut crate::app::App, what: &str| { + if let Some(s) = app.status.take() + && !s.text.chars().any(pseudo::is_accented) + { + plain.push(format!("{what}: {:?}", s.text)); + } + }; + let sun = anicraft_engine::geom::Vec2::new(1000.0, 160.0); + let hill = anicraft_engine::geom::Vec2::new(300.0, 600.0); + let empty = anicraft_engine::geom::Vec2::new(-500.0, -500.0); + for (p, shift) in [(sun, false), (sun, true), (hill, false), (empty, false)] { + crate::erasertool::eyedropper(&mut app, p, shift, 1.0); + check(&mut app, "eyedropper"); + } + for p in [hill, empty] { + crate::erasertool::faucet(&mut app, p, 1.0); + check(&mut app, "faucet"); + } + crate::erasertool::erase_everything(&mut app); + check(&mut app, "erase everything"); + crate::erasertool::erase_everything(&mut app); + check(&mut app, "erase everything again"); + assert!(plain.is_empty(), "tool status lines in plain English:\n{}", plain.join("\n")); +} + +#[test] +fn every_menu_item_is_translated() { + // The menus are built from the command registry when they open; each is drawn here as it + // opens, in the pseudo-locale, and every item it shows must have been translated. + let mut found = Vec::new(); + for top in crate::menus::TOP_MENUS { + let (mut app, ctx) = pseudo_app(|_, _| {}); + let cmds = anicraft_engine::commands(); + let mut update = None; + for _ in 0..2 { + let mut out = ctx.run_ui(screen(), |ui| crate::menus::menu_contents(&mut app, ui, top, &cmds)); + out.textures_delta.clear(); + update = out.platform_output.accesskit_update; + } + let nodes = update.map(|u| u.nodes).unwrap_or_default(); + assert!(nodes.len() > 2, "the {top} menu drew nothing"); + found.extend(plain_names(top, &app, nodes)); + } + assert!(found.is_empty(), "menu items not translated:\n{}", found.join("\n")); +} + +#[test] +fn status_messages_after_commands_are_translated() { + // What the status bar says after a command (and the screen reader announces) is ours. + let (mut app, _ctx) = pseudo_app(|_, _| {}); + let steps: &[(&str, serde_json::Value)] = &[ + ("layer.select", serde_json::json!({"index": 0})), + ("edit.select_all", serde_json::json!({})), + ("edit.delete", serde_json::json!({})), + ("edit.undo", serde_json::json!({})), + ("edit.redo", serde_json::json!({})), + ("timeline.clear_keyframe", serde_json::json!({})), + ("timeline.remove_frame", serde_json::json!({})), + ("draw.erase_all", serde_json::json!({})), + ("layer.new", serde_json::json!({})), + ("layer.delete", serde_json::json!({"confirm": true})), + ("scene.new", serde_json::json!({})), + ("scene.prev", serde_json::json!({})), + ("scene.next", serde_json::json!({})), + ("scene.delete", serde_json::json!({"confirm": true})), + ("file.new_sample", serde_json::json!({"which": "interactive"})), + ("file.new", serde_json::json!({"confirm": true})), + ]; + let mut plain = Vec::new(); + for (id, params) in steps { + app.status = None; + app.perform(id, params.clone()); + match &app.status { + Some(s) if !s.text.chars().any(pseudo::is_accented) => plain.push(format!("{id}: {:?}", s.text)), + _ => {} + } + } + assert!(plain.is_empty(), "status lines in plain English:\n{}", plain.join("\n")); +} + +#[test] +fn screen_reader_names_are_translated_too() { + // ADR 0022 names every control; ADR 0040 translates them. In the pseudo-locale every name + // we wrote is accented, so a plain-English one skipped translation (this catches strings + // the source guideline can't see: ones passed through variables or built at run time). + use crate::app::Tool; + let mut found = untranslated_names("default", |_, _| {}); + for tool in [Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::Eyedropper, Tool::Pen, Tool::Camera, Tool::Bone] { + found.extend(untranslated_names(&format!("{tool:?} tool"), |a, _| a.tool = tool)); + } + // Selections and states that change what Properties, the timeline and the dialogs show. + found.extend(untranslated_names("shape selected", |a, _| { + a.run("layer.select", serde_json::json!({"index": 0})); + a.run("edit.select_all", serde_json::json!({})); + })); + found.extend(untranslated_names("text selected", |a, _| { + a.run("text.create", serde_json::json!({"x": 40.0, "y": 40.0, "text": "Title"})); + a.run("edit.select_all", serde_json::json!({})); + })); + found.extend(untranslated_names("button instance", |a, _| { + a.perform("file.new_sample", serde_json::json!({"which": "interactive"})); + if let Some(button) = a.s.doc.library.iter().find(|s| s.kind == anicraft_engine::doc::SymbolKind::Button).map(|s| s.id.0) { + a.run("library.place", serde_json::json!({"symbol": button, "x": 100.0, "y": 100.0})); + } + crate::actions_panel::open(a, crate::actions_panel::Tab::Instance); + })); + found.extend(untranslated_names("close guard", |a, _| { + a.run("layer.new", serde_json::json!({})); + a.close_dialog = true; + })); + found.extend(untranslated_names("library item", |a, _| { + a.library_sel = a.s.doc.library.first().map(|s| crate::app::LibraryItem::Symbol(s.id)); + })); + for panel in ["select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] { + found.extend(untranslated_names(panel, |a, _| a.open_panel(Some(panel)))); + } + assert!(found.is_empty(), "{} screen-reader names not translated in the pseudo-locale:\n{}", found.len(), found.join("\n")); +} + +#[test] +fn the_selection_title_reads_like_the_engines_label_in_english() { + // panels.rs keeps a translated copy of `anicraft_engine::element_label`; in English the two + // must say the same, so a change to one shows here. + let mut s = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + s.execute("edit.select_all", &serde_json::json!({})).ok(); + s.execute("modify.convert_to_symbol", &serde_json::json!({"name": "Clip"})).ok(); + s.execute("text.create", &serde_json::json!({"x": 10.0, "y": 10.0, "text": "A longer line of text than fits\nand a second"})).ok(); + set_language(ENGLISH); + let doc = &s.doc; + let mut seen = 0; + for scene in &doc.scenes { + for layer in &scene.timeline.layers { + for k in &layer.keyframes { + for e in &k.elements { + assert_eq!(crate::panels::element_title(doc, e), anicraft_engine::element_label(doc, e)); + seen += 1; + } + } + } + } + assert!(seen > 3, "the sample has elements ({seen})"); +} diff --git a/src/icons.rs b/src/icons.rs index bf41d346..ec155d3c 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -65,11 +65,17 @@ pub enum Icon { Sound, SoundOff, Camera, + Magnet, + Bone, + EditMultiple, } impl Icon { #[cfg(test)] - pub const ALL: [Icon; 51] = [ + pub const ALL: [Icon; 54] = [ + Icon::EditMultiple, + Icon::Bone, + Icon::Magnet, Icon::SoundOff, Icon::Camera, Icon::Width, @@ -192,6 +198,13 @@ impl Icon { Icon::Folder => ("folder", false), // A film camera with its two reels (AniCraft original, on Lucide's grid). Icon::Camera => ("anicraft-camera", false), + // A horseshoe magnet, poles up (AniCraft original, on Lucide's grid): Snap to Objects. + Icon::Magnet => ("anicraft-magnet", false), + // A bone: a wedge from its joint to its end (AniCraft original, on Lucide's grid). + Icon::Bone => ("anicraft-bone", false), + // Frames stacked one behind the other, all edited at once (AniCraft original, on + // Lucide's grid): Edit Multiple Frames. + Icon::EditMultiple => ("anicraft-edit-multiple", false), Icon::FolderOpen => ("folder-open", false), } } @@ -222,6 +235,7 @@ static FILES: &[(&str, &str)] = &[ ("type", include_str!("../assets/icons/type.svg")), ("volume-2", include_str!("../assets/icons/volume-2.svg")), ("anicraft-sound-off", include_str!("../assets/icons/anicraft-sound-off.svg")), + ("anicraft-magnet", include_str!("../assets/icons/anicraft-magnet.svg")), ("play", include_str!("../assets/icons/play.svg")), ("pause", include_str!("../assets/icons/pause.svg")), ("rotate-cw", include_str!("../assets/icons/rotate-cw.svg")), @@ -245,6 +259,8 @@ static FILES: &[(&str, &str)] = &[ ("anicraft-eyedropper", include_str!("../assets/icons/anicraft-eyedropper.svg")), ("anicraft-masked", include_str!("../assets/icons/anicraft-masked.svg")), ("anicraft-camera", include_str!("../assets/icons/anicraft-camera.svg")), + ("anicraft-bone", include_str!("../assets/icons/anicraft-bone.svg")), + ("anicraft-edit-multiple", include_str!("../assets/icons/anicraft-edit-multiple.svg")), ("folder", include_str!("../assets/icons/folder.svg")), ("folder-open", include_str!("../assets/icons/folder-open.svg")), ]; diff --git a/src/keymap.rs b/src/keymap.rs index 5d47a49a..56184e70 100644 --- a/src/keymap.rs +++ b/src/keymap.rs @@ -12,19 +12,20 @@ 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. +/// Keys handled before the shortcut map, which the editor will not assign, and what for +/// (English: translated where it is shown). 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"), + ("Ctrl+K", tr_noop!("the command palette")), + ("Ctrl+Shift+P", tr_noop!("the command palette")), + ("F1", tr_noop!("the shortcut editor")), + ("Ctrl+Alt+Shift+K", tr_noop!("the shortcut editor")), + ("Ctrl+U", tr_noop!("Preferences")), + ("Ctrl+,", tr_noop!("Preferences")), + ("Ctrl+Q", tr_noop!("quitting")), + ("Enter", tr_noop!("play / stop")), + ("Escape", tr_noop!("cancelling")), + ("Space", tr_noop!("panning with any tool")), + ("Tab", tr_noop!("moving between fields")), ]; /// Most keys one action may have. @@ -34,8 +35,9 @@ pub const MAX_KEYS: usize = 4; #[derive(Clone, Debug)] pub struct Action { pub id: &'static str, + /// English, as the registry has it: translated where it is shown (`i18n::t_cmd`, `i18n::t`). pub label: &'static str, - /// Where it lives (a top menu, "Tools" or "View"). + /// Where it lives (a top menu, "Tools" or "View"); English, translated where it is shown. pub group: &'static str, pub defaults: Vec<&'static str>, } @@ -60,6 +62,7 @@ pub fn tool_id(t: Tool) -> &'static str { Tool::InkBottle => "tool.ink_bottle", Tool::Eyedropper => "tool.eyedropper", Tool::Camera => "tool.camera", + Tool::Bone => "tool.bone", Tool::Hand => "tool.hand", Tool::Zoom => "tool.zoom", } @@ -71,16 +74,16 @@ pub fn tool_for(id: &str) -> Option { 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.next_panel" => "Next Panel", - "view.prev_panel" => "Previous Panel", - "view.actions" => "Actions Panel", - "view.brush_smaller" => "Brush Size Down", - "view.brush_larger" => "Brush Size Up", - _ => "View action", + "view.fit" => tr_noop!("Fit Stage in Window"), + "view.onion" => tr_noop!("Onion Skin On / Off"), + "view.select_all_frames" => tr_noop!("Select All Frames"), + "view.align_to_stage" => tr_noop!("Align to Stage On / Off"), + "view.next_panel" => tr_noop!("Next Panel"), + "view.prev_panel" => tr_noop!("Previous Panel"), + "view.actions" => tr_noop!("Actions Panel"), + "view.brush_smaller" => tr_noop!("Brush Size Down"), + "view.brush_larger" => tr_noop!("Brush Size Up"), + _ => tr_noop!("View action"), } } @@ -93,11 +96,11 @@ pub fn actions() -> Vec { .map(|c| Action { id: c.id, label: c.label, - group: if c.menu.is_empty() { "Other" } else { c.menu.split('/').next().unwrap_or("Other") }, + group: if c.menu.is_empty() { tr_noop!("Other") } else { c.menu.split('/').next().unwrap_or(tr_noop!("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() })); + v.extend(Tool::ALL.into_iter().map(|t| Action { id: tool_id(t), label: t.label(), group: tr_noop!("Tools"), defaults: t.shortcut().into_iter().collect() })); let mut views: Vec<&str> = Vec::new(); for (_, id) in VIEW_SHORTCUTS { if !views.contains(id) { @@ -107,7 +110,7 @@ pub fn actions() -> Vec { v.extend(views.into_iter().map(|id| Action { id, label: view_label(id), - group: "View", + group: tr_noop!("View"), defaults: VIEW_SHORTCUTS.iter().filter(|(_, i)| *i == id).map(|(k, _)| *k).collect(), })); v @@ -239,7 +242,7 @@ pub enum Refusal { /// 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)"))?; + let c = normalize(chord).ok_or(Refusal::Reserved(tr_noop!("nothing (not a key)")))?; if let Some(why) = reserved(&c) { return Err(Refusal::Reserved(why)); } diff --git a/src/main.rs b/src/main.rs index a5f0930d..29a3838d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ //! //! ```text //! anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open ] -//! [--theme graphite|high-contrast] [--scale ] +//! [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] //! anicraft --version //! ``` //! `--screenshot` starts normally, draws ~120 frames, saves the window as PNG and exits. @@ -18,6 +18,9 @@ // window chrome, `--open` panels); that code stays compiled for it but unused (ADR 0036). #![cfg_attr(target_arch = "wasm32", allow(dead_code))] +// First, so its `tr!` macros are in scope in every module after it. +#[macro_use] +mod i18n; mod a11y; mod actions_panel; mod app; @@ -25,6 +28,7 @@ mod autosave; mod brushtool; mod envelope; mod erasertool; +mod bone_tool; mod camera_tool; mod dialogs; mod gpu_stage; @@ -34,6 +38,7 @@ mod menus; mod motion_editor; mod panels; mod motion_path; +mod onion; mod pathtools; mod platform; mod plugins_ui; @@ -78,10 +83,12 @@ fn open_session(file: Option<&Path>) -> (Session, Option) { /// `--theme` / `--scale`: the look for this run only (screenshots of high contrast or 200 %), /// over the saved preferences, without saving them. #[cfg(not(target_arch = "wasm32"))] -#[derive(Clone, Copy, Default)] +#[derive(Clone, Default)] struct Look { theme: Option, scale: Option, + /// `--lang`: a locale code, `auto` or `pseudo` (ADR 0040). + lang: Option, } #[cfg(not(target_arch = "wasm32"))] @@ -94,6 +101,8 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o // The embedded interface font joins the text library before anything lays text out: // opening an Animate document from the command line lays its text out right here. anicraft_engine::text::Fonts::register(theme::embedded_fonts()); + // `--lang` before the window exists, so its first status line is in that language too. + i18n::force(look.lang.as_deref()); let (session, report) = open_session(file); eframe::run_native( "AniCraft", @@ -104,7 +113,7 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o a.open_panel(open.as_deref()); // An imported document says what came across, as opening it from the menu does. if let Some(r) = report { - a.status_ok(format!("{r} Save to keep it as an AniCraft document.")); + a.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)); } Ok(Box::new(a)) }), @@ -152,19 +161,28 @@ fn main() -> eframe::Result { std::process::exit(2); } }, + "--lang" => match args.next() { + Some(code) if i18n::known(&code) => look.lang = Some(code), + other => { + let offered: Vec<&str> = i18n::offered().into_iter().map(|(c, _)| c).collect(); + eprintln!("--lang takes auto, pseudo or a language this build has ({}), not {}", offered.join(", "), other.as_deref().unwrap_or("nothing")); + std::process::exit(2); + } + }, // Printed by the release packaging checks and for bug reports. "--version" | "-V" => { println!("AniCraft {} ({})", env!("CARGO_PKG_VERSION"), app::RELEASE_STAGE); return Ok(()); } "--help" | "-h" => { - println!( - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|script|testmovie|exporthtml|sound|envelope]\n\ + println!( // i18n-exempt: the --help console text + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ --theme the interface palette for this run (not saved)\n\ --scale the interface scale for this run, 75 to 200 (not saved)\n\ + --lang the interface language for this run (not saved); pseudo tests the layout\n\ Headless use: anicraft-cli --help" ); return Ok(()); @@ -177,7 +195,7 @@ fn main() -> eframe::Result { // 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(), look) { + match run(first, file.as_deref(), shot.clone(), open.clone(), look.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, look) diff --git a/src/menus.rs b/src/menus.rs index 4f7a1de8..51574d6b 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -6,7 +6,8 @@ use crate::theme::{Type, text}; use anicraft_engine::{CommandSpec, commands}; // Commands sits where Animate has it: after Modify, before Control. -const TOP_MENUS: [&str; 9] = ["File", "Edit", "View", "Insert", "Modify", "Commands", "Control", "Window", "Help"]; +// English keys (the registry's menu paths start with them), translated where they are drawn. +pub(crate) const TOP_MENUS: [&str; 9] = [tr_noop!("File"), tr_noop!("Edit"), tr_noop!("View"), tr_noop!("Insert"), tr_noop!("Modify"), tr_noop!("Commands"), tr_noop!("Control"), tr_noop!("Window"), tr_noop!("Help")]; pub fn bar(app: &mut App, ui: &mut egui::Ui) { let cmds = commands(); @@ -17,22 +18,22 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) { // 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) { + if ui_item(ui, tr!("About AniCraft"), "", None) { app.show_about = true; } ui.separator(); - if ui_item(ui, "Settings…", "Ctrl+,", None) { + if ui_item(ui, tr!("Settings…"), "Ctrl+,", None) { app.open_prefs(); } ui.separator(); - if ui_item(ui, "Quit AniCraft", "Ctrl+Q", None) { + if ui_item(ui, tr!("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.menu_button(crate::i18n::t(top), |ui| { ui.set_min_width(230.0); menu_contents(app, ui, top, &cmds); }); @@ -61,17 +62,32 @@ fn enabled(app: &App, id: &str) -> bool { } } +/// Whether a registry command that switches a setting has it on (`None`: not a setting). +fn checked(app: &App, id: &str) -> Option { + match id { + "draw.snap_to_objects" => Some(app.s.style.snap_objects), + "draw.object_drawing" => Some(app.s.style.object_drawing), + _ => None, + } +} + 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(), + "edit.undo" => app.s.undo_label().map_or_else(|| crate::i18n::t_cmd(spec.id, spec.label).to_string(), |l| tr!("Undo {action}", action = crate::i18n::t_dyn(l))), + _ => crate::i18n::t_cmd(spec.id, spec.label).to_string(), + }; + // Settings show whether they are on, as check items do. + let label = match checked(app, spec.id) { + Some(true) => format!("✔ {label}"), + Some(false) => format!(" {label}"), + None => label, }; let button = egui::Button::new(label).shortcut_text(text(Type::Key, platform::shortcut_label(app.keymap.primary(spec.id).unwrap_or("")))); // What this build can't do stays in its usual place, dimmed, saying why (the web build). let missing = platform::unavailable(spec.id); let r = ui.add_enabled(enabled(app, spec.id) && missing.is_none(), button); let r = match missing { - Some(why) => r.on_disabled_hover_text(why), + Some(why) => r.on_disabled_hover_text(crate::i18n::t(why)), None => r, }; if r.clicked() { @@ -88,7 +104,8 @@ pub fn cmd_item(app: &mut App, ui: &mut egui::Ui, id: &str) { } } -/// A check item for state that is not a registry command's own (context menus). +/// A check item for state that is not a registry command's own (context menus). `label` is +/// already in the interface language (`tr!`). 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(); @@ -98,6 +115,7 @@ pub fn check_item(ui: &mut egui::Ui, label: &str, checked: bool, enabled: bool) clicked } +/// A view item (not a registry command); `label` is already translated. fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option) -> bool { let label_text = match checked { Some(true) => format!("✔ {label}"), @@ -111,13 +129,8 @@ fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option clicked } -fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) { - if top == "Commands" { - // Installed plug-ins first (they change at run time), then the registry's items. - crate::plugins_ui::menu(app, ui, cmds, item); - return; - } - // Direct items first, then one submenu per "Top/Sub" path, in registry order. +/// A top menu's registry items: its own, then one submenu per "Top/Sub" path, in order. +fn registry_items(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) { for spec in cmds.iter().filter(|c| c.menu == top) { item(app, ui, spec); } @@ -131,122 +144,141 @@ fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpe } for sub in subs { let path = format!("{top}/{sub}"); - ui.menu_button(sub, |ui| { + ui.menu_button(crate::i18n::t(sub), |ui| { ui.set_min_width(220.0); for spec in cmds.iter().filter(|c| c.menu == path) { item(app, ui, spec); } }); } +} + +pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) { + if top == "Commands" { + // Installed plug-ins first (they change at run time), then the registry's items. + crate::plugins_ui::menu(app, ui, cmds, item); + return; + } + // Direct items first, then one submenu per "Top/Sub" path, in registry order (in View, + // after its zoom and preview items, where Animate keeps Snapping). + if top != "View" { + registry_items(app, ui, top, cmds); + } match top { // Windows / Linux conventions; on macOS these live in the AniCraft (application) menu. // A web page is closed with its tab. "File" if platform::OS != Os::Mac && !platform::WEB => { ui.separator(); - if ui_item(ui, "Exit", "Ctrl+Q", None) { + if ui_item(ui, tr!("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) { + if ui_item(ui, tr!("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) { + if ui_item(ui, tr!("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) { + if ui_item(ui, tr!("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) { + if ui_item(ui, tr!("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; + if ui_item(ui, tr!("Onion Skin"), app.keymap.primary("view.onion").unwrap_or(""), Some(app.onion.ghosts)) { + crate::onion::toggle_ghosts(app); } - if ui_item(ui, "Preview Through Camera", "", Some(app.camera_preview)) { + if ui_item(ui, tr!("Edit Multiple Frames"), "", Some(app.onion.edit_multiple)) { + crate::onion::toggle_edit_multiple(app); + } + ui.menu_button(tr!("Onion Skin Options"), |ui| crate::onion::menu(app, ui)); + if ui_item(ui, tr!("Preview Through Camera"), "", Some(app.camera_preview)) { app.toggle_camera_preview(); } - ui.menu_button("Stage Rendering", |ui| { + ui.menu_button(tr!("Stage Rendering"), |ui| { for (mode, name, tip) in crate::prefs::RenderMode::ALL { - if ui_item(ui, name, "", Some(app.prefs.render_mode == mode)) { + if ui_item(ui, crate::i18n::t(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)); + ui.label(text(Type::Caption, crate::i18n::t(tip))); } if crate::gpu_stage::AVAILABLE { ui.separator(); for (choice, name, tip) in crate::prefs::StageRenderer::ALL { - if ui_item(ui, name, "", Some(app.prefs.stage_renderer == choice)) { + if ui_item(ui, crate::i18n::t(name), "", Some(app.prefs.stage_renderer == choice)) { let mut p = app.prefs.clone(); p.stage_renderer = choice; let ctx = ui.ctx().clone(); app.set_prefs(&ctx, p); } - ui.label(text(Type::Caption, tip)); + ui.label(text(Type::Caption, crate::i18n::t(tip))); } } }); + ui.separator(); + registry_items(app, ui, top, cmds); } "Control" => { ui.separator(); - if ui_item(ui, if app.playing { "Stop" } else { "Play" }, "Enter", None) { + if ui_item(ui, if app.playing { tr!("Stop") } else { tr!("Play") }, "Enter", None) { app.toggle_play(); } - if ui_item(ui, "Loop Playback", "", Some(app.looping)) { + if ui_item(ui, tr!("Loop Playback"), "", Some(app.looping)) { app.looping = !app.looping; } } "Window" => { use crate::app::BottomTab; - if ui_item(ui, "Timeline", "", Some(app.bottom == BottomTab::Timeline)) { + if ui_item(ui, tr!("Timeline"), "", Some(app.bottom == BottomTab::Timeline)) { app.bottom = BottomTab::Timeline; } - if ui_item(ui, "Motion Editor", "", Some(app.bottom == BottomTab::MotionEditor)) { + if ui_item(ui, tr!("Motion Editor"), "", Some(app.bottom == BottomTab::MotionEditor)) { app.bottom = BottomTab::MotionEditor; } - if ui_item(ui, "Actions", app.keymap.primary("view.actions").unwrap_or(""), Some(app.show_actions)) { + if ui_item(ui, tr!("Actions"), app.keymap.primary("view.actions").unwrap_or(""), Some(app.show_actions)) { app.show_actions = !app.show_actions; } ui.separator(); - if ui_item(ui, "Onion Skin", "", Some(app.onion)) { - app.onion = !app.onion; + if ui_item(ui, tr!("Onion Skin"), "", Some(app.onion.ghosts)) { + crate::onion::toggle_ghosts(app); } - ui.label(text(Type::Caption, "Panels are docked: Tools, Stage, Timeline, Properties, Library")); + ui.label(text(Type::Caption, tr!("Panels are docked: Tools, Stage, Timeline, Properties, Library"))); } "Help" => { - if ui_item(ui, "Command Palette…", "Ctrl+K", None) { + if ui_item(ui, tr!("Command Palette…"), "Ctrl+K", None) { app.palette = Some(crate::dialogs::Palette::default()); } - if ui_item(ui, "Keyboard Shortcuts", "F1", None) { + if ui_item(ui, tr!("Keyboard Shortcuts"), "F1", None) { app.show_shortcuts = true; } ui.separator(); // (The web build has no folders to show.) - if !platform::WEB && ui_item(ui, "Project Files & Docs…", "", None) { + if !platform::WEB && ui_item(ui, tr!("Project Files & Docs…"), "", None) { app.show_files = true; } - if ui_item(ui, "Licenses & Notices", "", None) { + if ui_item(ui, tr!("Licenses & Notices"), "", None) { app.show_licenses = true; } - if ui_item(ui, "About AniCraft", "", None) { + if ui_item(ui, tr!("About AniCraft"), "", None) { app.show_about = true; } - ui.label(text(Type::Caption, format!("{} commands are scriptable via anicraft-cli", cmds.len()))); + ui.label(text(Type::Caption, trn!("{n} command is scriptable with anicraft-cli", "{n} commands are scriptable with anicraft-cli", cmds.len()))); } _ => {} } diff --git a/src/motion_editor.rs b/src/motion_editor.rs index a4987735..2400e223 100644 --- a/src/motion_editor.rs +++ b/src/motion_editor.rs @@ -6,11 +6,15 @@ //! the span. Drag a key up or down to change its value, drag the two handles of the selected //! segment to shape its ease (a cubic Bézier), click to move the playhead, double-click to add //! a key. Every drag is one undo step (a session gesture); every change is a command. +//! +//! On X and Y, the keys of frames pinned to a motion path point (ADR 0049) are drawn in the +//! motion colour: they are the point's place and its timing, so dragging one moves the point on +//! the stage, and removing one unpins it. use crate::a11y::{self, Named}; use crate::app::App; use crate::theme::{SQUARE, T, TARGET, Type, color, font, text, with_type}; -use anicraft_engine::doc::{Easing, MotionTween, Property, Props, Track}; +use anicraft_engine::doc::{Easing, MotionTween, Pin, Property, Props, Track}; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, WidgetType, pos2, vec2}; use serde_json::json; @@ -114,9 +118,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // ---- property list --------------------------------------------------------------------- painter.rect_filled(Rect::from_min_max(list.left_top(), pos2(list.right(), list.top() + RULER_H)), 0.0, T.panel_alt); - painter.text(pos2(list.left() + 10.0, list.top() + RULER_H * 0.5), Align2::LEFT_CENTER, "Property", font(Type::Heading), color(Type::Heading)); - painter.text(pos2(list.right() - 44.0, list.top() + RULER_H * 0.5), Align2::RIGHT_CENTER, format!("Frame {}", app.s.frame + 1), font(Type::DataSmall), color(Type::DataSmall)); + painter.text(pos2(list.left() + 10.0, list.top() + RULER_H * 0.5), Align2::LEFT_CENTER, tr!("Property"), font(Type::Heading), color(Type::Heading)); + painter.text(pos2(list.right() - 44.0, list.top() + RULER_H * 0.5), Align2::RIGHT_CENTER, tr!("Frame {frame}", frame = app.s.frame + 1), font(Type::DataSmall), color(Type::DataSmall)); let now = m.props_at(&base, offset as f32); + // Frames pinned to path points: their X and Y keys are the points' places (ADR 0049). + let pins = m.pinned_anchors(&base); + let pin_at = |p: Property, f: u32| pins.iter().find(|q| q.frame == f).copied().filter(|_| matches!(p, Property::X | Property::Y)); let rows_top = list.top() + RULER_H; // Rows that don't fit scroll with the wheel over the list. let fit = (((list.bottom() - rows_top) / ROW_H).floor() as usize).max(1); @@ -134,6 +141,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let selected = app.me_prop == p; painter.rect_filled(row, 0.0, if selected { T.accent_dim } else if r % 2 == 0 { T.panel } else { T.panel_alt }); let track = m.track(p); + let label = crate::i18n::t(p.label()); // Groups (Position, Transform, Colour effect) are set apart by a rule. if p.group() != last_group { if !last_group.is_empty() { @@ -141,12 +149,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } last_group = p.group(); } - painter.text(pos2(row.left() + 12.0, row.center().y), Align2::LEFT_CENTER, p.label(), font(Type::Body), if track.is_some() { T.text } else { T.text_dim }); + painter.text(pos2(row.left() + 12.0, row.center().y), Align2::LEFT_CENTER, label, font(Type::Body), if track.is_some() { T.text } else { T.text_dim }); if track.is_some() { - painter.text(pos2(row.left() + 84.0, row.center().y), Align2::LEFT_CENTER, "keyed", font(Type::Caption), T.tween_motion); + painter.text(pos2(row.left() + 84.0, row.center().y), Align2::LEFT_CENTER, tr!("keyed"), font(Type::Caption), T.tween_motion); } let rr = ui.interact(row, ui.id().with(("me_row", p.key())), Sense::click()); - a11y::control(ui, &rr, WidgetType::SelectableLabel, &format!("{}{}", p.label(), if track.is_some() { " · keyed" } else { "" }), Some(selected)); + a11y::control(ui, &rr, WidgetType::SelectableLabel, &if track.is_some() { tr!("{property} · keyed", property = label) } else { label.to_string() }, Some(selected)); if rr.clicked() { app.me_prop = p; app.me_key = None; @@ -159,10 +167,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let suffix = if p.unit() == "px" { " px" } else { p.unit() }; // In a child placed on the row, so the field never grows the dock. let mut cell = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center))); - let r = with_type(&mut cell, Type::Data, |ui| ui.add_sized(vec2(field.width(), field.height()), egui::DragValue::new(&mut v).speed(speed).range(range).max_decimals(1).suffix(suffix)).named(p.label())); + let r = with_type(&mut cell, Type::Data, |ui| ui.add_sized(vec2(field.width(), field.height()), egui::DragValue::new(&mut v).speed(speed).range(range).max_decimals(1).suffix(suffix)).named(label)); if r.changed() { app.me_prop = p; - app.s.begin_gesture("Property keyframe"); + app.s.begin_gesture(tr_noop!("Property keyframe")); app.run("motion.set_key", json!({"property": p.key(), "frame": app.s.frame, "value": v})); } // Key toggle: a filled diamond where this property has a key at the playhead. @@ -173,8 +181,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_filled(toggle, T.rc(), T.hover); } diamond(&painter, toggle.center(), 5.0, if keyed { T.text } else { Color32::TRANSPARENT }, Stroke::new(1.5, if keyed { T.text } else { T.text_faint })); - let tip = if keyed { format!("Remove the {} keyframe at frame {}", p.label(), app.s.frame + 1) } else { format!("Add a {} keyframe at frame {}", p.label(), app.s.frame + 1) }; - a11y::control(ui, &tr, WidgetType::Checkbox, &format!("{} keyframe at frame {}", p.label(), app.s.frame + 1), Some(keyed)); + let tip = match (keyed, pin_at(p, offset)) { + (true, Some(q)) if m.path.is_some() && interior(&pins, q) => tr!("Unpin point {anchor} of the motion path from frame {frame}: its X and Y keyframes go", anchor = q.anchor, frame = app.s.frame + 1), + (true, _) => tr!("Remove the {property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1), + (false, _) => tr!("Add a {property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1), + }; + a11y::control(ui, &tr, WidgetType::Checkbox, &tr!("{property} keyframe at frame {frame}", property = label, frame = app.s.frame + 1), Some(keyed)); if tr.on_hover_text(tip).clicked() { app.me_prop = p; if keyed { @@ -190,6 +202,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // ---- graph ----------------------------------------------------------------------------- let p = app.me_prop; let track = m.track(p); + let label = crate::i18n::t(p.label()); let (lo, hi) = match app.me_drag { Some(MeDrag::Key { lo, hi, .. } | MeDrag::Handle { lo, hi, .. }) => (lo, hi), _ => value_range(track, base.get(p), frames, p), @@ -246,9 +259,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { x += 2.0; } gp.add(egui::Shape::line(pts, Stroke::new(2.0, if track.is_some() { T.tween_motion } else { T.text_faint }))); - gp.text(pos2(graph.right() - 8.0, graph.top() + 6.0), Align2::RIGHT_TOP, format!("{} · {}", p.label(), fmt(p, now.get(p))), font(Type::Data), color(Type::Data)); + gp.text(pos2(graph.right() - 8.0, graph.top() + 6.0), Align2::RIGHT_TOP, format!("{label} · {}", fmt(p, now.get(p))), font(Type::Data), color(Type::Data)); if track.is_none() { - gp.text(graph.center(), Align2::CENTER_CENTER, format!("{} has no keyframes: it stays {}. Click ◇ or drag its value to key it here.", p.label(), fmt(p, base.get(p))), font(Type::Caption), color(Type::Caption)); + gp.text(graph.center(), Align2::CENTER_CENTER, tr!("{property} has no keyframes: it stays {value}. Click ◇ or drag its value to key it here.", property = label, value = fmt(p, base.get(p))), font(Type::Caption), color(Type::Caption)); } // Keys and the selected segment's handles. @@ -275,13 +288,21 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { for &(f, v, _) in &keys { let c = pos2(x_of(f as f32), y_of(v)); let picked = sel_key == Some(f); - diamond(&gp, c, if picked { 6.5 } else { 5.5 }, if picked { T.accent } else { T.text }, Stroke::new(1.0, T.ink)); + if pin_at(p, f).is_some() { + // A path point's place: the motion colour, ringed like the stage's pinned points. + diamond(&gp, c, if picked { 7.5 } else { 6.5 }, if picked { T.accent } else { T.tween_motion }, Stroke::new(1.5, T.ink)); + } else { + diamond(&gp, c, if picked { 6.5 } else { 5.5 }, if picked { T.accent } else { T.text }, Stroke::new(1.0, T.ink)); + } + } + if matches!(p, Property::X | Property::Y) && pins.len() > 2 { + gp.text(pos2(graph.right() - 8.0, graph.bottom() - 6.0), Align2::RIGHT_BOTTOM, tr!("Blue keys are pinned motion path points: drag one to move its point"), font(Type::Caption), T.tween_motion); } // ---- graph interaction ------------------------------------------------------------------- // Pointer work; the keyboard route to the same values is the property list and its fields. let gr = ui.interact(graph_full, ui.id().with("me_graph"), a11y::pointer_only()); - a11y::surface(ui, &gr, &format!("{} curve", app.me_prop.label())); + a11y::surface(ui, &gr, &tr!("{property} curve", property = crate::i18n::t(app.me_prop.label()))); let hover = gr.hover_pos(); let near_key = |pt: Pos2| keys.iter().find(|k| pos2(x_of(k.0 as f32), y_of(k.1)).distance(pt) <= GRAB).map(|k| k.0); let near_handle = |pt: Pos2| handles.and_then(|h| [(1u8, h[1]), (2u8, h[2])].into_iter().find(|(_, q)| q.distance(pt) <= GRAB).map(|(w, _)| w)); @@ -301,12 +322,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.playing = false; app.me_drag = Some(match (near_handle(pt), sel_key, near_key(pt)) { (Some(which), Some(frame), _) => { - app.s.begin_gesture("Property ease"); + app.s.begin_gesture(tr_noop!("Property ease")); MeDrag::Handle { frame, which, lo, hi } } (_, _, Some(frame)) => { app.me_key = Some(frame); - app.s.begin_gesture("Property keyframe"); + app.s.begin_gesture(tr_noop!("Property keyframe")); app.run("timeline.goto", json!({"frame": start + frame})); MeDrag::Key { frame, lo, hi } } @@ -378,11 +399,19 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.me_key = Some(f - start); } } - gr.on_hover_text_at_pointer("Drag a key up or down to change it, or a handle to shape the ease. Double-click to add a key."); + match hover.and_then(near_key).and_then(|f| pin_at(p, f)) { + Some(q) => gr.on_hover_text_at_pointer(tr!("Frame {frame} · point {anchor} of the motion path: drag to move the point", frame = start + q.frame + 1, anchor = q.anchor)), + None => gr.on_hover_text_at_pointer(tr!("Drag a key up or down to change it, or a handle to shape the ease. Double-click to add a key.")), + }; footer(app, ui, body, track, sel_key, start); } +/// Whether `q` is a pin between the ends (which can be let go). +fn interior(pins: &[Pin], q: Pin) -> bool { + pins.first() != Some(&q) && pins.last() != Some(&q) +} + /// The value distance a segment's handles are measured against: the segment's own rise, or a /// quarter of the view for a flat segment (whose ease then shows no change until its ends /// differ). @@ -404,32 +433,32 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s let ui = &mut child; let p = app.me_prop; let seg = sel_key.zip(track).and_then(|(f, t)| t.key_at(f).filter(|i| *i + 1 < t.keys.len()).and_then(|i| t.keys.get(i)).map(|k| (f, k.ease))); - ui.label(text(Type::Label, format!("{} ease", p.label()))); + ui.label(text(Type::Label, tr!("{property} ease", property = crate::i18n::t(p.label())))); match seg { Some((f, ease)) => { - egui::ComboBox::from_id_salt("me_ease").width(160.0).selected_text(ease.label()).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("me_ease").width(160.0).selected_text(crate::timeline::easing_label(&ease)).show_ui(ui, |ui| { for (name, e) in Easing::PRESETS { - if ui.selectable_label(ease == e, name).clicked() { + if ui.selectable_label(ease == e, crate::i18n::t(name)).clicked() { app.run("motion.set_ease", json!({"property": p.key(), "frame": start + f, "easing": crate::timeline::easing_param(e)})); } } }) .response - .set_name("Ease"); - if ui.button("Same for all").on_hover_text("Give every property's segment at this frame this ease").clicked() { + .set_name(tr!("Ease")); + if ui.button(tr!("Same for all")).on_hover_text(tr!("Give every property's segment at this frame this ease")).clicked() { app.run("motion.set_ease", json!({"frame": start + f, "easing": crate::timeline::easing_param(ease)})); } } None => { - ui.label(text(Type::Caption, "Pick a key that has another key after it")); + ui.label(text(Type::Caption, tr!("Pick a key that has another key after it"))); } } ui.separator(); - if ui.button("Remove Tween").on_hover_text("The object stays as it is on the span's first frame (Ctrl+Z to undo)").clicked() { + if ui.button(tr!("Remove Tween")).on_hover_text(tr!("The object stays as it is on the span's first frame ({undo} to undo)", undo = app.undo_key())).clicked() { app.run("timeline.remove_tween", json!({})); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(text(Type::Caption, "Moving the object on the stage inside the span adds keys here")); + ui.label(text(Type::Caption, tr!("Moving the object on the stage inside the span adds keys here"))); }); } @@ -437,17 +466,17 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s fn empty_state(app: &mut App, ui: &mut egui::Ui, body: Rect) { let k = app.s.active_layer().and_then(|l| l.keyframe_at(app.s.frame).map(|k| (!k.elements.is_empty(), k.motion.is_some()))); let msg = match k { - Some((true, _)) => "This span has no motion tween. Create one to animate its object property by property.", - Some((false, _)) => "This span is empty. Draw or place an object, then create a motion tween.", - None => "The playhead is on an empty frame of this layer.", + Some((true, _)) => tr!("This span has no motion tween. Create one to animate its object property by property."), + Some((false, _)) => tr!("This span is empty. Draw or place an object, then create a motion tween."), + None => tr!("The playhead is on an empty frame of this layer."), }; let r = Rect::from_center_size(body.center(), vec2(body.width().min(520.0), 90.0)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r).layout(egui::Layout::top_down(egui::Align::Center))); - child.label(text(Type::Heading, "Motion Editor")); + child.label(text(Type::Heading, tr!("Motion Editor"))); child.add_space(4.0); child.label(text(Type::Caption, msg)); child.add_space(6.0); - if k.is_some_and(|(has, _)| has) && child.button("Create Motion Tween").clicked() { + if k.is_some_and(|(has, _)| has) && child.button(tr!("Create Motion Tween")).clicked() { app.run("timeline.create_motion_tween", json!({})); } } diff --git a/src/motion_path.rs b/src/motion_path.rs index 9f917368..94d272d8 100644 --- a/src/motion_path.rs +++ b/src/motion_path.rs @@ -12,14 +12,19 @@ //! * **Ctrl-drag** (⌘ on macOS) the path or its object, with Selection or Subselection, to move //! the whole path; the timing stays. //! +//! Anchors pinned to frames (ADR 0049) are diamonds, the keyframe mark, with their frame number +//! beside them; the others are squares that only shape the path. Selection takes the ends and the +//! pinned anchors; the right-click menu pins a Subselection anchor to the playhead's frame or +//! unpins it. +//! //! A tween without a path of its own shows the straight path its X/Y curves trace; the first //! edit makes it a path. Every change is a `motion.*` command, and a drag is one undo step (a //! session gesture). Only the anchor selection and the drag in progress live here. use crate::app::{App, Drag, Tool}; use crate::pathtools::Xf; -use crate::theme::T; -use anicraft_engine::doc::{ElementId, Props}; +use crate::theme::{T, Type, font}; +use anicraft_engine::doc::{ElementId, Pin, Props}; use anicraft_engine::geom::edit::{ANCHOR, C1, C2}; use anicraft_engine::geom::{Affine, Path, PathCmd, Vec2}; use egui::{Key, Modifiers, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; @@ -52,10 +57,37 @@ pub struct Shown { pub keys: Vec, /// The playhead's frame in the span. pub offset: u32, + /// The span's first frame. + pub start: u32, + /// The anchors tied to frames (from the span's start), ends included, in order (ADR 0049). + pub pins: Vec, /// The object travelling it. pub target: ElementId, } +impl Shown { + /// The pin on anchor `a`, if it is tied to a frame. + pub fn pin(&self, a: usize) -> Option { + self.pins.iter().find(|p| p.anchor as usize == a).copied() + } + + /// Whether anchor `a` is an end (always pinned). + fn is_end(&self, a: usize) -> bool { + is_end(a, self.path.cmds.len()) + } + + /// Why anchor `a` can't be pinned to the playhead's frame, or `None` when it can. + fn unpinnable(&self, a: usize) -> Option { + let (Some(first), Some(last)) = (self.pins.first(), self.pins.last()) else { return Some(tr!("The object doesn't move yet").into()) }; + let f = self.offset; + if !(first.frame < f && f < last.frame) { + return Some(tr!("Move the playhead between frames {first} and {last}, where the object moves along the path", first = self.start + first.frame + 1, last = self.start + last.frame + 1)); + } + let a = a as u32; + self.pins.iter().find(|p| p.frame != f && p.anchor != a && (p.frame < f) != (p.anchor < a)).map(|p| tr!("Point {anchor} is pinned to frame {frame}: pins keep the path's order", anchor = p.anchor, frame = self.start + p.frame + 1)) + } +} + /// The motion path of the active layer's motion tween at the playhead, when its object or a /// frame of its span is selected and it moves at all. pub fn shown(app: &App) -> Option { @@ -68,7 +100,7 @@ pub fn shown(app: &App) -> Option { let (a, b) = sel.frames(); sel.layers(&tl.layers).contains(&layer.id) && a < k.end() && b >= k.start }); - if !app.s.selection.contains(&target.id) && !span_selected { + if !app.s.selection.contains(layer.id, target.id) && !span_selected { return None; } let base = Props::of(target); @@ -77,18 +109,19 @@ pub fn shown(app: &App) -> Option { let mut keys: Vec = [anicraft_engine::doc::Property::X, anicraft_engine::doc::Property::Y].into_iter().filter_map(|p| m.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).filter(|f| *f < k.duration).collect(); keys.sort_unstable(); keys.dedup(); - Some(Shown { path, dots, keys, offset: app.s.frame - k.start, target: target.id }) + let pins = m.pinned_anchors(&base); + Some(Shown { path, dots, keys, offset: app.s.frame - k.start, start: k.start, pins, target: target.id }) } -/// The anchors the tool can take: both ends with Selection, every anchor with Subselection -/// (and shown to the Pen, which adds between them). -fn grabbable_anchors(path: &Path, tool: Tool) -> Vec<(usize, Vec2)> { +/// The anchors the tool can take: the ends and the pinned anchors with Selection (the motion's +/// keyframes), every anchor with Subselection (and shown to the Pen, which adds between them). +fn grabbable_anchors(path: &Path, pins: &[Pin], tool: Tool) -> Vec<(usize, Vec2)> { let all = path.anchors(); match tool { Tool::Subselect | Tool::Pen => all, _ => { let n = all.len(); - all.into_iter().enumerate().filter(|(i, _)| *i == 0 || *i + 1 == n).map(|(_, a)| a).collect() + all.into_iter().enumerate().filter(|(i, _)| *i == 0 || *i + 1 == n || pins.iter().any(|p| p.anchor as usize == *i)).map(|(_, a)| a).collect() } } } @@ -125,7 +158,7 @@ pub fn hit(app: &App, shown: &Shown, p: Pos2, xf: Xf, segments: bool) -> Option< } } } - if let Some((cmd, _)) = grabbable_anchors(&shown.path, app.tool).into_iter().find(|(_, q)| near(*q)) { + if let Some((cmd, _)) = grabbable_anchors(&shown.path, &shown.pins, app.tool).into_iter().find(|(_, q)| near(*q)) { return Some(Grab::Anchor(cmd)); } if segments && app.tool == Tool::Select { @@ -143,7 +176,8 @@ pub fn drag_start(app: &mut App, shown: Shown, grab: Grab, at: Vec2) -> Drag { app.motion_anchors = vec![a]; } app.motion_drag = Some(shown.path); - app.s.begin_gesture("Edit Motion Path"); + // Undo labels stay English in the history and are translated where they show. + app.s.begin_gesture(tr_noop!("Edit Motion Path")); Drag::MotionPath { grab, start: pos2(at.x, at.y) } } @@ -205,7 +239,7 @@ pub fn move_hit(app: &App, p: Pos2, xf: Xf) -> bool { /// Starts moving the whole path from stage point `at`: one undo step until the drag ends. pub fn move_start(app: &mut App, at: Vec2) -> Drag { - app.s.begin_gesture("Move Motion Path"); + app.s.begin_gesture(tr_noop!("Move Motion Path")); Drag::MotionMove { last: pos2(at.x, at.y) } } @@ -229,7 +263,7 @@ fn add_at(app: &mut App, p: Pos2, xf: Xf) -> bool { if let Some(v) = app.run("motion.add_point", json!({"x": sp.x, "y": sp.y, "slop": PICK * xf.unit()})) { app.motion_anchors = v["anchor"].as_u64().map(|a| vec![a as usize]).unwrap_or_default(); app.points.clear(); - app.status_ok(format!("Added a point to the motion path. {} to undo.", crate::platform::shortcut_label("Ctrl+Z"))); + app.status_ok(tr!("Added a point to the motion path. {undo} to undo.", undo = app.undo_key())); } true } @@ -278,20 +312,39 @@ pub fn delete_selected(app: &mut App) { } if let Some(v) = app.run("motion.delete_points", json!({"anchors": anchors})) { let n = v["deleted"].as_u64().unwrap_or(0); - let what = if n == 1 { "1 point".to_string() } else { format!("{n} points") }; - let undo = crate::platform::shortcut_label("Ctrl+Z"); - app.status_ok(if v["kept_ends"].as_bool() == Some(true) { format!("Deleted {what} from the motion path; its ends stay, as they are where the motion starts and ends. {undo} to undo.") } else { format!("Deleted {what} from the motion path. {undo} to undo.") }); + let undo = app.undo_key(); + app.status_ok(if v["kept_ends"].as_bool() == Some(true) { + trn!("Deleted {n} point from the motion path; its ends stay, as they are where the motion starts and ends. {undo} to undo.", "Deleted {n} points from the motion path; its ends stay, as they are where the motion starts and ends. {undo} to undo.", n, undo = undo) + } else { + trn!("Deleted {n} point from the motion path. {undo} to undo.", "Deleted {n} points from the motion path. {undo} to undo.", n, undo = undo) + }); app.motion_anchors.clear(); } } +/// Pins anchor `a` to the playhead's frame (ADR 0049): the object passes it exactly then. +pub fn pin_anchor(app: &mut App, a: usize) { + if let Some(v) = app.run("motion.pin_point", json!({"anchor": a})) { + let frame = v["frame"].as_u64().unwrap_or(0) + 1; + app.status_ok(tr!("Pinned point {anchor} to frame {frame}: the object passes it then. {undo} to undo.", anchor = a, frame = frame, undo = app.undo_key())); + } +} + +/// Lets anchor `a`'s pin go: it shapes the path only, and its frame's X/Y keys go. +pub fn unpin_anchor(app: &mut App, a: usize) { + if let Some(v) = app.run("motion.unpin_point", json!({"anchor": a})) { + let frame = v["frame"].as_u64().unwrap_or(0) + 1; + app.status_ok(tr!("Unpinned point {anchor} from frame {frame}: it shapes the path only. {undo} to undo.", anchor = a, frame = frame, undo = app.undo_key())); + } +} + /// Makes the selected anchors smooth or corners (one undo step). pub fn convert_selected(app: &mut App, smooth: bool) { let anchors = selected(app); if anchors.is_empty() { return; } - app.s.begin_gesture(if smooth { "Make Smooth" } else { "Make Corner" }); + app.s.begin_gesture(if smooth { tr_noop!("Make Smooth") } else { tr_noop!("Make Corner") }); for a in anchors { app.run("motion.convert_point", json!({"anchor": a, "smooth": smooth})); } @@ -355,28 +408,57 @@ pub fn menu(app: &mut App, ui: &mut egui::Ui) -> bool { return false; } let anchors = selected(app); - let Some(n) = shown(app).map(|s| s.path.cmds.len()) else { return false }; + let Some(shown) = shown(app) else { return false }; + let n = shown.path.cmds.len(); if anchors.is_empty() { return false; } - if ui.button("Make Smooth").clicked() { + if ui.button(tr!("Make Smooth")).clicked() { convert_selected(app, true); ui.close(); } - if ui.button("Make Corner").clicked() { + if ui.button(tr!("Make Corner")).clicked() { convert_selected(app, false); ui.close(); } ui.separator(); + // Pinning to frames (ADR 0049): one anchor at a time, to the playhead's frame. + if let [a] = anchors[..] { + let frame = shown.start + shown.offset + 1; + match shown.pin(a) { + Some(p) if shown.is_end(a) => { + ui.add_enabled(false, egui::Button::new(tr!("Pinned to Frame {frame}", frame = shown.start + p.frame + 1))).on_disabled_hover_text(tr!("The ends of a motion path are always pinned, to the first and last position keys")); + } + Some(p) => { + if ui.button(tr!("Unpin from Frame {frame}", frame = shown.start + p.frame + 1)).on_hover_text(tr!("The point shapes the path only; its frame's X and Y keyframes go")).clicked() { + unpin_anchor(app, a); + ui.close(); + } + } + None => { + let why = shown.unpinnable(a); + let resp = ui.add_enabled(why.is_none(), egui::Button::new(tr!("Pin to Frame {frame}", frame = frame))); + let resp = match why { + Some(why) => resp.on_disabled_hover_text(why), + None => resp.on_hover_text(tr!("The object passes this point exactly on frame {frame}", frame = frame)), + }; + if resp.clicked() { + pin_anchor(app, a); + ui.close(); + } + } + } + ui.separator(); + } let deletable = anchors.iter().any(|a| !is_end(*a, n)); - let label = if anchors.len() > 1 { "Delete Points" } else { "Delete Point" }; + let label = if anchors.len() > 1 { tr!("Delete Points") } else { tr!("Delete Point") }; let resp = ui.add_enabled(deletable, egui::Button::new(label)); - let resp = if deletable { resp } else { resp.on_disabled_hover_text("The ends of a motion path are where the motion starts and ends: drag them to move them") }; + let resp = if deletable { resp } else { resp.on_disabled_hover_text(tr!("The ends of a motion path are where the motion starts and ends: drag them to move them")) }; if resp.clicked() { delete_selected(app); ui.close(); } - if ui.button("Straighten Path").on_hover_text("Back to the straight path the X and Y curves trace").clicked() { + if ui.button(tr!("Straighten Path")).on_hover_text(tr!("Back to the straight path the X and Y curves trace")).clicked() { app.run("motion.clear_path", json!({})); app.motion_anchors.clear(); ui.close(); @@ -414,6 +496,17 @@ fn anchor_box(painter: &Painter, c: Pos2, filled: bool) { painter.rect_stroke(r, 0.0, Stroke::new(1.5, T.tween_motion), StrokeKind::Middle); } +/// A pinned anchor: a diamond (the keyframe mark) with its frame number in a tag beside it. +fn pinned_anchor(painter: &Painter, c: Pos2, filled: bool, frame: u32) { + let r = 5.5; + let pts = vec![c + vec2(0.0, -r), c + vec2(r, 0.0), c + vec2(0.0, r), c + vec2(-r, 0.0)]; + painter.add(egui::Shape::convex_polygon(pts, if filled { T.tween_motion } else { T.ink }, Stroke::new(1.5, T.tween_motion))); + let g = painter.layout_no_wrap(frame.to_string(), font(Type::DataSmall), T.ink); + let tag = Rect::from_min_size(c + vec2(r + 3.0, -r - g.size().y - 1.0), g.size() + vec2(6.0, 2.0)); + painter.rect_filled(tag, T.rc(), T.tween_motion); + painter.galley(tag.min + vec2(3.0, 1.0), g, T.ink); +} + /// Draws the path: a line in the motion colour on a dark halo (it reads on any artwork), a dot /// per frame, larger on position keys and ringed at the playhead, and the anchors the tool can /// take (with the selected anchors' handles under Subselection). `hot` is what the pointer is @@ -451,8 +544,12 @@ pub fn draw(app: &App, painter: &Painter, shown: &Shown, xf: Xf, hot: Option pinned_anchor(painter, xf.to_screen(q), lit, shown.start + p.frame + 1), + None => anchor_box(painter, xf.to_screen(q), lit), + } } } } @@ -491,13 +588,313 @@ mod tests { let q = dragged(&p, Grab::Segment(1, 0.5), Vec2::new(0.0, 20.0), false); assert!(q.segment_point(1, 0.5).unwrap().distance(before + Vec2::new(0.0, 20.0)) < 1e-3); assert_eq!(q.point(1, ANCHOR), p.point(1, ANCHOR)); - // Selection takes only the ends; Subselection every anchor, and the Pen sees them all. - assert_eq!(grabbable_anchors(&p, Tool::Select).iter().map(|a| a.0).collect::>(), vec![0, 2]); - assert_eq!(grabbable_anchors(&p, Tool::Subselect).len(), 3); - assert_eq!(grabbable_anchors(&p, Tool::Pen).len(), 3); + // Selection takes the ends and pinned anchors; Subselection every anchor, and the Pen + // sees them all. + assert_eq!(grabbable_anchors(&p, &[], Tool::Select).iter().map(|a| a.0).collect::>(), vec![0, 2]); + assert_eq!(grabbable_anchors(&p, &[Pin { frame: 5, anchor: 1 }], Tool::Select).len(), 3); + assert_eq!(grabbable_anchors(&p, &[], Tool::Subselect).len(), 3); + assert_eq!(grabbable_anchors(&p, &[], Tool::Pen).len(), 3); assert_eq!(handles(&p, &[1]), vec![(1, C2, 1), (2, C1, 1)]); assert_eq!(handles(&p, &[0]), vec![(1, C1, 0)]); assert_eq!(handles(&p, &[0, 2]), vec![(1, C1, 0), (2, C2, 2)], "every selected anchor shows its handles"); assert!(is_end(0, 3) && is_end(2, 3) && !is_end(1, 3)); } + + /// The pointer and keyboard paths, on a headless app showing the sample's curved motion + /// path (the `motionpoints` screenshot setup: the span selected, Subselection, anchor 1). + mod headless { + use super::*; + + /// Stage and screen coordinates coincide. + const XF: Xf = Xf { origin: Pos2::ZERO, zoom: 1.0 }; + + #[test] + fn hit_finds_handles_anchors_and_segments_per_tool() { + let mut app = app(); + let s = shown(&app).expect("the motion path shows"); + assert_eq!(s.path.cmds.len(), 3); + let handle = s.path.point(1, C2).unwrap(); + assert_eq!(hit(&app, &s, screen(handle), XF, true), Some(Grab::Handle(1, C2))); + assert_eq!(hit(&app, &s, screen(anchor(&s, 1)), XF, true), Some(Grab::Anchor(1))); + assert_eq!(hit(&app, &s, far(), XF, true), None); + app.tool = Tool::Select; + assert_eq!(hit(&app, &s, screen(anchor(&s, 1)), XF, false), None, "Selection takes only the ends"); + assert_eq!(hit(&app, &s, screen(anchor(&s, 2)), XF, false), Some(Grab::Anchor(2))); + let mid = screen(s.path.segment_point(1, 0.5).unwrap()); + assert!(matches!(hit(&app, &s, mid, XF, true), Some(Grab::Segment(1, _)))); + assert_eq!(hit(&app, &s, mid, XF, false), None, "the press goes to the object first"); + } + + #[test] + fn clicks_select_anchors_and_shift_toggles_them() { + let mut app = app(); + let s = shown(&app).unwrap(); + assert!(click(&mut app, screen(anchor(&s, 0)), XF, false)); + assert_eq!(app.motion_anchors, vec![0]); + assert!(click(&mut app, screen(anchor(&s, 2)), XF, true)); + assert_eq!(app.motion_anchors, vec![0, 2]); + assert!(click(&mut app, screen(anchor(&s, 0)), XF, true)); + assert_eq!(app.motion_anchors, vec![2]); + assert!(click(&mut app, screen(s.path.segment_point(1, 0.5).unwrap()), XF, true), "on the path"); + assert_eq!(app.motion_anchors, vec![2], "Shift on the path keeps the selection"); + assert!(click(&mut app, screen(s.path.segment_point(1, 0.5).unwrap()), XF, false)); + assert!(app.motion_anchors.is_empty()); + app.motion_anchors = vec![1]; + assert!(!click(&mut app, far(), XF, false), "off the path"); + assert!(app.motion_anchors.is_empty()); + } + + #[test] + fn a_right_click_selects_the_anchor_under_it() { + let mut app = app(); + let s = shown(&app).unwrap(); + assert!(secondary_click(&mut app, screen(anchor(&s, 2)), XF)); + assert_eq!(app.motion_anchors, vec![2]); + app.motion_anchors = vec![1, 2]; + assert!(secondary_click(&mut app, screen(anchor(&s, 2)), XF)); + assert_eq!(app.motion_anchors, vec![1, 2], "a selection it is part of stays"); + assert!(secondary_click(&mut app, screen(s.path.segment_point(0, 0.5).unwrap_or_else(|| s.path.segment_point(1, 0.25).unwrap())), XF)); + assert!(!secondary_click(&mut app, far(), XF)); + app.tool = Tool::Select; + assert!(!secondary_click(&mut app, screen(anchor(&s, 2)), XF), "only with Subselection"); + } + + #[test] + fn a_double_click_on_the_path_adds_an_anchor_in_one_undo_step() { + let mut app = app(); + let s = shown(&app).unwrap(); + assert!(!double_click(&mut app, far(), XF)); + assert!(!double_click(&mut app, screen(anchor(&s, 1)), XF), "an anchor is there already"); + let steps = app.s.history().undo_len(); + assert!(double_click(&mut app, screen(s.path.segment_point(1, 0.5).unwrap()), XF)); + assert_eq!(cmds(&app), 4); + assert_eq!(app.motion_anchors.len(), 1, "the new anchor is selected"); + assert!(status(&app).contains("Added a point")); + assert_eq!(app.s.history().undo_len(), steps + 1); + app.tool = Tool::Select; + assert!(!double_click(&mut app, screen(s.path.segment_point(1, 0.5).unwrap()), XF), "only with Subselection"); + } + + #[test] + fn the_pen_adds_with_alt_click_on_the_path_only() { + let mut app = app(); + app.tool = Tool::Pen; + let s = shown(&app).unwrap(); + let mid = screen(s.path.segment_point(1, 0.5).unwrap()); + assert!(matches!(pen_hot(&app, mid, XF), Some(Grab::Segment(1, _)))); + assert_eq!(pen_hot(&app, screen(anchor(&s, 1)), XF), None); + assert_eq!(pen_hot(&app, far(), XF), None); + assert!(pen_alt_click(&mut app, mid, XF)); + assert_eq!(cmds(&app), 4); + app.tool = Tool::Subselect; + assert!(!pen_alt_click(&mut app, mid, XF), "only with the Pen"); + } + + #[test] + fn deleting_points_keeps_the_ends_and_says_so() { + let mut app = app(); + app.motion_anchors = vec![0, 1, 9]; + delete_selected(&mut app); + assert_eq!(cmds(&app), 2); + assert!(status(&app).contains("its ends stay"), "{}", status(&app)); + assert!(app.motion_anchors.is_empty()); + // Nothing selected: nothing happens. + let steps = app.s.history().undo_len(); + delete_selected(&mut app); + assert_eq!(app.s.history().undo_len(), steps); + } + + #[test] + fn deleting_a_middle_point_reports_one_point() { + let mut app = app(); + delete_selected(&mut app); + assert_eq!(cmds(&app), 2); + assert!(status(&app).starts_with("Deleted 1 point from the motion path."), "{}", status(&app)); + } + + #[test] + fn converting_points_is_one_undo_step() { + let mut app = app(); + let steps = app.s.history().undo_len(); + convert_selected(&mut app, false); + assert_eq!(app.s.history().undo_len(), steps + 1); + assert_eq!(app.s.undo_label(), Some("Make Corner")); + app.motion_anchors.clear(); + convert_selected(&mut app, true); + assert_eq!(app.s.history().undo_len(), steps + 1, "no anchor, no step"); + } + + #[test] + fn dragging_an_end_moves_it_in_one_undo_step() { + let mut app = app(); + let s = shown(&app).unwrap(); + let end = anchor(&s, 2); + let steps = app.s.history().undo_len(); + let drag = drag_start(&mut app, s, Grab::Anchor(2), end); + assert_eq!(app.motion_anchors, vec![2], "the grabbed anchor becomes the selection"); + let Drag::MotionPath { grab, start } = drag else { panic!("a motion path drag") }; + drag_to(&mut app, grab, start, start + vec2(10.0, 0.0), false); + drag_to(&mut app, grab, start, start + vec2(20.0, 5.0), false); + drag_end(&mut app); + assert!(app.motion_drag.is_none()); + assert_eq!(app.s.history().undo_len(), steps + 1); + let moved = anchor(&shown(&app).unwrap(), 2); + assert!(moved.distance(end + Vec2::new(20.0, 5.0)) < 1e-2, "{moved:?}"); + // With no drag in progress, following the pointer does nothing. + drag_to(&mut app, grab, start, start + vec2(99.0, 0.0), false); + assert_eq!(anchor(&shown(&app).unwrap(), 2), moved); + } + + #[test] + fn moving_the_whole_path_keeps_its_shape() { + let mut app = app(); + let s = shown(&app).unwrap(); + assert!(move_hit(&app, screen(anchor(&s, 1)), XF)); + assert!(move_hit(&app, screen(s.path.segment_point(1, 0.5).unwrap()), XF)); + assert!(!move_hit(&app, far(), XF)); + let before: Vec = s.path.anchors().into_iter().map(|(_, q)| q).collect(); + let drag = move_start(&mut app, before[0]); + assert!(matches!(drag, Drag::MotionMove { .. })); + move_to(&mut app, Vec2::ZERO); + move_to(&mut app, Vec2::new(5.0, -3.0)); + app.s.end_gesture(); + assert_eq!(app.s.undo_label(), Some("Move Motion Path")); + let after: Vec = shown(&app).unwrap().path.anchors().into_iter().map(|(_, q)| q).collect(); + for (a, b) in before.iter().zip(&after) { + assert!(b.distance(*a + Vec2::new(5.0, -3.0)) < 1e-2, "{a:?} -> {b:?}"); + } + } + + #[test] + fn pinning_from_the_menu_pins_to_the_playhead_and_unpinning_lets_go() { + let mut app = app(); + let s = shown(&app).unwrap(); + assert_eq!(s.pins.len(), 2, "only the ends are pinned"); + assert!(s.is_end(0) && s.pin(1).is_none()); + assert_eq!(s.unpinnable(1), None, "frame 10 is inside the motion"); + let steps = app.s.history().undo_len(); + pin_anchor(&mut app, 1); + assert_eq!(app.s.history().undo_len(), steps + 1); + assert!(status(&app).starts_with("Pinned point 1 to frame 10"), "{}", status(&app)); + let s = shown(&app).unwrap(); + assert_eq!(s.pin(1), Some(Pin { frame: 9, anchor: 1 })); + assert!(s.dots[9].distance(anchor(&s, 1)) < 1e-3, "the object is on the pinned anchor on its frame"); + // Selection now takes the pinned anchor too. + app.tool = Tool::Select; + assert_eq!(hit(&app, &s, screen(anchor(&s, 1)), XF, false), Some(Grab::Anchor(1))); + unpin_anchor(&mut app, 1); + assert!(status(&app).starts_with("Unpinned point 1 from frame 10"), "{}", status(&app)); + assert!(shown(&app).unwrap().pin(1).is_none()); + // Outside the motion the menu says why it can't pin. + app.s.set_frame(0); + assert!(shown(&app).unwrap().unpinnable(1).is_some_and(|w| w.contains("between frames 1 and"))); + } + + #[test] + fn the_menu_offers_pin_unpin_and_shows_an_ends_frame() { + let (mut app, ctx) = app_and_ctx(); + for anchors in [vec![1], vec![0], vec![2]] { + app.motion_anchors = anchors; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(menu(&mut app, ui)); + }); + out.textures_delta.clear(); + } + pin_anchor(&mut app, 1); + app.motion_anchors = vec![1]; + let s = shown(&app).unwrap(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(menu(&mut app, ui)); + draw(&app, ui.painter(), &s, XF, Some(Grab::Anchor(1))); + }); + out.textures_delta.clear(); + } + + #[test] + fn upkeep_forgets_anchors_the_path_lost() { + let mut app = app(); + app.motion_anchors = vec![1, 7]; + upkeep(&mut app); + assert_eq!(app.motion_anchors, vec![1]); + app.motion_anchors.clear(); + upkeep(&mut app); + assert!(app.motion_anchors.is_empty()); + } + + #[test] + fn delete_and_escape_act_on_the_selected_points() { + let (mut app, ctx) = app_and_ctx(); + frame_with_key(&ctx, &mut app, Key::Escape); + assert!(app.motion_anchors.is_empty(), "Escape drops the anchor selection"); + app.motion_anchors = vec![1]; + frame_with_key(&ctx, &mut app, Key::Delete); + assert_eq!(cmds(&app), 2); + // Not with Selection: Delete is then the global shortcut's. + app.tool = Tool::Select; + app.motion_anchors = vec![0]; + frame_with_key(&ctx, &mut app, Key::Escape); + assert_eq!(app.motion_anchors, vec![0]); + } + + #[test] + fn the_menu_and_the_drawing_need_subselection_and_a_selection() { + let (mut app, ctx) = app_and_ctx(); + let s = shown(&app).unwrap(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(menu(&mut app, ui)); + draw(&app, ui.painter(), &s, XF, Some(Grab::Handle(1, C2))); + app.motion_anchors.clear(); + assert!(!menu(&mut app, ui), "no anchor selected"); + app.tool = Tool::Select; + assert!(!menu(&mut app, ui)); + draw(&app, ui.painter(), &s, XF, Some(Grab::Segment(1, 0.5))); + }); + out.textures_delta.clear(); + } + + // ----- helpers ----- + + fn app_and_ctx() -> (App, egui::Context) { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + // Screenshot mode: default preferences, no autosave, no plug-in folder. + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + app.open_panel(Some("motionpoints")); + assert_eq!(app.tool, Tool::Subselect); + assert_eq!(app.motion_anchors, vec![1]); + (app, ctx) + } + + fn app() -> App { + app_and_ctx().0 + } + + fn frame_with_key(ctx: &egui::Context, app: &mut App, key: Key) { + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + let mut out = ctx.run_ui(input, |ui| consume_keys(app, ui.ctx())); + // The textures it made have nowhere to go: drop them. + out.textures_delta.clear(); + } + + fn anchor(s: &Shown, i: usize) -> Vec2 { + s.path.point(i, ANCHOR).unwrap() + } + + fn screen(q: Vec2) -> Pos2 { + XF.to_screen(q) + } + + fn far() -> Pos2 { + pos2(-5000.0, -5000.0) + } + + fn cmds(app: &App) -> usize { + shown(app).map_or(0, |s| s.path.cmds.len()) + } + + fn status(app: &App) -> String { + app.status.as_ref().map(|s| s.text.clone()).unwrap_or_default() + } + } } diff --git a/src/onion.rs b/src/onion.rs new file mode 100644 index 00000000..b950b6a9 --- /dev/null +++ b/src/onion.rs @@ -0,0 +1,547 @@ +//! Onion skin and Edit Multiple Frames in the editor (ADR 0047): the timeline's buttons and +//! onion menu, the markers on the frame ruler, and Edit Multiple Frames on the stage. +//! +//! The settings are view state ([`OnionSkin`], in `App::onion`); the options that carry over +//! between sessions are also in the preferences. Only Edit Multiple Frames' moves change the +//! document, through `frames.edit_multiple`. + +use crate::a11y::Named; +use crate::app::{App, Drag}; +use crate::prefs::{ONION_REACH_MAX, OnionPrefs}; +use crate::theme::{T, Type, color, font, text, to_color32, to_rgba}; +use anicraft_engine::doc::Rgba; +use anicraft_engine::geom::{Rect as GRect, Vec2}; +use anicraft_engine::onion::{FrameItem, Markers, OnionSkin, PRESETS}; +use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use serde_json::json; +use std::sync::Arc; + +/// The onion menu's popup (opened by its button, a right-click on the ruler, or `--open onion`). +pub const MENU_ID: &str = "onion_menu"; + +/// What the shown items depend on: document state, scene, playhead and the markers' frames. +type ItemsKey = (u64, usize, u32, u32, u32); +/// Every element Edit Multiple Frames shows, with its stage bounds. +pub type Shown = Arc>; + +/// The editor's onion state beyond [`OnionSkin`]. +#[derive(Default)] +pub struct OnionUi { + /// The marker being dragged on the ruler: the start (`true`) or the end. + pub drag: Option, + /// Edit Multiple Frames' selection: elements on keyframes within the markers. + pub sel: Vec, + /// Open the onion menu on the next frame. + pub open_menu: bool, + /// What Edit Multiple Frames shows, for (state, scene, playhead, first, last). + cache: Option<(ItemsKey, Shown)>, +} + +fn rgb(c: [u8; 3]) -> Rgba { + Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0) +} + +/// The settings a session starts with: off, with the saved options and colours. +pub fn from_prefs(p: &OnionPrefs) -> OnionSkin { + let mut o = OnionSkin { ghosts: false, edit_multiple: false, markers: Markers::Relative { before: p.before, after: p.after }, tint: p.tint, fade: p.fade, outlines: p.outlines, keyframes_only: p.keyframes_only, ..OnionSkin::default() }; + if p.all { + o.all(); + } + o.past = p.past.map_or_else(|| to_rgba(T.onion_past), rgb); + o.future = p.future.map_or_else(|| to_rgba(T.onion_future), rgb); + o +} + +/// The theme's colours where the user didn't pick their own (after a palette change). +pub fn refresh_colors(app: &mut App) { + app.onion.past = app.prefs.onion.past.map_or_else(|| to_rgba(T.onion_past), rgb); + app.onion.future = app.prefs.onion.future.map_or_else(|| to_rgba(T.onion_future), rgb); +} + +/// Changes the settings and saves the options that carry over. +fn change(app: &mut App, ctx: &egui::Context, f: impl FnOnce(&mut OnionSkin, &mut OnionPrefs)) { + let mut p = app.prefs.clone(); + f(&mut app.onion, &mut p.onion); + let o = app.onion; + match o.markers { + Markers::Relative { before, after } => { + p.onion.before = before.min(ONION_REACH_MAX); + p.onion.after = after.min(ONION_REACH_MAX); + p.onion.all = false; + } + Markers::Anchored { .. } => p.onion.all = o.is_all(), + } + (p.onion.tint, p.onion.fade, p.onion.outlines, p.onion.keyframes_only) = (o.tint, o.fade, o.outlines, o.keyframes_only); + app.set_prefs(ctx, p); +} + +/// The frames within the markers (0-based, inclusive). +pub fn range(app: &App) -> (u32, u32) { + app.onion.range(app.s.frame, app.s.frame_count()) +} + +/// What the stage composes now: `None` while playing or when nothing is on. +pub fn stage_skin(app: &App) -> Option<&OnionSkin> { + (!app.playing && app.onion.shows()).then_some(&app.onion) +} + +/// Onion skin on or off (the timeline button, View › Onion Skin, Alt+Shift+O). +pub fn toggle_ghosts(app: &mut App) { + app.onion.ghosts = !app.onion.ghosts; +} + +/// Edit Multiple Frames on or off. The selection starts empty either way: what was selected on +/// one frame is not what is selected on several. +pub fn toggle_edit_multiple(app: &mut App) { + app.onion.edit_multiple = !app.onion.edit_multiple; + app.onion_ui.sel.clear(); + if app.onion.edit_multiple { + app.s.selection.clear(); + app.status_ok(tr!("Edit Multiple Frames: the keyframes between the onion markers show at full strength. Select and drag artwork to move it on all of them; drag the markers on the frame ruler to choose the frames.")); + } +} + +/// Edit Multiple Frames is taking the Selection tool's input. +pub fn editing(app: &App) -> bool { + app.onion.edit_multiple && !app.playing && !crate::camera_tool::previewing(app) +} + +// ----- the menu ------------------------------------------------------------------------------ + +/// The onion menu: on/off, options, markers, colours. Stays open while options change. +pub fn menu(app: &mut App, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let o = app.onion; + let key = app.keymap.primary("view.onion").unwrap_or("").to_string(); + let mut ghosts = o.ghosts; + if ui.checkbox(&mut ghosts, a11y_key(tr!("Onion Skin"), &key)).changed() { + toggle_ghosts(app); + } + let mut multi = o.edit_multiple; + if ui.checkbox(&mut multi, tr!("Edit Multiple Frames")).on_hover_text(tr!("Show the keyframes between the markers at full strength, and select and move their artwork together")).changed() { + toggle_edit_multiple(app); + } + let mut outlines = o.outlines; + if ui.checkbox(&mut outlines, tr!("Outlines")).on_hover_text(tr!("Draw onion frames as outlines only")).changed() { + change(app, &ctx, |o, _| o.outlines = outlines); + } + let mut keys = o.keyframes_only; + if ui.checkbox(&mut keys, tr!("Keyframes Only")).on_hover_text(tr!("Onion-skin only the frames where a keyframe starts")).changed() { + change(app, &ctx, |o, _| o.keyframes_only = keys); + } + ui.separator(); + ui.label(text(Type::Caption, tr!("Markers"))); + let mut always = app.prefs.onion.always_markers; + if ui.checkbox(&mut always, tr!("Always Show Markers")).on_hover_text(tr!("Show the markers on the frame ruler even when onion skin is off")).changed() { + change(app, &ctx, |_, p| p.always_markers = always); + } + let mut anchored = o.anchored(); + if ui.checkbox(&mut anchored, tr!("Anchor Markers")).on_hover_text(tr!("Keep the markers on their frames instead of moving them with the playhead")).changed() { + let (f, n) = (app.s.frame, app.s.frame_count()); + change(app, &ctx, |o, _| o.set_anchored(anchored, f, n)); + } + ui.horizontal(|ui| { + for n in PRESETS { + let on = o.markers == Markers::Relative { before: n, after: n }; + if ui.selectable_label(on, tr!("Onion {n}", n = n)).on_hover_text(trn!("{n} frame before and after the playhead", "{n} frames before and after the playhead", n as usize)).clicked() { + change(app, &ctx, |o, _| o.preset(n)); + } + } + if ui.selectable_label(o.is_all(), tr!("Onion All")).on_hover_text(tr!("Every frame of the timeline")).clicked() { + change(app, &ctx, |o, _| o.all()); + } + }); + ui.separator(); + ui.label(text(Type::Caption, tr!("Colour"))); + let mut tint = o.tint; + if ui.checkbox(&mut tint, tr!("Tint")).on_hover_text(tr!("Tint frames before the playhead and after it in their colours; off, they keep their own colours")).changed() { + change(app, &ctx, |o, _| o.tint = tint); + } + let mut fade = o.fade; + if ui.checkbox(&mut fade, tr!("Fade by Distance")).on_hover_text(tr!("Frames farther from the playhead are fainter")).changed() { + change(app, &ctx, |o, _| o.fade = fade); + } + ui.horizontal(|ui| { + for past in [true, false] { + let name = if past { tr!("Before colour") } else { tr!("After colour") }; + ui.label(text(Type::Body, if past { tr!("Before") } else { tr!("After") })); + let mut c = to_color32(if past { o.past } else { o.future }); + let r = ui.color_edit_button_srgba(&mut c).named(name).on_hover_text(if past { tr!("Colour of the frames before the playhead") } else { tr!("Colour of the frames after the playhead") }); + if r.changed() { + let [cr, cg, cb, _] = c.to_srgba_unmultiplied(); + change(app, &ctx, |o, p| { + let pick = [cr, cg, cb]; + if past { + o.past = rgb(pick); + p.past = Some(pick); + } else { + o.future = rgb(pick); + p.future = Some(pick); + } + }); + } + } + let custom = app.prefs.onion.past.is_some() || app.prefs.onion.future.is_some(); + if ui.add_enabled(custom, egui::Button::new(tr!("Reset"))).on_hover_text(tr!("Back to the theme's colours")).clicked() { + change(app, &ctx, |o, p| { + p.past = None; + p.future = None; + o.past = to_rgba(T.onion_past); + o.future = to_rgba(T.onion_future); + }); + } + }); +} + +/// A checkbox label with its shortcut, as menus show it. +fn a11y_key(name: &str, key: &str) -> String { + crate::a11y::with_key(name, Some(key)) +} + +/// The timeline's onion buttons: Onion Skin, Edit Multiple Frames and the onion menu. +pub fn buttons(app: &mut App, ui: &mut egui::Ui) { + let key = app.keymap.primary("view.onion").map(str::to_string); + if crate::timeline::icon_button(ui, &crate::a11y::with_key(tr!("Onion skin"), key.as_deref()), Some(app.onion.ghosts), crate::icons::Icon::Onion).clicked() { + toggle_ghosts(app); + } + if crate::timeline::icon_button(ui, tr!("Edit Multiple Frames"), Some(app.onion.edit_multiple), crate::icons::Icon::EditMultiple).clicked() { + toggle_edit_multiple(app); + } + let (rect, resp) = ui.allocate_exact_size(vec2(16.0, crate::theme::TARGET), Sense::click()); + let hot = resp.hovered() || egui::Popup::is_id_open(ui.ctx(), egui::Id::new(MENU_ID)); + ui.painter().rect_filled(rect, T.rc(), if hot { T.header } else { Color32::TRANSPARENT }); + crate::icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(12.0, 12.0)), crate::icons::Icon::ChevronDown, if hot { T.icon_hot } else { T.icon }); + crate::a11y::control(ui, &resp, egui::WidgetType::Button, tr!("Onion skin options"), None); + let resp = resp.on_hover_text(tr!("Onion skin options: markers, outlines, colours")); + if std::mem::take(&mut app.onion_ui.open_menu) { + egui::Popup::open_id(ui.ctx(), egui::Id::new(MENU_ID)); + } + let shown = egui::Popup::menu(&resp).id(egui::Id::new(MENU_ID)).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(230.0); + menu(app, ui); + }); + // egui leaves the popup's own surface without a role or name. + if let Some(r) = shown { + ui.ctx().accesskit_node_builder(r.response.id, |node| { + node.set_role(egui::accesskit::Role::Menu); + node.set_label(tr!("Onion skin options")); + }); + } +} + +// ----- the markers on the frame ruler -------------------------------------------------------- + +/// Draws the onion markers on the frame ruler and lets them be dragged. `x_of` is a frame +/// cell's left edge, `frame_at` the frame under a pointer x. +pub fn ruler(app: &mut App, ui: &mut egui::Ui, ruler: Rect, cell_w: f32, x_of: impl Fn(u32) -> f32, frame_at: impl Fn(f32) -> u32) { + let shown = app.onion.shows() || app.prefs.onion.always_markers; + if !shown || app.playing { + app.onion_ui.drag = None; + return; + } + let (first, last) = range(app); + let p = app.s.frame; + let painter = ui.painter_at(ruler); + let (past, future) = (to_color32(app.onion.past), to_color32(app.onion.future)); + let dim = if app.onion.shows() { 1.0 } else { 0.5 }; + // The frames within the markers, before and after the playhead in their colours. + if first < p { + painter.rect_filled(Rect::from_min_max(pos2(x_of(first), ruler.top()), pos2(x_of(p), ruler.bottom())), 0.0, past.gamma_multiply(0.22 * dim)); + } + if last > p { + painter.rect_filled(Rect::from_min_max(pos2(x_of(p + 1), ruler.top()), pos2(x_of(last + 1), ruler.bottom())), 0.0, future.gamma_multiply(0.22 * dim)); + } + let frames = app.s.frame_count(); + let anchored = app.onion.anchored(); + for start in [true, false] { + let x = if start { x_of(first) } else { x_of(last + 1) }; + let c = if start { past } else { future }.gamma_multiply(dim); + // A bracket: [ at the start, ] at the end. + let serif = (cell_w * 0.5).clamp(3.0, 6.0) * if start { 1.0 } else { -1.0 }; + let (top, bottom) = (ruler.top() + 2.0, ruler.bottom() - 1.0); + let stroke = Stroke::new(2.0, c); + painter.line_segment([pos2(x, top), pos2(x, bottom)], stroke); + painter.line_segment([pos2(x, top), pos2(x + serif, top)], stroke); + painter.line_segment([pos2(x, bottom), pos2(x + serif, bottom)], stroke); + if anchored { + // Anchored markers carry a pin. + painter.circle_filled(pos2(x + serif * 0.6, ruler.center().y), 2.0, c); + } + let hit = Rect::from_center_size(pos2(x, ruler.center().y), vec2(10.0, ruler.height())); + let id = ui.id().with(("onion_marker", start)); + let resp = ui.interact(hit, id, crate::a11y::pointer_only()); + let at = if start { first } else { last }; + let name = if start { tr!("Onion start marker") } else { tr!("Onion end marker") }; + resp.widget_info(|| egui::WidgetInfo::slider(true, f64::from(at + 1), name)); + if resp.hovered() || resp.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if resp.drag_started() { + app.onion_ui.drag = Some(start); + } + if resp.dragged() + && app.onion_ui.drag == Some(start) + && let Some(ptr) = resp.interact_pointer_pos() + { + // The end marker sits after its frame's cell: aim at the cell the pointer is in. + let f = frame_at(if start { ptr.x + cell_w * 0.5 } else { ptr.x - cell_w * 0.5 }); + app.onion.drag_marker(start, f, p, frames); + } + if resp.drag_stopped() { + app.onion_ui.drag = None; + // Saved when let go, not on every step of the drag. + let ctx = ui.ctx().clone(); + change(app, &ctx, |_, _| {}); + } + let tip = if anchored { tr!("Drag to choose the frames onion skin shows (anchored: they stay when the playhead moves)") } else { tr!("Drag to choose how many frames onion skin shows before and after the playhead") }; + resp.on_hover_text(tip); + } +} + +// ----- Edit Multiple Frames on the stage ------------------------------------------------------ + +/// Every element Edit Multiple Frames shows, with its stage bounds (cached per document state, +/// playhead and markers). +pub fn items(app: &mut App) -> Shown { + let (first, last) = range(app); + let key = (app.s.state, app.s.scene, app.s.frame, first, last); + if let Some((k, v)) = &app.onion_ui.cache + && *k == key + { + return v.clone(); + } + let v = Arc::new(app.s.multi_frame_items(first, last)); + app.onion_ui.cache = Some((key, v.clone())); + v +} + +/// The selection, less what isn't shown any more (after an undo, a marker drag, a new frame). +fn live_selection(app: &mut App) -> Vec { + let shown = items(app); + let sel: Vec = app.onion_ui.sel.iter().copied().filter(|it| shown.iter().any(|(s, _)| s == it)).collect(); + app.onion_ui.sel.clone_from(&sel); + sel +} + +/// Moves the selection by `d` on every keyframe it is on (no-op when nothing is selected). +fn move_by(app: &mut App, d: Vec2) -> bool { + let sel = live_selection(app); + if sel.is_empty() || d == Vec2::ZERO { + return false; + } + let (first, last) = range(app); + let items: Vec = sel.iter().map(FrameItem::to_json).collect(); + app.run("frames.edit_multiple", json!({"first": first, "last": last, "dx": d.x, "dy": d.y, "items": items})).is_some() +} + +/// A press on the stage with Edit Multiple Frames on: on artwork, select it (unless it is) and +/// move; elsewhere, a marquee. +pub fn drag_start(app: &mut App, sp: Pos2, shift: bool, zoom: f32) -> Drag { + let (first, last) = range(app); + match app.s.multi_frame_pick(first, last, Vec2::new(sp.x, sp.y), 3.0 / zoom.max(1e-3)) { + Some(it) => { + if !app.onion_ui.sel.contains(&it) { + if !shift { + app.onion_ui.sel.clear(); + } + app.onion_ui.sel.push(it); + } + // Undo labels stay English in the history and are translated where they show. + app.s.begin_gesture(tr_noop!("Move")); + Drag::MultiMove { last: sp } + } + None => Drag::MultiMarquee { start: sp, cur: sp }, + } +} + +/// The pointer moved to `c` during a move. +pub fn drag_to(app: &mut App, last: &mut Pos2, c: Pos2) { + let d = c - *last; + if d.length_sq() > 0.0 && move_by(app, Vec2::new(d.x, d.y)) { + *last = c; + } +} + +/// A click: select what is under the pointer (Shift adds or takes away), or nothing. +pub fn click(app: &mut App, sp: Pos2, shift: bool, zoom: f32) { + let (first, last) = range(app); + match app.s.multi_frame_pick(first, last, Vec2::new(sp.x, sp.y), 3.0 / zoom.max(1e-3)) { + Some(it) if shift => match app.onion_ui.sel.iter().position(|s| *s == it) { + Some(i) => { + app.onion_ui.sel.remove(i); + } + None => app.onion_ui.sel.push(it), + }, + Some(it) => app.onion_ui.sel = vec![it], + None if !shift => app.onion_ui.sel.clear(), + None => {} + } +} + +/// A marquee let go: what lies wholly inside it, on every keyframe shown. +pub fn marquee(app: &mut App, a: Pos2, b: Pos2, shift: bool) { + let r = GRect::from_points(Vec2::new(a.x, a.y), Vec2::new(b.x, b.y)); + let inside: Vec = items(app).iter().filter(|(_, bb)| !bb.is_empty() && r.contains(bb.min) && r.contains(bb.max)).map(|(it, _)| *it).collect(); + if !shift { + app.onion_ui.sel.clear(); + } + for it in inside { + if !app.onion_ui.sel.contains(&it) { + app.onion_ui.sel.push(it); + } + } +} + +/// Select All with Edit Multiple Frames on: every element on every keyframe shown. +pub fn select_all(app: &mut App) { + app.onion_ui.sel = items(app).iter().map(|(it, _)| *it).collect(); + let n = app.onion_ui.sel.len(); + app.status_ok(trn!("Selected {n} element on the frames between the markers", "Selected {n} elements on the frames between the markers", n)); +} + +/// The arrow keys with Edit Multiple Frames on: one undo step per press. +pub fn nudge(app: &mut App, d: Vec2) { + let own = !app.s.in_gesture(); + if own { + app.s.begin_gesture(tr_noop!("Move")); // i18n-exempt: an undo label (the engine's English, translated where shown) + } + move_by(app, d); + if own { + app.s.end_gesture(); + } +} + +/// Boxes around the selection on every keyframe (and the artwork under the pointer), and the +/// marquee being dragged. +pub fn draw(app: &mut App, painter: &egui::Painter, to_screen: impl Fn(Vec2) -> Pos2, hover: Option, zoom: f32) { + let sel = live_selection(app); + let shown = items(app); + let box_of = |b: &GRect| Rect::from_min_max(to_screen(b.min), to_screen(b.max)).expand(1.0); + if let Some(h) = hover + && app.drag == Drag::None + { + let (first, last) = range(app); + if let Some(it) = app.s.multi_frame_pick(first, last, Vec2::new(h.x, h.y), 3.0 / zoom.max(1e-3)) + && !sel.contains(&it) + && let Some((_, b)) = shown.iter().find(|(s, _)| *s == it) + { + painter.rect_stroke(box_of(b), 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.55)), StrokeKind::Middle); + } + } + for (it, b) in shown.iter().filter(|(it, _)| sel.contains(it)) { + if b.is_empty() { + continue; + } + let r = box_of(b); + // The playhead's keyframe in the selection colour; the others a step lighter, so it is + // clear which artwork is on this frame. + let here = app.s.doc.timeline(app.s.scene).layer(it.layer).and_then(|l| l.keyframe_at(app.s.frame)).is_some_and(|k| k.start == it.frame); + let c = if here { T.selection } else { T.selection.gamma_multiply(0.7) }; + painter.rect_stroke(r, 0.0, Stroke::new(if here { 1.5 } else { 1.0 }, c), StrokeKind::Middle); + } + if let Drag::MultiMarquee { start, cur } = app.drag { + 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, Stroke::new(1.0, T.selection), StrokeKind::Middle); + } +} + +/// A caption on the stage while Edit Multiple Frames is on: which frames it shows. +pub fn stage_badge(app: &App, painter: &egui::Painter, canvas: Rect) { + if !editing(app) { + return; + } + let (first, last) = range(app); + let s = tr!("Edit Multiple Frames: {first}–{last}", first = first + 1, last = last + 1); + let at = canvas.left_top() + vec2(10.0, 8.0); + let galley = painter.layout_no_wrap(s, font(Type::Caption), color(Type::Caption)); + let r = Rect::from_min_size(at, galley.size()).expand2(vec2(6.0, 3.0)); + painter.rect_filled(r, T.rc(), T.panel_alt); + painter.galley(at, galley, color(Type::Caption)); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app() -> App { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + // Screenshot mode: default preferences, nothing saved. + App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))) + } + + #[test] + fn edit_multiple_frames_selects_and_moves_across_keyframes_in_one_step() { + let mut a = app(); + a.open_panel(Some("editmultiple")); + assert!(editing(&a) && a.s.selection.is_empty(), "the playhead's selection is let go"); + let sel = a.onion_ui.sel.clone(); + assert!(sel.iter().any(|it| it.frame != sel[0].frame), "artwork on more than one keyframe: {sel:?}"); + // Where each selected element is on its own keyframe. + let at = |a: &App| -> Vec { + sel.iter() + .map(|it| { + let l = a.s.doc.timeline(a.s.scene).layer(it.layer).expect("layer"); + let k = l.keyframes.iter().find(|k| k.start == it.frame).expect("keyframe"); + k.elements.iter().find(|e| e.id == it.element).expect("element").transform.translation().x + }) + .collect() + }; + let before = at(&a); + let steps = a.s.history_len(); + nudge(&mut a, Vec2::new(10.0, 0.0)); + assert_eq!(a.s.history_len(), steps + 1, "one undo step"); + for (b, c) in before.iter().zip(at(&a)) { + assert!((c - b - 10.0).abs() < 1e-3, "{b} → {c}"); + } + a.s.undo().expect("undo"); + assert_eq!(at(&a), before, "one undo takes it all back"); + assert_eq!(a.onion_ui.sel, sel, "the selection stays"); + // Off: the selection goes with it, and arrow keys act on the playhead's selection again. + toggle_edit_multiple(&mut a); + assert!(!editing(&a) && a.onion_ui.sel.is_empty()); + } + + #[test] + fn a_marquee_takes_what_lies_wholly_inside_on_every_keyframe() { + let mut a = app(); + a.open_panel(Some("editmultiple")); + let shown = items(&mut a); + let (first, _) = shown.iter().find(|(_, b)| b.max.x < 640.0 && b.max.y < 400.0 && !b.is_empty()).copied().expect("something in the top left"); + marquee(&mut a, pos2(-5.0, -5.0), pos2(640.0, 400.0), false); + assert!(a.onion_ui.sel.contains(&first)); + assert!(a.onion_ui.sel.iter().all(|it| shown.iter().any(|(s, b)| s == it && b.max.x <= 640.0 && b.max.y <= 400.0))); + marquee(&mut a, pos2(5000.0, 5000.0), pos2(5001.0, 5001.0), false); + assert!(a.onion_ui.sel.is_empty()); + } + + #[test] + fn options_are_saved_and_come_back() { + let mut a = app(); + let ctx = egui::Context::default(); + change(&mut a, &ctx, |o, p| { + o.preset(5); + o.outlines = true; + o.keyframes_only = true; + o.fade = false; + p.past = Some([1, 2, 3]); + }); + let p = a.prefs.onion.clone(); + assert_eq!((p.before, p.after, p.all, p.outlines, p.keyframes_only, p.fade, p.past), (5, 5, false, true, true, false, Some([1, 2, 3]))); + let back = from_prefs(&p); + assert_eq!((back.markers, back.outlines, back.keyframes_only, back.fade, back.ghosts), (Markers::Relative { before: 5, after: 5 }, true, true, false, false)); + assert_eq!(srgb_of(back.past), [1, 2, 3]); + change(&mut a, &ctx, |o, _| o.all()); + assert!(a.prefs.onion.all && from_prefs(&a.prefs.onion).is_all()); + // A broken file can't ask for more than the limit. + let mut big = a.prefs.clone(); + big.onion.before = u32::MAX; + assert_eq!(big.sanitized().onion.before, ONION_REACH_MAX); + } + + fn srgb_of(c: Rgba) -> [u8; 3] { + let [r, g, b, _] = to_color32(c).to_srgba_unmultiplied(); + [r, g, b] + } +} diff --git a/src/panels.rs b/src/panels.rs index dcdb8b2d..36e64f91 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -4,7 +4,6 @@ use crate::app::{App, LibraryItem, 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 crate::a11y::{self, Named}; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::{Value, json}; @@ -31,6 +30,7 @@ fn tool_icon(tool: Tool) -> Icon { Tool::InkBottle => Icon::Ink, Tool::Eyedropper => Icon::Eyedropper, Tool::Camera => Icon::Camera, + Tool::Bone => Icon::Bone, Tool::Hand => Icon::Hand, Tool::Zoom => Icon::Zoom, } @@ -63,12 +63,12 @@ fn tool_column(app: &mut App, ui: &mut egui::Ui, area: Rect) { let tint = if active { T.on_active } else if resp.hovered() { T.icon_hot } else { T.icon }; icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(TOOL_ICON, TOOL_ICON)), tool_icon(tool), tint); // "Pen tool (P)": what the tooltip says first, and what a screen reader says. - let name = a11y::with_key(&format!("{} tool", tool.label()), app.keymap.primary(crate::keymap::tool_id(tool))); + let name = a11y::with_key(&tr!("{tool} tool", tool = crate::i18n::t(tool.label())), app.keymap.primary(crate::keymap::tool_id(tool))); a11y::control(ui, &resp, WidgetType::Button, &name, Some(active)); if active { a11y::anchor(ui, a11y::Region::Tools, area, &resp); } - let resp = resp.on_hover_text(format!("{name}\n{}", tool.hint())); + let resp = resp.on_hover_text(format!("{name}\n{}", crate::i18n::t(tool.hint()))); if resp.clicked() { app.tool = tool; } @@ -84,6 +84,26 @@ fn tool_column(app: &mut App, ui: &mut egui::Ui, area: Rect) { ui.add_space(4.0); } } + // Snap to Objects (Animate's magnet, ADR 0042): on, dragged points and selections snap + // to points, lines and fill edges. + let (rect, resp) = ui.allocate_exact_size(vec2(TOOL_BUTTON, TOOL_BUTTON), Sense::click()); + let on = app.s.style.snap_objects; + let bg = if on { + T.active + } else if resp.hovered() { + T.header + } else { + Color32::TRANSPARENT + }; + ui.painter().rect_filled(rect, T.rc(), bg); + let tint = if on { T.on_active } else if resp.hovered() { T.icon_hot } else { T.icon }; + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(TOOL_ICON, TOOL_ICON)), Icon::Magnet, tint); + let name = a11y::with_key(tr!("Snap to Objects"), app.keymap.primary("draw.snap_to_objects")); + a11y::control(ui, &resp, WidgetType::Checkbox, &name, Some(on)); + let resp = resp.on_hover_text(if on { tr!("{name}: on\nDragged points and selections snap to points, lines and fill edges within 10 pixels.", name = name) } else { tr!("{name}: off\nDragged points and selections snap to points, lines and fill edges within 10 pixels.", name = name) }); + if resp.clicked() { + app.run("draw.snap_to_objects", json!({})); + } ui.add_space(10.0); // fill / stroke swatches let st = &app.s.style; @@ -103,7 +123,7 @@ fn tool_column(app: &mut App, ui: &mut egui::Ui, area: Rect) { pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { ui.horizontal_centered(|ui| { // The scene being edited; the menu switches scenes and manages them. - let name = app.s.doc.scenes.get(app.s.scene).map_or_else(|| "Scene".to_string(), |s| s.name.clone()); + let name = app.s.doc.scenes.get(app.s.scene).map_or_else(|| tr!("Scene").to_string(), |s| s.name.clone()); egui::ComboBox::from_id_salt("scene").selected_text(text(Type::Body, name).strong()).height(480.0).show_ui(ui, |ui| { ui.set_min_width(240.0); let scenes: Vec<(String, u32)> = app.s.doc.scenes.iter().map(|s| (s.name.clone(), s.timeline.frame_count())).collect(); @@ -127,7 +147,7 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { } }) .response - .set_name("Scene"); + .set_name(tr!("Scene")); 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)); @@ -135,7 +155,7 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::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() { + if ui.selectable_label(false, tr!("Fit in window")).clicked() { app.view.fit = true; } for pct in [25.0f32, 50.0, 100.0, 200.0, 400.0, 800.0] { @@ -145,12 +165,12 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { } }) .response - .set_name("Zoom"); - if ui.selectable_label(app.onion, "Onion skin").clicked() { - app.onion = !app.onion; + .set_name(tr!("Zoom")); + if ui.selectable_label(app.onion.ghosts, tr!("Onion skin")).clicked() { + crate::onion::toggle_ghosts(app); } let st = app.s.doc.stage; - ui.label(text(Type::Data, format!("{} × {} px", st.width, st.height)).color(T.text_faint)); + ui.label(text(Type::Data, format!("{} × {} px", st.width, st.height)).color(T.text_faint)); // i18n-exempt: stage size, numbers and a unit }); }); } @@ -164,19 +184,24 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let wide = ui.available_width() >= 1000.0; 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.label(small(tr!("undo {steps} · {size} MB", steps = app.s.history().undo_len(), size = format!("{:.1}", app.s.history().bytes() as f32 / (1024.0 * 1024.0))))); ui.add_space(12.0); if let Some(a) = crate::autosave::status(app, now) { - ui.label(small(a)).on_hover_text("A recovery copy of your unsaved work. If AniCraft closes unexpectedly, the next start offers it back."); + ui.label(small(a)).on_hover_text(tr!("A recovery copy of your unsaved work. If AniCraft closes unexpectedly, the next start offers it back.")); ui.add_space(12.0); } if wide { if let Some((n, mb, hit)) = app.stage_cache.stats() { - ui.label(small(format!("cache {n} fr · {mb:.0} MB · {hit:.0}% hit"))); + ui.label(small(tr!("cache {frames} fr · {size} MB · {hit}% hit", frames = n, size = format!("{mb:.0}"), hit = format!("{hit:.0}")))); 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, renderer_tag(app)))); + let ms = format!("{:.1}", app.stage_cache.ms); + let line = match renderer_tag(app) { + Some(renderer) => tr!("render {ms} ms · {renderer} · tiles {ready}/{needed}", ms = ms, renderer = renderer, ready = ready, needed = needed), + None => tr!("render {ms} ms · tiles {ready}/{needed}", ms = ms, ready = ready, needed = needed), + }; + ui.label(small(line)); } if let Some(p) = app.cursor_stage { ui.label(small(format!("x {:.0} y {:.0}", p.x, p.y))); @@ -185,7 +210,7 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) { let msg = app.status.as_ref().filter(|s| s.error || now - s.at < 8.0 || s.at == 0.0); let (line, colour) = match msg { Some(s) => (s.text.as_str(), if s.error { T.error } else { T.ok }), - None => (app.tool.hint(), color(Type::Label)), + None => (crate::i18n::t(app.tool.hint()), color(Type::Label)), }; let r = ui.add(egui::Label::new(text(Type::Label, line).color(colour)).truncate()); // Screen readers announce what an action did ("Deleted layer — Ctrl+Z to undo") @@ -196,20 +221,20 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) { }); } -/// Who draws the stage, when this build can draw it on the GPU (ADR 0019): " GPU", or " CPU" +/// Who draws the stage, when this build can draw it on the GPU (ADR 0019): "GPU", or "CPU" /// with what kept the GPU out. -fn renderer_tag(app: &App) -> String { +fn renderer_tag(app: &App) -> Option { use crate::gpu_stage::State; if !crate::gpu_stage::AVAILABLE { - return String::new(); - } - match (app.stage_cache.gpu.state(), &app.stage_cache.drawn_by) { - (State::Starting, _) => " · GPU starting".into(), - (State::Failed(_), _) => " · CPU (GPU unavailable)".into(), - (State::Running { .. }, Some((true, _))) => " · GPU".into(), - (State::Running { .. }, Some((false, Some(why)))) => format!(" · CPU for {why}"), - _ => " · CPU".into(), + return None; } + Some(match (app.stage_cache.gpu.state(), &app.stage_cache.drawn_by) { + (State::Starting, _) => tr!("GPU starting").into(), + (State::Failed(_), _) => tr!("CPU (GPU unavailable)").into(), + (State::Running { .. }, Some((true, _))) => "GPU".into(), // i18n-exempt: renderer name + (State::Running { .. }, Some((false, Some(why)))) => tr!("CPU for {reason}", reason = crate::i18n::t_dyn(why)), + _ => "CPU".into(), // i18n-exempt: renderer name + }) } // ----- right dock --------------------------------------------------------------------------- @@ -244,21 +269,21 @@ pub fn right(app: &mut App, ui: &mut egui::Ui) { let dock = ui.max_rect(); // Dock sections are layout bands; each folds away to give the others room. let props = egui::ScrollArea::vertical().id_salt("props").max_height(h * 0.56).auto_shrink([false, true]).show(ui, |ui| { - crate::theme::section_with_header(ui, "dock_properties", Section::Band, "Properties", None, |ui| { + crate::theme::section_with_header(ui, "dock_properties", Section::Band, tr!("Properties"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| properties(app, ui)); }) .0 }); - section(ui, "dock_align", Section::Band, "Align", None, |ui| { + section(ui, "dock_align", Section::Band, tr!("Align"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| align_panel(app, ui)); }); // Ctrl+F6 lands on the Properties and Library headers; each panel owns the dock down to the // next one (Align goes with Properties, History with the Library). let split = ui.cursor().top(); - let (library_header, _) = crate::theme::section_with_header(ui, "dock_library", Section::Band, "Library", None, |ui| { + let (library_header, _) = crate::theme::section_with_header(ui, "dock_library", Section::Band, tr!("Library"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); }); - section(ui, "dock_history", Section::Band, "History", None, |ui| { + section(ui, "dock_history", Section::Band, tr!("History"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| history(app, ui)); }); a11y::anchor(ui, a11y::Region::Properties, Rect::from_min_max(dock.min, pos2(dock.right(), split)), &props.inner); @@ -276,11 +301,11 @@ fn align_panel(app: &mut App, ui: &mut egui::Ui) { 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() { T.icon_hot } 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(), + Some(k) => format!("{} ({})", crate::i18n::t_cmd(c.id, c.label), crate::platform::shortcut_label(k)), + None => crate::i18n::t_cmd(c.id, c.label).to_string(), }); a11y::control(ui, &resp, WidgetType::Button, &tip, None); - let tip = if has_sel { tip } else { format!("{tip}\nSelect something to align") }; + let tip = if has_sel { tip } else { tr!("{command}\nSelect something to align", command = tip) }; 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!({}) }); @@ -301,7 +326,7 @@ fn align_panel(app: &mut App, ui: &mut egui::Ui) { 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)"); + crate::theme::checkbox(ui, &mut app.align_to_stage, text(Type::Body, tr!("To stage"))).on_hover_text(tr!("Align to the stage instead of the selection's bounds (a single shape always aligns to the stage)")); }); } @@ -313,18 +338,18 @@ fn history(app: &mut App, ui: &mut egui::Ui) { 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" }; + let base = if evicted > 0 { tr!("… older steps freed (memory budget)") } else { tr!("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() { + if ui.selectable_label(current, crate::i18n::t_dyn(label).into_owned()).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() { + if ui.selectable_label(false, text(Type::Body, crate::i18n::t_dyn(label)).color(T.text_faint).italics()).clicked() { target = Some(past.len() + i + 1); } } @@ -337,35 +362,104 @@ fn history(app: &mut App, ui: &mut egui::Ui) { } 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(); + // The selection on every layer (ADR 0044). + let sel: Vec<_> = app.s.selected_elements().into_iter().map(|(_, e)| e).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::Text | Tool::Pencil | Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper) { - let title = format!("{} tool", app.tool.label()); + let title = tr!("{tool} tool", tool = crate::i18n::t(app.tool.label())); section(ui, "prop_tool", Section::Rule, &title, None, |ui| tool_props(app, ui)); } + // ---- Snap to Objects for the tools that drag points and selections (ADR 0042) ---- + if matches!(app.tool, Tool::Select | Tool::Subselect | Tool::Transform) { + let title = tr!("{tool} tool", tool = crate::i18n::t(app.tool.label())); + section(ui, "prop_tool", Section::Rule, &title, None, |ui| { + let mut on = app.s.style.snap_objects; + row_prose(ui, tr!("Snapping"), |ui| { + crate::theme::checkbox(ui, &mut on, tr!("Snap to objects")).on_hover_text(tr!("Dragged points and selections snap to points, lines and fill edges within 10 pixels (the magnet under the tools)")); + }); + if on != app.s.style.snap_objects { + app.run("draw.snap_to_objects", json!({"on": on})); + } + }); + } // ---- the camera, with the Camera tool or its layer active (ADR 0027) ---- let camera_layer = app.s.doc.timeline(app.s.scene).camera_layer().map(|l| l.id); if camera_layer.is_some() && (app.tool == Tool::Camera || camera_layer == Some(app.s.layer)) { - section(ui, "prop_camera", Section::Rule, "Camera", None, |ui| camera_props(app, ui)); + section(ui, "prop_camera", Section::Rule, tr!("Camera"), None, |ui| camera_props(app, ui)); + } + // ---- the bone picked on the stage (ADR 0043) ---- + if let Some(id) = app.bone_sel { + let name = app.s.doc.timeline(app.s.scene).layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| b.name.clone())); + if let Some(name) = name { + let title = if name.is_empty() { tr!("Bone").to_string() } else { tr!("Bone: {name}", name = name) }; + section(ui, "prop_bone", Section::Rule, &title, None, |ui| bone_props(app, ui, id)); + } } 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())); + // One count per template: the layers' phrase is its own plural, with its preposition, so + // its grammar travels with it, and the outer sentence places it. + let title = match (sel.len(), app.s.selected_layers().len()) { + (1, _) => element_title(&app.s.doc, e), + (n, 0 | 1) => trn!("{n} element", "{n} elements", n), + (n, l) => trn!("{n} element {on_layers}", "{n} elements {on_layers}", n, on_layers = trn!("on {n} layer", "on {n} layers", l)), + }; + section(ui, "prop_selection", Section::Rule, &title, None, |ui| selection_props(app, ui, e, &sel)); } else { - section(ui, "prop_document", Section::Rule, "Document", None, |ui| document_props(app, ui)); + section(ui, "prop_document", Section::Rule, tr!("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)); + section(ui, "prop_frame", Section::Rule, tr!("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) { +/// A symbol type's name, as the Properties panel shows it. +fn symbol_kind_label(kind: SymbolKind) -> &'static str { + match kind { + SymbolKind::Graphic => tr!("Graphic"), + SymbolKind::MovieClip => tr!("Movie clip"), + SymbolKind::Button => tr!("Button"), + } +} + +/// [`anicraft_engine::element_label`] in the interface language: the selection's title (the +/// same English; `i18n::tests` compares them). +pub(crate) fn element_title(doc: &anicraft_engine::doc::Document, e: &anicraft_engine::doc::Element) -> String { + let kind = match &e.kind { + ElementKind::Shape(_) => tr!("Shape").to_string(), + ElementKind::Symbol { symbol, .. } => match doc.symbol(*symbol) { + Some(s) => match s.kind { + SymbolKind::Graphic => tr!("Graphic: {name}", name = s.name), + SymbolKind::MovieClip => tr!("Movie clip: {name}", name = s.name), + SymbolKind::Button => tr!("Button: {name}", name = s.name), + }, + None => tr!("Graphic: missing").to_string(), + }, + ElementKind::Camera => tr!("Camera").to_string(), + ElementKind::Text(t) => { + let first: String = t.text.lines().next().unwrap_or("").chars().take(24).collect(); + let more = if t.text.chars().count() > first.chars().count() { "…" } else { "" }; + tr!("Text: {text}", text = format!("{first}{more}")) + } + }; + if e.name.is_empty() { kind } else { tr!("{name} ({kind})", name = e.name, kind = kind) } +} + +/// "mixed" after a value that differs across the selection (the field shows the first one's). +fn mixed(ui: &mut egui::Ui, differs: bool) { + if differs { + ui.label(text(Type::Caption, tr!("mixed")).color(T.text_faint)).on_hover_text(tr!("The selected elements differ here; it shows the first one's. A change applies to all of them")); + } +} + +/// The selection's properties: `e` is the first selected element, `all` the whole selection. +fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, all: &[std::sync::Arc]) { + let many = all.len() > 1; + let differs = |f: &dyn Fn(&anicraft_engine::doc::Element) -> f32| all.iter().any(|x| (f(x) - f(e)).abs() > 1e-4); if let ElementKind::Symbol { symbol, events, .. } = &e.kind && app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic) { @@ -374,30 +468,51 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E { 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)).named("Position X"); - let b = ui.add(egui::DragValue::new(&mut y).prefix("Y ").speed(1.0).max_decimals(1)).named("Position Y"); + if many { + // Several elements: where their combined box is, as in Animate; a change moves them + // all together. + let b = app.s.selection_bounds(); + let (ox, oy) = (b.min.x, b.min.y); + let (mut bx, mut by) = (ox, oy); + row(ui, tr!("Position"), |ui| { + let a = ui.add(egui::DragValue::new(&mut bx).prefix("X ").speed(1.0).max_decimals(1)).named(tr!("Position X")); + let c = ui.add(egui::DragValue::new(&mut by).prefix("Y ").speed(1.0).max_decimals(1)).named(tr!("Position Y")); + if (a.changed() || c.changed()) && !b.is_empty() { + live(app, tr_noop!("Move"), "element.translate", json!({"dx": bx - ox, "dy": by - oy})); + } + }); + } else { + row(ui, tr!("Position"), |ui| { + let a = ui.add(egui::DragValue::new(&mut x).prefix("X ").speed(1.0).max_decimals(1)).named(tr!("Position X")); + let b = ui.add(egui::DragValue::new(&mut y).prefix("Y ").speed(1.0).max_decimals(1)).named(tr!("Position Y")); + if a.changed() || b.changed() { + live(app, tr_noop!("Move"), "element.set_transform", json!({"x": x, "y": y})); + } + }); + } + let scale_mixed = many && (differs(&|x| x.transform.decompose().sx) || differs(&|x| x.transform.decompose().sy)); + row(ui, tr!("Scale"), |ui| { + let a = ui.add(egui::DragValue::new(&mut sx).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale width")); + let b = ui.add(egui::DragValue::new(&mut sy).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale height")); if a.changed() || b.changed() { - live(app, "Move", "element.set_transform", json!({"x": x, "y": y})); + live(app, tr_noop!("Scale"), "element.set_transform", json!({"sx": sx / 100.0, "sy": sy / 100.0})); } + mixed(ui, scale_mixed); }); - 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)).named("Scale width"); - let b = ui.add(egui::DragValue::new(&mut sy).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named("Scale height"); - 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)).named("Rotation").changed() { - live(app, "Rotate", "element.set_transform", json!({"rotation": rot})); + let rot_mixed = many && differs(&|x| x.transform.decompose().rotation); + row(ui, tr!("Rotation"), |ui| { + if ui.add(egui::DragValue::new(&mut rot).suffix("°").speed(0.5).range(-360.0..=360.0).max_decimals(1)).named(tr!("Rotation")).changed() { + live(app, tr_noop!("Rotate"), "element.set_transform", json!({"rotation": rot})); } + mixed(ui, rot_mixed); }); let mut alpha = e.color.alpha * 100.0; - row(ui, "Alpha", |ui| { - if a11y::slider(ui, &mut alpha, 0.0..=100.0, "Alpha", a11y::SliderLook { suffix: " %", max_decimals: Some(0), ..Default::default() }).changed() { - live(app, "Alpha", "element.set_alpha", json!({"alpha": alpha / 100.0})); + let alpha_mixed = many && differs(&|x| x.color.alpha); + row(ui, tr!("Alpha"), |ui| { + if a11y::slider(ui, &mut alpha, 0.0..=100.0, tr!("Alpha"), a11y::SliderLook { suffix: " %", max_decimals: Some(0), ..Default::default() }).changed() { + live(app, tr_noop!("Alpha"), "element.set_alpha", json!({"alpha": alpha / 100.0})); } + mixed(ui, alpha_mixed); }); // Blending and filters, on movie clips and buttons as in Animate. if let ElementKind::Symbol { symbol, filters, .. } = &e.kind @@ -409,16 +524,16 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E && app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic) { let current = *blend; - row_prose(ui, "Blending", |ui| { - egui::ComboBox::from_id_salt("prop_blend").selected_text(current.label()).show_ui(ui, |ui| { + row_prose(ui, tr!("Blending"), |ui| { + egui::ComboBox::from_id_salt("prop_blend").selected_text(crate::i18n::t(current.label())).show_ui(ui, |ui| { for m in anicraft_engine::doc::BlendMode::ALL { - if ui.selectable_label(m == current, m.label()).clicked() && m != current { + if ui.selectable_label(m == current, crate::i18n::t(m.label())).clicked() && m != current { app.run("element.set_blend", json!({"mode": m.key()})); } } }) .response - .set_name("Blending"); + .set_name(tr!("Blending")); }); } if let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = &e.kind @@ -428,43 +543,38 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E let (kind, frames) = sym; ui.add_space(4.0); // How the instance plays: the symbol's type, and a graphic's looping. - row_prose(ui, "Type", |ui| { - let label = |k: SymbolKind| match k { - SymbolKind::Graphic => "Graphic", - SymbolKind::MovieClip => "Movie clip", - SymbolKind::Button => "Button", - }; - egui::ComboBox::from_id_salt("prop_symkind").width(150.0).selected_text(label(kind)).show_ui(ui, |ui| { + row_prose(ui, tr!("Type"), |ui| { + egui::ComboBox::from_id_salt("prop_symkind").width(150.0).selected_text(symbol_kind_label(kind)).show_ui(ui, |ui| { for (k, id, tip) in [ - (SymbolKind::Graphic, "graphic", "Keeps step with the timeline it is on (looping options below)"), - (SymbolKind::MovieClip, "movie_clip", "Plays its own timeline on a loop, from when it appears"), - (SymbolKind::Button, "button", "Shows its Up frame"), + (SymbolKind::Graphic, "graphic", tr!("Keeps step with the timeline it is on (looping options below)")), + (SymbolKind::MovieClip, "movie_clip", tr!("Plays its own timeline on a loop, from when it appears")), + (SymbolKind::Button, "button", tr!("Shows its Up frame")), ] { - if ui.selectable_label(kind == k, label(k)).on_hover_text(tip).clicked() && kind != k { + if ui.selectable_label(kind == k, symbol_kind_label(k)).on_hover_text(tip).clicked() && kind != k { app.run("symbol.set_kind", json!({"symbol": symbol.0, "kind": id})); } } }) .response - .set_name("Symbol type"); + .set_name(tr!("Symbol type")); }); // The class scripts know the symbol by (kept, not run; ADR 0013), in documents // that use scripts. let linkage = app.s.doc.symbol(*symbol).and_then(|s| s.linkage.clone()); if linkage.is_some() || crate::actions_panel::scripted(&app.s.doc) { let (class, base) = linkage.map_or((String::new(), String::new()), |l| (l.class, l.base)); - let hint = if base.is_empty() { "The class scripts create this symbol by (its linkage). Kept with the document; scripts don't run yet".to_string() } else { format!("The class scripts create this symbol by (its linkage), extending {base}. Kept with the document; scripts don't run yet") }; - row_prose(ui, "Class", |ui| { - if let Some(v) = crate::actions_panel::class_field(ui, "prop_symclass", &class, "Linkage class", &hint) { + let hint = if base.is_empty() { tr!("The class scripts create this symbol by (its linkage). Kept with the document; scripts don't run yet").to_string() } else { tr!("The class scripts create this symbol by (its linkage), extending {base}. Kept with the document; scripts don't run yet", base = base) }; + row_prose(ui, tr!("Class"), |ui| { + if let Some(v) = crate::actions_panel::class_field(ui, "prop_symclass", &class, tr!("Linkage class"), &hint) { let base = if v.is_empty() { String::new() } else { base.clone() }; app.run("script.set_class", json!({"symbol": symbol.0, "class": v, "base": base})); } }); } if kind == SymbolKind::Graphic { - let names = [(LoopMode::Loop, "loop", "Loop"), (LoopMode::PlayOnce, "play_once", "Play once"), (LoopMode::SingleFrame, "single_frame", "Single frame")]; - let current = names.iter().find(|(m, _, _)| m == loop_mode).map_or("Loop", |(_, _, l)| l); - row_prose(ui, "Looping", |ui| { + let names = [(LoopMode::Loop, "loop", tr!("Loop")), (LoopMode::PlayOnce, "play_once", tr!("Play once")), (LoopMode::SingleFrame, "single_frame", tr!("Single frame"))]; + let current = names.iter().find(|(m, _, _)| m == loop_mode).map_or(tr!("Loop"), |(_, _, l)| l); + row_prose(ui, tr!("Looping"), |ui| { egui::ComboBox::from_id_salt("prop_loop").width(150.0).selected_text(current).show_ui(ui, |ui| { for (m, id, l) in names { if ui.selectable_label(m == *loop_mode, l).clicked() && m != *loop_mode { @@ -473,18 +583,18 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E } }) .response - .set_name("Looping"); + .set_name(tr!("Looping")); }); let mut first = first_frame + 1; - row(ui, "First frame", |ui| { - let r = ui.add(egui::DragValue::new(&mut first).range(1..=frames.max(1)).speed(0.2)).named("First frame"); + row(ui, tr!("First frame"), |ui| { + let r = ui.add(egui::DragValue::new(&mut first).range(1..=frames.max(1)).speed(0.2)).named(tr!("First frame")); if r.changed() { - live(app, "First frame", "element.set_loop", json!({"first_frame": first.saturating_sub(1)})); + live(app, tr_noop!("First frame"), "element.set_loop", json!({"first_frame": first.saturating_sub(1)})); } - ui.label(text(Type::Caption, format!("of {frames}"))); + ui.label(text(Type::Caption, tr!("of {frames}", frames = frames))); }); } else if kind == SymbolKind::MovieClip { - ui.label(text(Type::Caption, format!("Plays its {frames}-frame timeline on a loop from when it appears."))); + ui.label(text(Type::Caption, trn!("Plays its {n}-frame timeline on a loop from when it appears.", "Plays its {n}-frame timeline on a loop from when it appears.", frames))); } } if let ElementKind::Text(t) = &e.kind { @@ -494,8 +604,8 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if let Some((label, p)) = text_style_rows(app, ui, &mut st, Some(&mut width)) { live(app, label, "text.edit", p); } - row_prose(ui, "Text", |ui| { - if ui.button("Edit Text").on_hover_text("Type on the stage (or double-click the text)").clicked() { + row_prose(ui, tr!("Text"), |ui| { + if ui.button(tr!("Edit Text")).on_hover_text(tr!("Type on the stage (or double-click the text)")).clicked() { let at = e.transform.apply(anicraft_engine::geom::Vec2::ZERO); app.text_edit = Some(crate::app::TextEditing { at: pos2(at.x, at.y), element: Some(e.id), text: t.text.clone(), original: t.text.clone(), focus: true }); } @@ -504,32 +614,42 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if let ElementKind::Shape(sh) = &e.kind { ui.add_space(4.0); let fill = sh.fill.as_ref().map(Paint::primary_color); - row(ui, "Fill", |ui| { + // Mixed: the selected shapes' fills, or lines, are not all alike. + let shapes: Vec<&anicraft_engine::doc::Shape> = all.iter().filter_map(|x| match &x.kind { + ElementKind::Shape(s) => Some(s), + _ => None, + }).collect(); + let fill_mixed = shapes.iter().any(|s| s.fill.as_ref().map(Paint::primary_color) != fill); + let line = |s: &anicraft_engine::doc::Shape| s.stroke.as_ref().map(|st| (st.color, st.width.to_bits())); + let stroke_mixed = shapes.iter().any(|s| line(s) != line(sh)); + row(ui, tr!("Fill"), |ui| { let is_grad = matches!(sh.fill, Some(Paint::Linear { .. } | Paint::Radial { .. })); let mut c = rgb(fill.unwrap_or(Rgba::WHITE)); - if ui.color_edit_button_srgb(&mut c).named("Fill colour").changed() { - live(app, "Fill colour", "element.set_fill", json!({"color": hex(c)})); + if ui.color_edit_button_srgb(&mut c).named(tr!("Fill colour")).changed() { + live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": hex(c)})); } let mut on = fill.is_some(); - if crate::theme::checkbox(ui, &mut on, "").named("Fill").on_hover_text("Fill on/off").changed() { + if crate::theme::checkbox(ui, &mut on, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off")).changed() { app.run("element.set_fill", if on { json!({"color": hex(c)}) } else { json!({"color": null}) }); } if let Some(Paint::Bitmap { bitmap, .. }) = &sh.fill { - let name = app.s.doc.bitmap(*bitmap).map_or_else(|| "missing bitmap".to_string(), |b| format!("{} · {}×{}", b.name, b.width, b.height)); + let name = app.s.doc.bitmap(*bitmap).map_or_else(|| tr!("missing bitmap").to_string(), |b| format!("{} · {}×{}", b.name, b.width, b.height)); ui.label(text(Type::Caption, name)); } else if is_grad { - ui.label(text(Type::Caption, "gradient")); + ui.label(text(Type::Caption, tr!("gradient"))); } + mixed(ui, fill_mixed); }); let mut sc = rgb(sh.stroke.as_ref().map_or(app.s.style.stroke, |s| s.color)); let mut sw = sh.stroke.as_ref().map_or(0.0, |s| s.width); - row(ui, "Stroke", |ui| { - if ui.color_edit_button_srgb(&mut sc).named("Stroke colour").changed() { - live(app, "Stroke colour", "element.set_stroke", json!({"color": hex(sc)})); + row(ui, tr!("Stroke"), |ui| { + if ui.color_edit_button_srgb(&mut sc).named(tr!("Stroke colour")).changed() { + live(app, tr_noop!("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)).named("Stroke width").changed() { - live(app, "Stroke width", "element.set_stroke", json!({"width": sw})); + if ui.add(egui::DragValue::new(&mut sw).suffix(" px").speed(0.1).range(0.0..=200.0).max_decimals(1)).named(tr!("Stroke width")).changed() { + live(app, tr_noop!("Stroke width"), "element.set_stroke", json!({"width": sw})); } + mixed(ui, stroke_mixed); }); if let Some(st) = &sh.stroke { // The width profile, as Animate's Width menu: built-ins with a picture of each. @@ -537,11 +657,20 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if let Some(pick) = profile_picker(ui, ProfileRow::Selection, current.as_ref()) { app.run("stroke.set_profile", json!({"profile": pick.key()})); } + // Style, caps and joins (ADR 0046). + let style_mixed = shapes.iter().any(|s| s.stroke.as_ref().map(|x| &x.style) != Some(&st.style)); + if let Some(edit) = line_style_rows(ui, ProfileRow::Selection, &st.style, style_mixed) { + if edit.drag { + live(app, edit.label, "stroke.set_style", edit.params); + } else { + app.run("stroke.set_style", edit.params); + } + } } } 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")] { + for (label, id) in [(tr!("Convert to Symbol"), "modify.convert_to_symbol"), (tr!("Break Apart"), "modify.break_apart"), (tr!("Duplicate"), "edit.duplicate"), (tr!("Delete"), "edit.delete")] { if ui.button(label).clicked() { app.invoke(id); } @@ -554,17 +683,17 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E /// the top of Animate's Properties. fn instance_rows(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, events: &[anicraft_engine::doc::EventHandler]) { let mut name = e.name.clone(); - row_prose(ui, "Instance", |ui| { - let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(150.0).hint_text("instance name")).named("Instance name"); - if r.on_hover_text("The name actions use to address it (letters, digits and _)").changed() { - live(app, "Instance name", "instance.set_name", json!({"element": e.id.0, "name": name})); + row_prose(ui, tr!("Instance"), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(150.0).hint_text(tr!("instance name"))).named(tr!("Instance name")); + if r.on_hover_text(tr!("The name actions use to address it (letters, digits and _)")).changed() { + live(app, tr_noop!("Instance name"), "instance.set_name", json!({"element": e.id.0, "name": name})); } }); let key = app.keymap.primary("view.actions").map(crate::platform::shortcut_label).unwrap_or_default(); - row_prose(ui, "Events", |ui| { - let what = if events.is_empty() { "None".to_string() } else { events.iter().map(|h| h.event.label()).collect::>().join(", ") }; + row_prose(ui, tr!("Events"), |ui| { + let what = if events.is_empty() { tr!("None").to_string() } else { events.iter().map(|h| crate::i18n::t(h.event.label())).collect::>().join(", ") }; ui.label(text(Type::Body, what).color(if events.is_empty() { T.text_faint } else { T.text })); - if ui.small_button("Actions…").on_hover_text(format!("Edit what it does on clicks and the pointer ({key})")).clicked() { + if ui.small_button(tr!("Actions…")).on_hover_text(tr!("Edit what it does on clicks and the pointer ({key})", key = key)).clicked() { crate::actions_panel::open(app, crate::actions_panel::Tab::Instance); } }); @@ -579,44 +708,44 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc // As the renderer sees them (a file may hold values or ramps a command would refuse). let mut list: Vec = current.iter().map(Filter::sanitized).collect(); let mut changed: Option<&'static str> = None; - row_prose(ui, "Filters", |ui| { - egui::ComboBox::from_id_salt("add_filter").selected_text(if list.is_empty() { "None" } else { "Add filter" }).show_ui(ui, |ui| { + row_prose(ui, tr!("Filters"), |ui| { + egui::ComboBox::from_id_salt("add_filter").selected_text(if list.is_empty() { tr!("None") } else { tr!("Add filter") }).show_ui(ui, |ui| { for (kind, label) in Filter::KINDS { - if ui.selectable_label(false, label).clicked() + if ui.selectable_label(false, crate::i18n::t(label)).clicked() && let Some(f) = Filter::new(kind) { list.push(f); - changed = Some("Add filter"); + changed = Some(tr_noop!("Add filter")); } } }) .response - .set_name("Add filter"); + .set_name(tr!("Add filter")); }); - let quality_names = ["Low", "Medium", "High"]; + let quality_names = [tr!("Low"), tr!("Medium"), tr!("High")]; let mut remove = None; for (i, f) in list.iter_mut().enumerate() { // Screen readers hear which filter a value belongs to: "Drop Shadow blur X". - let fname = f.label(); + let fname = crate::i18n::t(f.label()); ui.push_id(("filter", i), |ui| { row_prose(ui, fname, |ui| { - if ui.small_button("Remove").named(&format!("Remove {fname}")).on_hover_text("Remove this filter").clicked() { + if ui.small_button(tr!("Remove")).named(&tr!("Remove {filter}", filter = fname)).on_hover_text(tr!("Remove this filter")).clicked() { remove = Some(i); } }); let blur_rows = |ui: &mut egui::Ui, bx: &mut f32, by: &mut f32, quality: &mut u8, changed: &mut Option<&'static str>| { - row(ui, "Blur", |ui| { - let a = ui.add(egui::DragValue::new(bx).prefix("X ").suffix(" px").speed(0.25).range(0.0..=255.0).max_decimals(1)).named(&format!("{fname} blur X")); - let b = ui.add(egui::DragValue::new(by).prefix("Y ").suffix(" px").speed(0.25).range(0.0..=255.0).max_decimals(1)).named(&format!("{fname} blur Y")); + row(ui, tr!("Blur"), |ui| { + let a = ui.add(egui::DragValue::new(bx).prefix("X ").suffix(" px").speed(0.25).range(0.0..=255.0).max_decimals(1)).named(&tr!("{filter} blur X", filter = fname)); + let b = ui.add(egui::DragValue::new(by).prefix("Y ").suffix(" px").speed(0.25).range(0.0..=255.0).max_decimals(1)).named(&tr!("{filter} blur Y", filter = fname)); if a.changed() || b.changed() { - *changed = Some("Filter blur"); + *changed = Some(tr_noop!("Filter blur")); } }); - row_prose(ui, "Quality", |ui| { + row_prose(ui, tr!("Quality"), |ui| { for (q, name) in quality_names.iter().enumerate() { - if ui.selectable_label(usize::from(*quality) == q + 1, *name).named(&format!("{fname} quality {name}")).clicked() { + if ui.selectable_label(usize::from(*quality) == q + 1, *name).named(&tr!("{filter} quality {quality}", filter = fname, quality = name)).clicked() { *quality = q as u8 + 1; - *changed = Some("Filter quality"); + *changed = Some(tr_noop!("Filter quality")); } } }); @@ -627,11 +756,11 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc Filter::DropShadow { blur_x, blur_y, strength, quality, angle, distance, color, inner, knockout, hide_object } => { blur_rows(ui, blur_x, blur_y, quality, &mut changed); shadow_rows(ui, fname, strength, color, &mut changed); - offset_row(ui, fname, angle, distance, "Shadow offset", &mut changed); - row_prose(ui, "Options", |ui| { - for (v, label) in [(inner, "Inner"), (knockout, "Knockout"), (hide_object, "Hide object")] { + offset_row(ui, fname, angle, distance, tr_noop!("Shadow offset"), &mut changed); + row_prose(ui, tr!("Options"), |ui| { + for (v, label) in [(inner, tr!("Inner")), (knockout, tr!("Knockout")), (hide_object, tr!("Hide object"))] { if crate::theme::checkbox(ui, v, label).changed() { - changed = Some("Shadow options"); + changed = Some(tr_noop!("Shadow options")); } } }); @@ -639,10 +768,10 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc Filter::Glow { blur_x, blur_y, strength, quality, color, inner, knockout } => { blur_rows(ui, blur_x, blur_y, quality, &mut changed); shadow_rows(ui, fname, strength, color, &mut changed); - row_prose(ui, "Options", |ui| { - for (v, label) in [(inner, "Inner"), (knockout, "Knockout")] { + row_prose(ui, tr!("Options"), |ui| { + for (v, label) in [(inner, tr!("Inner")), (knockout, tr!("Knockout"))] { if crate::theme::checkbox(ui, v, label).changed() { - changed = Some("Glow options"); + changed = Some(tr_noop!("Glow options")); } } }); @@ -650,15 +779,19 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc Filter::Bevel { blur_x, blur_y, strength, quality, angle, distance, shadow_color, highlight_color, side, knockout } => { blur_rows(ui, blur_x, blur_y, quality, &mut changed); strength_row(ui, fname, strength, &mut changed); - row_prose(ui, "Colours", |ui| { - for (c, label, undo) in [(shadow_color, "Shadow", "Bevel shadow colour"), (highlight_color, "Highlight", "Bevel highlight colour")] { + row_prose(ui, tr!("Colours"), |ui| { + let colours = [ + (shadow_color, tr!("Shadow"), tr!("{filter} shadow colour", filter = fname), tr_noop!("Bevel shadow colour")), + (highlight_color, tr!("Highlight"), tr!("{filter} highlight colour", filter = fname), tr_noop!("Bevel highlight colour")), + ]; + for (c, label, name, undo) in colours { ui.label(label); - if alpha_swatch(ui, c, &format!("{fname} {} colour", label.to_lowercase())) { + if alpha_swatch(ui, c, &name) { changed = Some(undo); } } }); - offset_row(ui, fname, angle, distance, "Bevel offset", &mut changed); + offset_row(ui, fname, angle, distance, tr_noop!("Bevel offset"), &mut changed); side_rows(ui, fname, side, knockout, &mut changed); } Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout } | Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout } => { @@ -666,14 +799,14 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc ramp_editor(ui, fname, stops, pin, &mut changed); blur_rows(ui, blur_x, blur_y, quality, &mut changed); strength_row(ui, fname, strength, &mut changed); - offset_row(ui, fname, angle, distance, "Filter offset", &mut changed); + offset_row(ui, fname, angle, distance, tr_noop!("Filter offset"), &mut changed); side_rows(ui, fname, side, knockout, &mut changed); } Filter::AdjustColor { brightness, contrast, saturation, hue } => { - for (v, label, range) in [(brightness, "Brightness", 100.0), (contrast, "Contrast", 100.0), (saturation, "Saturation", 100.0), (hue, "Hue", 180.0)] { + for (v, label, range) in [(brightness, tr!("Brightness"), 100.0), (contrast, tr!("Contrast"), 100.0), (saturation, tr!("Saturation"), 100.0), (hue, tr!("Hue"), 180.0)] { row(ui, label, |ui| { if a11y::slider(ui, v, -range..=range, label, a11y::SliderLook { max_decimals: Some(0), ..Default::default() }).changed() { - changed = Some("Adjust colour"); + changed = Some(tr_noop!("Adjust colour")); } }); } @@ -683,7 +816,7 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc } if let Some(i) = remove { list.remove(i); - changed = Some("Remove filter"); + changed = Some(tr_noop!("Remove filter")); } if let Some(label) = changed && let Ok(v) = serde_json::to_value(&list) @@ -694,39 +827,39 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc /// Strength and colour rows of a drop shadow or glow. fn shadow_rows(ui: &mut egui::Ui, fname: &str, strength: &mut f32, color: &mut Rgba, changed: &mut Option<&'static str>) { - row(ui, "Strength", |ui| { + row(ui, tr!("Strength"), |ui| { let mut pct = *strength * 100.0; - if ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(1.0).range(0.0..=1000.0).max_decimals(0)).named(&format!("{fname} strength")).changed() { + if ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(1.0).range(0.0..=1000.0).max_decimals(0)).named(&tr!("{filter} strength", filter = fname)).changed() { *strength = pct / 100.0; - *changed = Some("Filter strength"); + *changed = Some(tr_noop!("Filter strength")); } let mut c = rgb(*color); - if ui.color_edit_button_srgb(&mut c).named(&format!("{fname} colour")).on_hover_text("Colour").changed() { + if ui.color_edit_button_srgb(&mut c).named(&tr!("{filter} colour", filter = fname)).on_hover_text(tr!("Colour")).changed() { *color = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, color.a); - *changed = Some("Filter colour"); + *changed = Some(tr_noop!("Filter colour")); } }); } /// The Strength row of a bevel or gradient filter. fn strength_row(ui: &mut egui::Ui, fname: &str, strength: &mut f32, changed: &mut Option<&'static str>) { - row(ui, "Strength", |ui| { + row(ui, tr!("Strength"), |ui| { let mut pct = *strength * 100.0; - if ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(1.0).range(0.0..=1000.0).max_decimals(0)).named(&format!("{fname} strength")).changed() { + if ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(1.0).range(0.0..=1000.0).max_decimals(0)).named(&tr!("{filter} strength", filter = fname)).changed() { *strength = pct / 100.0; - *changed = Some("Filter strength"); + *changed = Some(tr_noop!("Filter strength")); } }); } /// Angle and distance of a shadow, bevel or gradient filter. fn offset_row(ui: &mut egui::Ui, fname: &str, angle: &mut f32, distance: &mut f32, undo: &'static str, changed: &mut Option<&'static str>) { - row(ui, "Offset", |ui| { + row(ui, tr!("Offset"), |ui| { let a = ui - .add(egui::DragValue::new(angle).prefix("Angle ").suffix("°").speed(1.0).range(0.0..=360.0).max_decimals(0)) - .named(&format!("{fname} angle")) - .on_hover_text("The direction the shadow falls (the light comes from the opposite side)"); - let b = ui.add(egui::DragValue::new(distance).prefix("Distance ").suffix(" px").speed(0.25).range(-1000.0..=1000.0).max_decimals(1)).named(&format!("{fname} distance")); + .add(egui::DragValue::new(angle).prefix(format!("{} ", tr!("Angle"))).suffix("°").speed(1.0).range(0.0..=360.0).max_decimals(0)) + .named(&tr!("{filter} angle", filter = fname)) + .on_hover_text(tr!("The direction the shadow falls (the light comes from the opposite side)")); + let b = ui.add(egui::DragValue::new(distance).prefix(format!("{} ", tr!("Distance"))).suffix(" px").speed(0.25).range(-1000.0..=1000.0).max_decimals(1)).named(&tr!("{filter} distance", filter = fname)); if a.changed() || b.changed() { *changed = Some(undo); } @@ -736,17 +869,18 @@ fn offset_row(ui: &mut egui::Ui, fname: &str, angle: &mut f32, distance: &mut f3 /// The Type (inner, outer, full) and Knockout rows of a bevel or gradient filter. fn side_rows(ui: &mut egui::Ui, fname: &str, side: &mut anicraft_engine::doc::FilterSide, knockout: &mut bool, changed: &mut Option<&'static str>) { use anicraft_engine::doc::FilterSide; - row_prose(ui, "Type", |ui| { - for (v, tip) in [(FilterSide::Inner, "Inside the artwork's edge"), (FilterSide::Outer, "Outside the artwork's edge"), (FilterSide::Full, "Inside and outside the edge")] { - if ui.selectable_label(*side == v, v.label()).named(&format!("{fname} type {}", v.label())).on_hover_text(tip).clicked() && *side != v { + row_prose(ui, tr!("Type"), |ui| { + for (v, tip) in [(FilterSide::Inner, tr!("Inside the artwork's edge")), (FilterSide::Outer, tr!("Outside the artwork's edge")), (FilterSide::Full, tr!("Inside and outside the edge"))] { + let label = crate::i18n::t(v.label()); + if ui.selectable_label(*side == v, label).named(&tr!("{filter} type {kind}", filter = fname, kind = label)).on_hover_text(tip).clicked() && *side != v { *side = v; - *changed = Some("Filter type"); + *changed = Some(tr_noop!("Filter type")); } } }); - row_prose(ui, "Options", |ui| { - if crate::theme::checkbox(ui, knockout, "Knockout").named(&format!("{fname} knockout")).on_hover_text("Show only the effect, not the artwork").changed() { - *changed = Some("Filter options"); + row_prose(ui, tr!("Options"), |ui| { + if crate::theme::checkbox(ui, knockout, tr!("Knockout")).named(&tr!("{filter} knockout", filter = fname)).on_hover_text(tr!("Show only the effect, not the artwork")).changed() { + *changed = Some(tr_noop!("Filter options")); } }); } @@ -786,12 +920,12 @@ fn ramp_editor(ui: &mut egui::Ui, fname: &str, stops: &mut Vec t).unwrap_or(stops.len()); stops.insert(i, new); sel = i; - *changed = Some("Add colour stop"); + *changed = Some(tr_noop!("Add colour stop")); } }); }); @@ -866,25 +1001,25 @@ fn ramp_editor(ui: &mut egui::Ui, fname: &str, stops: &mut Vec 2, egui::Button::new("Remove").small()).named(&format!("Remove {fname} colour stop")).on_hover_text("Remove this colour stop").clicked() { + if ui.add_enabled(!pinned && count > 2, egui::Button::new(tr!("Remove")).small()).named(&tr!("Remove {filter} colour stop", filter = fname)).on_hover_text(tr!("Remove this colour stop")).clicked() { remove = true; } }); @@ -892,7 +1027,7 @@ fn ramp_editor(ui: &mut egui::Ui, fname: &str, stops: &mut Vec = None; - row_prose(ui, "Font", |ui| { + row_prose(ui, tr!("Font"), |ui| { let shown = if st.font.is_empty() { anicraft_engine::text::Fonts::get().resolve("").unwrap_or_default() } else { st.font.clone() }; egui::ComboBox::from_id_salt("text_font").selected_text(shown.clone()).width(ui.available_width().min(220.0)).height(320.0).show_ui(ui, |ui| { if families.is_empty() { - ui.label(text(Type::Caption, "No fonts found on this computer")); + ui.label(text(Type::Caption, tr!("No fonts found on this computer"))); } for f in &families { if ui.selectable_label(*f == shown, f).clicked() { st.font = f.clone(); - out = Some(("Font", json!({"font": f}))); + out = Some((tr_noop!("Font"), json!({"font": f}))); } } }) .response - .set_name("Font"); + .set_name(tr!("Font")); }); - row(ui, "Size", |ui| { - if ui.add(egui::DragValue::new(&mut st.size).suffix(" px").speed(0.25).range(1.0..=2000.0).max_decimals(1)).named("Font size").changed() { - out = Some(("Font size", json!({"size": st.size}))); + row(ui, tr!("Size"), |ui| { + if ui.add(egui::DragValue::new(&mut st.size).suffix(" px").speed(0.25).range(1.0..=2000.0).max_decimals(1)).named(tr!("Font size")).changed() { + out = Some((tr_noop!("Font size"), json!({"size": st.size}))); } let mut c = rgb(st.color); - if ui.color_edit_button_srgb(&mut c).named("Text colour").on_hover_text("Text colour").changed() { + if ui.color_edit_button_srgb(&mut c).named(tr!("Text colour")).on_hover_text(tr!("Text colour")).changed() { st.color = Rgba::hex(u32::from(c[0]) << 16 | u32::from(c[1]) << 8 | u32::from(c[2])); - out = Some(("Text colour", json!({"color": hex(c)}))); + out = Some((tr_noop!("Text colour"), json!({"color": hex(c)}))); } }); - row_prose(ui, "Style", |ui| { - if ui.selectable_label(st.bold, text(Type::Body, "B").strong()).named("Bold").on_hover_text("Bold").clicked() { + row_prose(ui, tr!("Style"), |ui| { + // The letters on the two buttons are the usual bold and italic marks. + if ui.selectable_label(st.bold, text(Type::Body, "B").strong()).named(tr!("Bold")).on_hover_text(tr!("Bold")).clicked() { st.bold = !st.bold; - out = Some(("Bold", json!({"bold": st.bold}))); + out = Some((tr_noop!("Bold"), json!({"bold": st.bold}))); } - if ui.selectable_label(st.italic, text(Type::Body, "I").italics()).named("Italic").on_hover_text("Italic").clicked() { + if ui.selectable_label(st.italic, text(Type::Body, "I").italics()).named(tr!("Italic")).on_hover_text(tr!("Italic")).clicked() { st.italic = !st.italic; - out = Some(("Italic", json!({"italic": st.italic}))); + out = Some((tr_noop!("Italic"), json!({"italic": st.italic}))); } ui.separator(); - for (a, label, key) in [(TextAlign::Left, "Left", "left"), (TextAlign::Center, "Centre", "center"), (TextAlign::Right, "Right", "right")] { - let name = format!("Align {}", label.to_lowercase()); - if ui.selectable_label(st.align == a, label).named(&name).on_hover_text(name.as_str()).clicked() { + for (a, label, name, key) in [(TextAlign::Left, tr!("Left"), tr!("Align left"), "left"), (TextAlign::Center, tr!("Centre"), tr!("Align centre"), "center"), (TextAlign::Right, tr!("Right"), tr!("Align right"), "right")] { + if ui.selectable_label(st.align == a, label).named(name).on_hover_text(name).clicked() { st.align = a; - out = Some(("Text alignment", json!({"align": key}))); + out = Some((tr_noop!("Text alignment"), json!({"align": key}))); } } }); - row(ui, "Spacing", |ui| { - if ui.add(egui::DragValue::new(&mut st.letter_spacing).prefix("Letters ").suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named("Letter spacing").changed() { - out = Some(("Letter spacing", json!({"letter_spacing": st.letter_spacing}))); + row(ui, tr!("Spacing"), |ui| { + if ui.add(egui::DragValue::new(&mut st.letter_spacing).prefix(format!("{} ", tr!("Letters"))).suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("Letter spacing")).changed() { + out = Some((tr_noop!("Letter spacing"), json!({"letter_spacing": st.letter_spacing}))); } - if ui.add(egui::DragValue::new(&mut st.line_spacing).prefix("Lines ").suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named("Line spacing").changed() { - out = Some(("Line spacing", json!({"line_spacing": st.line_spacing}))); + if ui.add(egui::DragValue::new(&mut st.line_spacing).prefix(format!("{} ", tr!("Lines"))).suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("Line spacing")).changed() { + out = Some((tr_noop!("Line spacing"), json!({"line_spacing": st.line_spacing}))); } }); if let Some(width) = width { - row(ui, "Width", |ui| { + row(ui, tr!("Width"), |ui| { let mut wrap = width.is_some(); - if crate::theme::checkbox(ui, &mut wrap, "Wrap").on_hover_text("Wrap lines at a fixed width; off, each paragraph stays on one line").changed() { + if crate::theme::checkbox(ui, &mut wrap, tr!("Wrap")).on_hover_text(tr!("Wrap lines at a fixed width; off, each paragraph stays on one line")).changed() { *width = wrap.then_some(300.0); - out = Some(("Text width", json!({"width": *width}))); + out = Some((tr_noop!("Text width"), json!({"width": *width}))); } if let Some(w) = width.as_mut() - && ui.add(egui::DragValue::new(w).suffix(" px").speed(1.0).range(1.0..=100_000.0).max_decimals(0)).named("Text width").changed() + && ui.add(egui::DragValue::new(w).suffix(" px").speed(1.0).range(1.0..=100_000.0).max_decimals(0)).named(tr!("Text width")).changed() { - out = Some(("Text width", json!({"width": *w}))); + out = Some((tr_noop!("Text width"), json!({"width": *w}))); } }); } @@ -977,77 +1112,117 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin fn camera_props(app: &mut App, ui: &mut egui::Ui) { let Some(cam) = crate::camera_tool::camera(app) else { return }; let (mut x, mut y) = (cam.center.x, cam.center.y); - row(ui, "Position", |ui| { - let a = ui.add(egui::DragValue::new(&mut x).prefix("x ").suffix(" px").speed(1.0).max_decimals(1)).named("Camera X"); - let b = ui.add(egui::DragValue::new(&mut y).prefix("y ").suffix(" px").speed(1.0).max_decimals(1)).named("Camera Y"); + row(ui, tr!("Position"), |ui| { + let a = ui.add(egui::DragValue::new(&mut x).prefix("x ").suffix(" px").speed(1.0).max_decimals(1)).named(tr!("Camera X")); + let b = ui.add(egui::DragValue::new(&mut y).prefix("y ").suffix(" px").speed(1.0).max_decimals(1)).named(tr!("Camera Y")); if a.changed() || b.changed() { - live(app, "Move Camera", "camera.set", json!({"x": x, "y": y})); + live(app, tr_noop!("Move Camera"), "camera.set", json!({"x": x, "y": y})); } }); let mut zoom = cam.zoom * 100.0; let (lo, hi) = (anicraft_engine::doc::camera::MIN_ZOOM * 100.0, anicraft_engine::doc::camera::MAX_ZOOM * 100.0); - row(ui, "Zoom", |ui| { + row(ui, tr!("Zoom"), |ui| { ui.spacing_mut().slider_width = 96.0; - if a11y::slider(ui, &mut zoom, lo..=hi, "Camera zoom", a11y::SliderLook { suffix: " %", max_decimals: Some(0), logarithmic: true, ..Default::default() }).changed() { - live(app, "Zoom Camera", "camera.set", json!({"zoom": zoom})); + if a11y::slider(ui, &mut zoom, lo..=hi, tr!("Camera zoom"), a11y::SliderLook { suffix: " %", max_decimals: Some(0), logarithmic: true, ..Default::default() }).changed() { + live(app, tr_noop!("Zoom Camera"), "camera.set", json!({"zoom": zoom})); } }); let mut rot = cam.rotation.to_degrees(); - row(ui, "Rotation", |ui| { - if ui.add(egui::DragValue::new(&mut rot).suffix("°").speed(0.5).max_decimals(1)).named("Camera rotation").changed() { - live(app, "Rotate Camera", "camera.set", json!({"rotation": rot})); + row(ui, tr!("Rotation"), |ui| { + if ui.add(egui::DragValue::new(&mut rot).suffix("°").speed(0.5).max_decimals(1)).named(tr!("Camera rotation")).changed() { + live(app, tr_noop!("Rotate Camera"), "camera.set", json!({"rotation": rot})); } }); let mut tint = rgb(cam.tint); let mut amount = cam.tint_amount * 100.0; - row(ui, "Tint", |ui| { - let a = ui.color_edit_button_srgb(&mut tint).named("Camera tint colour"); - let b = ui.add(egui::DragValue::new(&mut amount).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)).named("Camera tint amount"); + row(ui, tr!("Tint"), |ui| { + let a = ui.color_edit_button_srgb(&mut tint).named(tr!("Camera tint colour")); + let b = ui.add(egui::DragValue::new(&mut amount).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)).named(tr!("Camera tint amount")); if a.changed() || b.changed() { - live(app, "Camera Tint", "camera.set", json!({"tint": hex(tint), "tint_amount": amount})); + live(app, tr_noop!("Camera Tint"), "camera.set", json!({"tint": hex(tint), "tint_amount": amount})); } }); ui.horizontal_wrapped(|ui| { let mut on = app.camera_preview; - if crate::theme::checkbox(ui, &mut on, "Preview through camera").on_hover_text("Show the stage as the movie shows it (View › Preview Through Camera)").changed() { + if crate::theme::checkbox(ui, &mut on, tr!("Preview through camera")).on_hover_text(tr!("Show the stage as the movie shows it (View › Preview Through Camera)")).changed() { app.toggle_camera_preview(); } - if ui.button("Reset").named("Reset camera").on_hover_text("Back to the stage as it is: centred, 100 %, no turn, no tint").clicked() { + if ui.button(tr!("Reset")).named(tr!("Reset camera")).on_hover_text(tr!("Back to the stage as it is: centred, 100 %, no turn, no tint")).clicked() { app.run("camera.set", json!({"reset": true})); } }); let hidden = app.s.doc.timeline(app.s.scene).camera_layer().is_some_and(|l| !l.visible); - ui.label(text(Type::Caption, if hidden { "The camera layer is hidden: the movie shows the stage as it is." } else { "The movie shows what the frame on the stage shows. Layer depth (in Frame, per layer) moves far layers less." })); + ui.label(text(Type::Caption, if hidden { tr!("The camera layer is hidden: the movie shows the stage as it is.") } else { tr!("The movie shows what the frame on the stage shows. Layer depth (in Frame, per layer) moves far layers less.") })); +} + +/// The selected bone: its joint angle at the playhead (editing it keys the pose), the joint's +/// limits, the pin, and removal. +fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId) { + let tl = app.s.doc.timeline(app.s.scene); + let Some((layer, bone)) = tl.layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| (l.clone(), b.clone()))) else { return }; + let pose = anicraft_engine::doc::armature::pose_at(&layer, app.s.frame).unwrap_or_default(); + let mut angle = bone.allow(pose.angle(id)).to_degrees(); + row(ui, tr!("Angle"), |ui| { + if ui.add(egui::DragValue::new(&mut angle).suffix("°").speed(0.5).max_decimals(1)).named(tr!("Bone angle")).on_hover_text(tr!("The joint's turn from where the bone was drawn, measured from the bone it hangs from")).changed() { + live(app, tr_noop!("Pose Bone"), "bone.pose", json!({"bone": id.0, "angle": angle})); + } + }); + let mut constrain = bone.limits.is_some(); + let mut pinned = bone.pinned; + ui.horizontal_wrapped(|ui| { + if crate::theme::checkbox(ui, &mut constrain, tr!("Constrain rotation")).on_hover_text(tr!("Limit how far the joint turns, in every pose")).changed() { + app.run("bone.set_limits", json!({"bone": id.0, "constrain": constrain})); + } + if crate::theme::checkbox(ui, &mut pinned, tr!("Pin")).on_hover_text(tr!("A pinned bone, and the bones it hangs from, stay put while you drag the bones below it")).changed() { + app.run("bone.pin", json!({"bone": id.0, "pinned": pinned})); + } + }); + if let Some(l) = bone.limits { + let (mut min, mut max) = (l.min.to_degrees(), l.max.to_degrees()); + row(ui, tr!("Limits"), |ui| { + let a = ui.add(egui::DragValue::new(&mut min).prefix("min ").suffix("°").speed(0.5).range(-360.0..=max).max_decimals(0)).named(tr!("Joint minimum angle")); + let b = ui.add(egui::DragValue::new(&mut max).prefix("max ").suffix("°").speed(0.5).range(min..=360.0).max_decimals(0)).named(tr!("Joint maximum angle")); + if a.changed() || b.changed() { + live(app, tr_noop!("Joint Limits"), "bone.set_limits", json!({"bone": id.0, "min": min, "max": max})); + } + }); + } + ui.horizontal_wrapped(|ui| { + if ui.button(tr!("Remove Bone")).named(tr!("Remove bone")).on_hover_text(tr!("Removes the bone and the bones below it; their instances stay where they are, on a layer of their own")).clicked() { + app.request("bone.remove", json!({"bone": id.0})); + } + }); + ui.label(text(Type::Caption, tr!("Drag bones or instances with the Selection tool to pose; a pose at another frame keys it, and poses tween."))); } 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)).named("Stage width"); - let b = ui.add(egui::DragValue::new(&mut h).suffix(" px").range(1..=8192)).named("Stage height"); + row(ui, tr!("Size"), |ui| { + let a = ui.add(egui::DragValue::new(&mut w).suffix(" px").range(1..=8192)).named(tr!("Stage width")); + let b = ui.add(egui::DragValue::new(&mut h).suffix(" px").range(1..=8192)).named(tr!("Stage height")); if a.changed() || b.changed() { - live(app, "Stage size", "doc.set_stage", json!({"width": w, "height": h})); + live(app, tr_noop!("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)).named("Frame rate").changed() { - live(app, "Frame rate", "doc.set_stage", json!({"fps": fps})); + row(ui, tr!("Frame rate"), |ui| { + if ui.add(egui::DragValue::new(&mut fps).suffix(" fps").speed(0.1).range(1.0..=120.0).max_decimals(2)).named(tr!("Frame rate")).changed() { + live(app, tr_noop!("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).named("Stage colour").changed() { - live(app, "Stage colour", "doc.set_stage", json!({"background": hex(bg)})); + row(ui, tr!("Stage"), |ui| { + if ui.color_edit_button_srgb(&mut bg).named(tr!("Stage colour")).changed() { + live(app, tr_noop!("Stage colour"), "doc.set_stage", json!({"background": hex(bg)})); } - ui.label(text(Type::Data, format!("{} frames", app.s.frame_count())).color(T.text_faint)); + ui.label(text(Type::Data, trn!("{n} frame", "{n} frames", app.s.frame_count())).color(T.text_faint)); }); // The document class, in documents that use scripts (kept, not run; ADR 0013). if crate::actions_panel::scripted(&app.s.doc) { let current = app.s.doc.document_class.clone(); - row_prose(ui, "Class", |ui| { - if let Some(v) = crate::actions_panel::class_field(ui, "prop_docclass", ¤t, "Document class", "The class scripts run the main timeline as (the document class). Kept with the document; scripts don't run yet") { + row_prose(ui, tr!("Class"), |ui| { + if let Some(v) = crate::actions_panel::class_field(ui, "prop_docclass", ¤t, tr!("Document class"), tr!("The class scripts run the main timeline as (the document class). Kept with the document; scripts don't run yet")) { app.run("script.set_class", json!({"class": v})); } }); @@ -1059,19 +1234,18 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L if layer.kind == anicraft_engine::doc::LayerKind::Folder { let tl = app.s.doc.timeline(app.s.scene); let n = tl.layers.iter().position(|l| l.id == layer.id).map_or(0, |i| tl.group_range(i).len().saturating_sub(1)); - let what = if n == 1 { "1 layer".to_string() } else { format!("{n} layers") }; - ui.label(text(Type::Label, format!("Folder · {what}"))); - ui.label(text(Type::Caption, "Folders hold layers, not frames. Hiding or locking the folder hides or locks everything in it; move layers in under it with Up and Down.")); + ui.label(text(Type::Label, trn!("Folder · {n} layer", "Folder · {n} layers", n))); + ui.label(text(Type::Caption, tr!("Folders hold layers, not frames. Hiding or locking the folder hides or locks everything in it; move layers in under it with Up and Down."))); return; } // Layer depth matters once the scene has a camera: deeper layers move less as it pans. if layer.kind != anicraft_engine::doc::LayerKind::Camera && app.s.doc.timeline(app.s.scene).camera_layer().is_some() { let mut depth = layer.depth; let (lo, hi) = (anicraft_engine::doc::camera::MIN_DEPTH, anicraft_engine::doc::camera::MAX_DEPTH); - row(ui, "Depth", |ui| { - let r = ui.add(egui::DragValue::new(&mut depth).suffix(" px").speed(2.0).range(lo..=hi).max_decimals(0)).named("Layer depth"); - if r.on_hover_text("How far behind the stage this layer is: when the camera pans, a deeper layer moves less (parallax). Negative is in front.").changed() { - live(app, "Layer Depth", "layer.set_depth", json!({"depth": depth})); + row(ui, tr!("Depth"), |ui| { + let r = ui.add(egui::DragValue::new(&mut depth).suffix(" px").speed(2.0).range(lo..=hi).max_decimals(0)).named(tr!("Layer depth")); + if r.on_hover_text(tr!("How far behind the stage this layer is: when the camera pans, a deeper layer moves less (parallax). Negative is in front.")).changed() { + live(app, tr_noop!("Layer Depth"), "layer.set_depth", json!({"depth": depth})); } }); } @@ -1079,15 +1253,17 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L 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))); + // One sentence per count: the frames, then the elements, each with its plural. + let frames = trn!("{n} frame", "{n} frames", k.duration); + let elements = trn!("{n} element", "{n} elements", n); + ui.label(text(Type::Label, tr!("Keyframe at {frame} · {frames} · {elements}", frame = k.start + 1, frames = frames, elements = elements))); 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.")); + ui.label(text(Type::Caption, tr!("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)).named("Frame label").changed() { - live(app, "Frame label", "timeline.set_label", json!({"label": label})); + row_prose(ui, tr!("Label"), |ui| { + if ui.add(egui::TextEdit::singleline(&mut label).desired_width(150.0)).named(tr!("Frame label")).changed() { + live(app, tr_noop!("Frame label"), "timeline.set_label", json!({"label": label})); } }); sound_rows(app, ui, k.sound.clone()); @@ -1095,38 +1271,37 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L volume_row(app, ui, layer); } let key = app.keymap.primary("view.actions").map(crate::platform::shortcut_label).unwrap_or_default(); - row_prose(ui, "Actions", |ui| { - let what = k.script.as_ref().map_or_else(|| "None".to_string(), anicraft_engine::doc::FrameScript::describe); + row_prose(ui, tr!("Actions"), |ui| { + let what = k.script.as_ref().map_or_else(|| tr!("None").to_string(), |s| crate::i18n::t_dyn(&s.describe()).into_owned()); let short: String = what.chars().take(36).collect(); let short = if short.len() < what.len() { format!("{short}…") } else { short }; ui.label(text(Type::Body, short).color(if k.script.is_none() { T.text_faint } else { T.text })).on_hover_text(what); - if ui.small_button("Edit…").on_hover_text(format!("What runs when the playhead enters this keyframe ({key})")).clicked() { + if ui.small_button(tr!("Edit…")).on_hover_text(tr!("What runs when the playhead enters this keyframe ({key})", key = key)).clicked() { app.actions.symbol = None; crate::actions_panel::open(app, crate::actions_panel::Tab::Frame); } }); if let Some(m) = &k.motion { // A motion tween: what is keyed, and the way to its curves. - row_prose(ui, "Tween", |ui| { - ui.label(text(Type::Body, "Motion")); + row_prose(ui, tr!("Tween"), |ui| { + ui.label(text(Type::Body, tr!("Motion"))); }); - let keyed: Vec<&str> = m.tracks.iter().map(|t| t.property.label()).collect(); + let keyed: Vec<&str> = m.tracks.iter().map(|t| crate::i18n::t(t.property.label())).collect(); let n = m.key_frames().len(); - ui.label(text(Type::Caption, if keyed.is_empty() { "No property keyframes yet: move or change the object at a later frame to add some.".to_string() } else { format!("{} · {n} {}", keyed.join(", "), if n == 1 { "key frame" } else { "key frames" }) })); + ui.label(text(Type::Caption, if keyed.is_empty() { tr!("No property keyframes yet: move or change the object at a later frame to add some.").to_string() } else { trn!("{properties} · {n} key frame", "{properties} · {n} key frames", n, properties = keyed.join(", ")) })); // The motion path (ADR 0030): bent on the stage, straightened here. let segments = m.path.as_ref().map(|p| p.cmds.len().saturating_sub(1)); - row_prose(ui, "Path", |ui| { + row_prose(ui, tr!("Path"), |ui| { let what = match segments { - Some(1) => "Curved · 1 segment".to_string(), - Some(n) => format!("Curved · {n} segments"), - None => "Straight".to_string(), + Some(n) => trn!("Curved · {n} segment", "Curved · {n} segments", n), + None => tr!("Straight").to_string(), }; - let how = format!( - "Select the object to see its path on the stage. Drag the path to bend it and its ends to move them; {} the path or the object to move the whole path. With the Subselection tool (A), drag points and handles, double-click the path to add a point (or Alt-click it with the Pen), Delete removes points, and right-click makes them smooth or corners.", - crate::platform::shortcut_label("Ctrl+Drag") + let how = tr!( + "Select the object to see its path on the stage. Drag the path to bend it and its ends to move them; {drag} the path or the object to move the whole path. With the Subselection tool (A), drag points and handles, double-click the path to add a point (or Alt-click it with the Pen), Delete removes points, and right-click makes them smooth or corners.", + drag = crate::platform::shortcut_label("Ctrl+Drag") ); ui.label(text(Type::Body, what)).on_hover_text(how); - if segments.is_some() && ui.small_button("Straighten").on_hover_text("Back to the straight path the X and Y curves trace").named("Straighten motion path").clicked() { + if segments.is_some() && ui.small_button(tr!("Straighten")).on_hover_text(tr!("Back to the straight path the X and Y curves trace")).named(tr!("Straighten motion path")).clicked() { app.run("motion.clear_path", json!({})); } }); @@ -1135,24 +1310,51 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L let start = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).and_then(|p| anicraft_engine::doc::motion::path_ends(&p)).map(|(a, _)| a); if let Some(a) = start { let (mut x, mut y) = (a.x, a.y); - row(ui, "Path start", |ui| { - let hint = "Where the motion starts. Changing it moves the whole path, and the object with it; the timing stays."; - let rx = ui.add(egui::DragValue::new(&mut x).prefix("X ").speed(1.0).max_decimals(1)).named("Motion path start X").on_hover_text(hint); - let ry = ui.add(egui::DragValue::new(&mut y).prefix("Y ").speed(1.0).max_decimals(1)).named("Motion path start Y").on_hover_text(hint); + row(ui, tr!("Path start"), |ui| { + let hint = tr!("Where the motion starts. Changing it moves the whole path, and the object with it; the timing stays."); + let rx = ui.add(egui::DragValue::new(&mut x).prefix("X ").speed(1.0).max_decimals(1)).named(tr!("Motion path start X")).on_hover_text(hint); + let ry = ui.add(egui::DragValue::new(&mut y).prefix("Y ").speed(1.0).max_decimals(1)).named(tr!("Motion path start Y")).on_hover_text(hint); if rx.changed() || ry.changed() { - live(app, "Move Motion Path", "motion.move_path", json!({"dx": x - a.x, "dy": y - a.y})); + live(app, tr_noop!("Move Motion Path"), "motion.move_path", json!({"dx": x - a.x, "dy": y - a.y})); + } + }); + } + // Points pinned to frames (ADR 0049), and the keyboard route to pinning at the + // playhead. + let pins = base.map(|b| m.pinned_anchors(&b)).unwrap_or_default(); + if let (Some(&first), Some(&last)) = (pins.first(), pins.last()) { + let offset = frame.saturating_sub(k.start); + let n = pins.len().saturating_sub(2); + row_prose(ui, tr!("Pinned"), |ui| { + let how = tr!("Points of the motion path pinned to frames: the object passes each one exactly then, and the X and Y keyframes there are its place. The ends are always pinned. Moving the object on the stage at a frame pins a point there; with the Subselection tool (A), right-click a point to pin or unpin it."); + ui.label(text(Type::Body, trn!("{n} point", "{n} points", n))).on_hover_text(how); + match pins.iter().find(|q| q.frame == offset) { + Some(&q) if q != first && q != last => { + let tip = tr!("Point {anchor} shapes the path only again; the X and Y keyframes of frame {frame} go", anchor = q.anchor, frame = frame + 1); + if ui.small_button(tr!("Unpin")).on_hover_text(tip).named(tr!("Unpin the motion path point at this frame")).clicked() { + app.run("motion.unpin_point", json!({"frame": frame})); + } + } + Some(_) => {} + None if first.frame < offset && offset < last.frame => { + let tip = tr!("Add a point where the object is on frame {frame}, pinned to it: nothing moves now, and the object passes the point then however the path is edited", frame = frame + 1); + if ui.small_button(tr!("Pin Here")).on_hover_text(tip).named(tr!("Pin the motion path at this frame")).clicked() { + app.run("motion.pin_point", json!({"frame": frame})); + } + } + None => {} } }); } let mut orient = m.orient; - if crate::theme::checkbox(ui, &mut orient, "Orient to path").on_hover_text("Turn the object as its motion path turns").named("Orient to path").changed() { + if crate::theme::checkbox(ui, &mut orient, tr!("Orient to path")).on_hover_text(tr!("Turn the object as its motion path turns")).named(tr!("Orient to path")).changed() { app.run("motion.orient", json!({"orient": orient})); } ui.horizontal(|ui| { - if ui.button("Motion Editor").on_hover_text("Edit the property curves and eases").clicked() { + if ui.button(tr!("Motion Editor")).on_hover_text(tr!("Edit the property curves and eases")).clicked() { app.bottom = crate::app::BottomTab::MotionEditor; } - if ui.button("Remove Tween").on_hover_text("The object stays as it is on the span's first frame").clicked() { + if ui.button(tr!("Remove Tween")).on_hover_text(tr!("The object stays as it is on the span's first frame")).clicked() { app.run("timeline.remove_tween", json!({})); } }); @@ -1160,35 +1362,35 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L } 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| { + row_prose(ui, tr!("Tween"), |ui| { + egui::ComboBox::from_id_salt("prop_ease").width(150.0).selected_text(crate::i18n::t_dyn(&t.easing.label()).into_owned()).show_ui(ui, |ui| { for (name, e) in anicraft_engine::doc::Easing::PRESETS { - if ui.selectable_label(t.easing == e, name).clicked() { + if ui.selectable_label(t.easing == e, crate::i18n::t(name)).clicked() { app.run("timeline.set_easing", json!({"easing": crate::timeline::easing_param(e)})); } } }) .response - .set_name("Easing"); + .set_name(tr!("Easing")); }); let shape = t.kind == anicraft_engine::doc::TweenKind::Shape; - row_prose(ui, "Kind", |ui| { - egui::ComboBox::from_id_salt("prop_kind").width(150.0).selected_text(if shape { "Shape" } else { "Classic" }).show_ui(ui, |ui| { - if ui.selectable_label(!shape, "Classic").clicked() && shape { + row_prose(ui, tr!("Kind"), |ui| { + egui::ComboBox::from_id_salt("prop_kind").width(150.0).selected_text(if shape { tr!("Shape") } else { tr!("Classic") }).show_ui(ui, |ui| { + if ui.selectable_label(!shape, tr!("Classic")).clicked() && shape { app.run("timeline.create_tween", json!({})); } - if ui.selectable_label(shape, "Shape").on_hover_text("Morphs one shape into another").clicked() && !shape { + if ui.selectable_label(shape, tr!("Shape")).on_hover_text(tr!("Morphs one shape into another")).clicked() && !shape { app.run("timeline.create_shape_tween", json!({})); } }) .response - .set_name("Tween kind"); + .set_name(tr!("Tween kind")); }); // On a layer a motion guide steers: turn with the path. let guided = layer.parent.is_some_and(|p| app.s.doc.timeline(app.s.scene).layer(p).is_some_and(|g| g.kind == anicraft_engine::doc::LayerKind::Guide)); if guided { let mut orient = t.orient; - if crate::theme::checkbox(ui, &mut orient, "Orient to path").on_hover_text("Turn with the motion guide as it bends").changed() { + if crate::theme::checkbox(ui, &mut orient, tr!("Orient to path")).on_hover_text(tr!("Turn with the motion guide as it bends")).changed() { app.run("timeline.set_orient", json!({"orient": orient})); } } @@ -1196,13 +1398,13 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L } None => { ui.horizontal_wrapped(|ui| { - if ui.button("Create Motion Tween").on_hover_text("Animate this span's object property by property").clicked() { + if ui.button(tr!("Create Motion Tween")).on_hover_text(tr!("Animate this span's object property by property")).clicked() { app.run("timeline.create_motion_tween", json!({})); } - if ui.button("Create Classic Tween").clicked() { + if ui.button(tr!("Create Classic Tween")).clicked() { app.run("timeline.create_tween", json!({})); } - if ui.button("Create Shape Tween").on_hover_text("Morph this keyframe's shapes into the next keyframe's").clicked() { + if ui.button(tr!("Create Shape Tween")).on_hover_text(tr!("Morph this keyframe's shapes into the next keyframe's")).clicked() { app.run("timeline.create_shape_tween", json!({})); } }); @@ -1210,7 +1412,7 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L } } None => { - ui.label(text(Type::Caption, "Empty frame — press F7 for a blank keyframe")); + ui.label(text(Type::Caption, tr!("Empty frame — press F7 for a blank keyframe"))); } } } @@ -1220,12 +1422,12 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L fn volume_row(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::Layer) { let (mut pct, mut muted) = (f64::from(layer.volume) * 100.0, layer.muted); let id = layer.id.0; - row_prose(ui, "Volume", |ui| { + row_prose(ui, tr!("Volume"), |ui| { let r = with_type(ui, Type::Data, |ui| ui.add_enabled(!muted, egui::DragValue::new(&mut pct).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix(" %"))); - if r.named("Layer volume").on_hover_text("The volume of this layer's sounds, and of the sounds in the symbols on it").changed() { - live(app, "Layer Volume", "layer.set_volume", json!({"layer": id, "volume": (pct / 100.0).clamp(0.0, 1.0)})); + if r.named(tr!("Layer volume")).on_hover_text(tr!("The volume of this layer's sounds, and of the sounds in the symbols on it")).changed() { + live(app, tr_noop!("Layer Volume"), "layer.set_volume", json!({"layer": id, "volume": (pct / 100.0).clamp(0.0, 1.0)})); } - if crate::theme::checkbox(ui, &mut muted, "Mute").on_hover_text("Silence this layer's sounds while you work and in every export").named("Mute layer").changed() { + if crate::theme::checkbox(ui, &mut muted, tr!("Mute")).on_hover_text(tr!("Silence this layer's sounds while you work and in every export")).named(tr!("Mute layer")).changed() { app.run("layer.set_volume", json!({"layer": id, "muted": muted})); } }); @@ -1239,10 +1441,10 @@ fn sound_rows(app: &mut App, ui: &mut egui::Ui, current: Option "Linear gradient", - Paint::Radial { .. } => "Radial gradient", - Paint::Bitmap { .. } => "Bitmap fill", - Paint::Solid(_) => "Solid", + Paint::Linear { .. } => tr!("Linear gradient"), + Paint::Radial { .. } => tr!("Radial gradient"), + Paint::Bitmap { .. } => tr!("Bitmap fill"), + Paint::Solid(_) => tr!("Solid"), }; - ui.label(text(Type::Caption, what)).on_hover_text("Picked with the Eyedropper. It stays where it was on the stage (lock fill). Pick a colour to fill with a solid colour again."); + ui.label(text(Type::Caption, what)).on_hover_text(tr!("Picked with the Eyedropper. It stays where it was on the stage (lock fill). Pick a colour to fill with a solid colour again.")); } if !fills { - crate::theme::checkbox(ui, &mut st.use_fill, "").named("Fill").on_hover_text("Fill on/off"); + crate::theme::checkbox(ui, &mut st.use_fill, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off")); } }); } if !fills { - row(ui, "Stroke", |ui| { + row(ui, tr!("Stroke"), |ui| { let mut c = rgb(st.stroke); - if ui.color_edit_button_srgb(&mut c).named("Stroke colour").changed() { + if ui.color_edit_button_srgb(&mut c).named(tr!("Stroke colour")).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, "").named("Stroke").on_hover_text("Stroke on/off"); + crate::theme::checkbox(ui, &mut st.use_stroke, "").named(tr!("Stroke")).on_hover_text(tr!("Stroke on/off")); } - ui.add(egui::DragValue::new(&mut st.stroke_width).suffix(" px").speed(0.1).range(0.0..=100.0).max_decimals(1)).set_name("Stroke width"); + ui.add(egui::DragValue::new(&mut st.stroke_width).suffix(" px").speed(0.1).range(0.0..=100.0).max_decimals(1)).set_name(tr!("Stroke width")); }); // The width profile new strokes get. let current = st.profile(); if let Some(pick) = profile_picker(ui, ProfileRow::Tool, current.as_ref()) { st.set_profile(pick); } + // And their style, caps and joins (with the params the commands take). + if let Some(edit) = line_style_rows(ui, ProfileRow::Tool, &st.line, false) + && let Ok(Some(line)) = anicraft_engine::params::opt_stroke_style(&edit.params, &st.line, st.stroke_width) + { + st.line = line; + } } // Merge drawing (ADR 0031) or drawing objects, for the tools that draw shapes. if matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush) { let key = anicraft_engine::find_command("draw.object_drawing").and_then(|c| c.shortcut).map(crate::platform::shortcut_label).unwrap_or_default(); - row_prose(ui, "Drawing", |ui| { - crate::theme::checkbox(ui, &mut st.object_drawing, "Object drawing") - .on_hover_text(format!("On: each shape is an object of its own. Off: shapes cut and merge with the shapes they touch ({key})")); + row_prose(ui, tr!("Drawing"), |ui| { + crate::theme::checkbox(ui, &mut st.object_drawing, tr!("Object drawing")) + .on_hover_text(tr!("On: each shape is an object of its own. Off: shapes cut and merge with the shapes they touch ({key})", key = key)); }); } 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)).set_name("Corner radius"); + Tool::Rect => row(ui, tr!("Corners"), |ui| { + ui.add(egui::DragValue::new(&mut app.rect_radius).suffix(" px").range(0.0..=500.0)).set_name(tr!("Corner radius")); }), - Tool::Star => row(ui, "Points", |ui| { - ui.add(egui::DragValue::new(&mut app.star_points).range(3..=32)).set_name("Star points"); + Tool::Star => row(ui, tr!("Points"), |ui| { + ui.add(egui::DragValue::new(&mut app.star_points).range(3..=32)).set_name(tr!("Star points")); }), - 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| { + Tool::PaintBucket => row_prose(ui, tr!("Gap size"), |ui| { + egui::ComboBox::from_id_salt("bucket_gap").width(170.0).selected_text(crate::i18n::t(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()); + ui.selectable_value(&mut app.bucket_gap, g, crate::i18n::t(g.label())); } }) .response - .set_name("Gap size"); + .set_name(tr!("Gap size")); }), - Tool::Pencil => row(ui, "Mode", |ui| { + Tool::Pencil => row(ui, tr!("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()); + ui.selectable_value(&mut app.pencil_mode, m, crate::i18n::t(m.label())).on_hover_text(crate::i18n::t(m.hint())); } }), Tool::Brush => brush_props(app, ui), @@ -1415,33 +1624,33 @@ fn eraser_props(app: &mut App, ui: &mut egui::Ui) { use anicraft_engine::geom::brush::TipShape; let keys = [app.keymap.primary("view.brush_smaller"), app.keymap.primary("view.brush_larger")].into_iter().flatten().map(crate::platform::shortcut_label).collect::>().join(" / "); let o = &mut app.eraser; - row_prose(ui, "Faucet", |ui| { - crate::theme::checkbox(ui, &mut o.faucet, "Delete whole fills and lines").on_hover_text("On: a click deletes the whole fill or line under it. Off: drag to erase"); + row_prose(ui, tr!("Faucet"), |ui| { + crate::theme::checkbox(ui, &mut o.faucet, tr!("Delete whole fills and lines")).on_hover_text(tr!("On: a click deletes the whole fill or line under it. Off: drag to erase")); }); ui.add_enabled_ui(!o.faucet, |ui| { - row(ui, "Size", |ui| { - let r = ui.add(egui::DragValue::new(&mut o.size).suffix(" px").speed(0.25).range(SIZE_MIN..=SIZE_MAX).max_decimals(1)).named("Eraser size"); + row(ui, tr!("Size"), |ui| { + let r = ui.add(egui::DragValue::new(&mut o.size).suffix(" px").speed(0.25).range(SIZE_MIN..=SIZE_MAX).max_decimals(1)).named(tr!("Eraser size")); if !keys.is_empty() { - r.on_hover_text(format!("Eraser size ({keys})")); + r.on_hover_text(tr!("Eraser size ({keys})", keys = keys)); } }); - row(ui, "Shape", |ui| { - for (shape, label, hint) in [(TipShape::Round, "Round", "A round eraser"), (TipShape::Square, "Square", "A square eraser")] { + row(ui, tr!("Shape"), |ui| { + for (shape, label, hint) in [(TipShape::Round, tr!("Round"), tr!("A round eraser")), (TipShape::Square, tr!("Square"), tr!("A square eraser"))] { ui.selectable_value(&mut o.shape, shape, label).on_hover_text(hint); } }); - row_prose(ui, "Mode", |ui| { - egui::ComboBox::from_id_salt("erase_mode").width(170.0).selected_text(o.mode.label()).show_ui(ui, |ui| { + row_prose(ui, tr!("Mode"), |ui| { + egui::ComboBox::from_id_salt("erase_mode").width(170.0).selected_text(crate::i18n::t(o.mode.label())).show_ui(ui, |ui| { for m in EraseMode::ALL { - ui.selectable_value(&mut o.mode, m, m.label()).on_hover_text(m.hint()); + ui.selectable_value(&mut o.mode, m, crate::i18n::t(m.label())).on_hover_text(crate::i18n::t(m.hint())); } }) .response - .set_name("Erase mode"); + .set_name(tr!("Erase mode")); }); }); - row_prose(ui, "Stage", |ui| { - if ui.button("Erase Everything…").on_hover_text("Clears every visible, unlocked layer at this frame, as double-clicking the Eraser tool does. You can undo it").clicked() { + row_prose(ui, tr!("Stage"), |ui| { + if ui.button(tr!("Erase Everything…")).on_hover_text(tr!("Clears every visible, unlocked layer at this frame, as double-clicking the Eraser tool does. You can undo it")).clicked() { crate::erasertool::erase_everything(app); } }); @@ -1454,34 +1663,34 @@ fn brush_props(app: &mut App, ui: &mut egui::Ui) { use anicraft_engine::geom::brush::TipShape; let keys = [app.keymap.primary("view.brush_smaller"), app.keymap.primary("view.brush_larger")].into_iter().flatten().map(crate::platform::shortcut_label).collect::>().join(" / "); let b = &mut app.brush; - row(ui, "Size", |ui| { - let r = ui.add(egui::DragValue::new(&mut b.size).suffix(" px").speed(0.25).range(SIZE_MIN..=SIZE_MAX).max_decimals(1)).named("Brush size"); + row(ui, tr!("Size"), |ui| { + let r = ui.add(egui::DragValue::new(&mut b.size).suffix(" px").speed(0.25).range(SIZE_MIN..=SIZE_MAX).max_decimals(1)).named(tr!("Brush size")); if !keys.is_empty() { - r.on_hover_text(format!("Brush size ({keys})")); + r.on_hover_text(tr!("Brush size ({keys})", keys = keys)); } }); - row(ui, "Shape", |ui| { - for (shape, label, hint) in [(TipShape::Round, "Round", "A round or oval tip"), (TipShape::Square, "Square", "A square or flat tip")] { + row(ui, tr!("Shape"), |ui| { + for (shape, label, hint) in [(TipShape::Round, tr!("Round"), tr!("A round or oval tip")), (TipShape::Square, tr!("Square"), tr!("A square or flat tip"))] { ui.selectable_value(&mut b.shape, shape, label).on_hover_text(hint); } }); - row(ui, "Angle", |ui| { - ui.add(egui::DragValue::new(&mut b.angle).suffix("°").speed(1.0).range(0.0..=180.0).max_decimals(0)).named("Brush angle").on_hover_text("Turns a flattened tip (clockwise)"); + row(ui, tr!("Angle"), |ui| { + ui.add(egui::DragValue::new(&mut b.angle).suffix("°").speed(1.0).range(0.0..=180.0).max_decimals(0)).named(tr!("Brush angle")).on_hover_text(tr!("Turns a flattened tip (clockwise)")); }); - row(ui, "Roundness", |ui| { - ui.add(egui::DragValue::new(&mut b.roundness).suffix(" %").speed(0.5).range(5.0..=100.0).max_decimals(0)).named("Brush roundness").on_hover_text("100 %: as wide as it is tall. Less flattens the tip, for calligraphic strokes"); + row(ui, tr!("Roundness"), |ui| { + ui.add(egui::DragValue::new(&mut b.roundness).suffix(" %").speed(0.5).range(5.0..=100.0).max_decimals(0)).named(tr!("Brush roundness")).on_hover_text(tr!("100 %: as wide as it is tall. Less flattens the tip, for calligraphic strokes")); }); - row(ui, "Smoothing", |ui| { - ui.add(egui::DragValue::new(&mut b.smoothing).speed(0.5).range(0.0..=100.0).max_decimals(0)).named("Brush smoothing").on_hover_text("How much the stroke is smoothed: 0 follows the hand closely"); + row(ui, tr!("Smoothing"), |ui| { + ui.add(egui::DragValue::new(&mut b.smoothing).speed(0.5).range(0.0..=100.0).max_decimals(0)).named(tr!("Brush smoothing")).on_hover_text(tr!("How much the stroke is smoothed: 0 follows the hand closely")); }); - row_prose(ui, "Mode", |ui| { - egui::ComboBox::from_id_salt("brush_mode").width(170.0).selected_text(b.mode.label()).show_ui(ui, |ui| { + row_prose(ui, tr!("Mode"), |ui| { + egui::ComboBox::from_id_salt("brush_mode").width(170.0).selected_text(crate::i18n::t(b.mode.label())).show_ui(ui, |ui| { for m in PaintMode::ALL { - ui.selectable_value(&mut b.mode, m, m.label()).on_hover_text(m.hint()); + ui.selectable_value(&mut b.mode, m, crate::i18n::t(m.label())).on_hover_text(crate::i18n::t(m.hint())); } }) .response - .set_name("Paint mode"); + .set_name(tr!("Paint mode")); }); } @@ -1510,7 +1719,7 @@ fn profile_preview(ui: &mut egui::Ui, profile: Option<&anicraft_engine::doc::Wid resp } -/// Which Width row a profile menu is (each needs its own popup). +/// Which place a profile or line style menu is in (each needs its own popup). #[derive(Clone, Copy, Debug, Hash)] enum ProfileRow { Selection, @@ -1524,17 +1733,18 @@ fn profile_picker(ui: &mut egui::Ui, which: ProfileRow, current: Option<&anicraf None => Some(ProfilePreset::Uniform), Some(p) => p.preset(), }; - let label = preset.map_or_else(|| format!("Custom ({} points)", current.map_or(0, |p| p.points().len())), |p| p.label().to_string()); + let label = preset.map_or_else(|| trn!("Custom ({n} point)", "Custom ({n} points)", current.map_or(0, |p| p.points().len())), |p| crate::i18n::t(p.label()).to_string()); let mut picked = None; - row_prose(ui, "Width", |ui| { + row_prose(ui, tr!("Width"), |ui| { profile_preview(ui, current, vec2(44.0, 12.0), T.text_dim, None); let menu = ui.id().with(which); egui::ComboBox::from_id_salt(menu).width(150.0).selected_text(label).show_ui(ui, |ui| { for pr in ProfilePreset::ALL { let on = preset == Some(pr); let r = ui.horizontal(|ui| { - let pic = profile_preview(ui, pr.profile().as_ref(), vec2(44.0, 12.0), if on { T.text } else { T.text_dim }, Some(pr.label())); - let lab = ui.selectable_label(on, pr.label()); + let name = crate::i18n::t(pr.label()); + let pic = profile_preview(ui, pr.profile().as_ref(), vec2(44.0, 12.0), if on { T.text } else { T.text_dim }, Some(name)); + let lab = ui.selectable_label(on, name); pic.clicked() || lab.clicked() }); if r.inner && !on { @@ -1543,12 +1753,141 @@ fn profile_picker(ui: &mut egui::Ui, which: ProfileRow, current: Option<&anicraf } }) .response - .on_hover_text("How the stroke's width varies along it. Shape it by hand with the Width tool (U).") - .set_name("Stroke width profile"); + .on_hover_text(tr!("How the stroke's width varies along it. Shape it by hand with the Width tool (U).")) + .set_name(tr!("Stroke width profile")); }); picked } +/// A picture of a line style: solid, dashed or dotted, as the Style menu shows them. +fn line_preview(ui: &mut egui::Ui, kind: anicraft_engine::doc::DashKind, size: egui::Vec2, color: Color32) { + use anicraft_engine::doc::DashKind; + let (r, _) = ui.allocate_exact_size(size, Sense::hover()); + let p = ui.painter(); + let y = r.center().y; + let line = Stroke::new(2.0, color); + match kind { + DashKind::Solid => { + p.line_segment([pos2(r.left(), y), pos2(r.right(), y)], line); + } + DashKind::Dashed => { + p.extend(egui::Shape::dashed_line(&[pos2(r.left(), y), pos2(r.right(), y)], line, 6.0, 3.0)); + } + DashKind::Dotted => { + let mut x = r.left() + 1.5; + while x < r.right() { + p.circle_filled(pos2(x, y), 1.5, color); + x += 5.0; + } + } + } +} + +/// A change made in the line style rows: its undo label, the `stroke.set_style` params, and +/// whether it is a drag (coalesced into one undo step) rather than a pick. +struct LineEdit { + label: &'static str, + params: Value, + drag: bool, +} + +/// The rows under Stroke that shape the line, as in Animate's Properties: Style (solid, dashed, +/// dotted) with its lengths, Cap, Join and, for miter joins, the miter limit. `which` keeps each +/// place's menus apart. Returns the change, if any. +fn line_style_rows(ui: &mut egui::Ui, which: ProfileRow, st: &anicraft_engine::doc::StrokeStyle, differs: bool) -> Option { + use anicraft_engine::doc::{Cap, Dash, DashKind, Join}; + let mut edit = None; + let kind = st.dash_kind(); + row_prose(ui, tr!("Style"), |ui| { + line_preview(ui, kind, vec2(44.0, 12.0), T.text_dim); + egui::ComboBox::from_id_salt((which, "line_style")).width(110.0).selected_text(crate::i18n::t(kind.label())).show_ui(ui, |ui| { + for k in DashKind::ALL { + let on = k == kind; + let r = ui.horizontal(|ui| { + line_preview(ui, k, vec2(44.0, 12.0), if on { T.text } else { T.text_dim }); + ui.selectable_label(on, crate::i18n::t(k.label())).clicked() + }); + if r.inner && !on { + edit = Some(LineEdit { label: tr_noop!("Stroke style"), params: json!({"style": k.key()}), drag: false }); + } + } + }) + .response + .on_hover_text(tr!("Solid, dashed or dotted")) + .set_name(tr!("Stroke style")); + mixed(ui, differs); + }); + // The small dash editor: the first dash and gap (an imported pattern keeps the rest). + match &st.dash { + Some(Dash::Dashed { lengths, .. }) => { + let mut v = lengths.to_vec(); + row(ui, tr!("Dash"), |ui| { + let mut changed = false; + for (i, name, hint) in [(0usize, tr!("Dash length"), tr!("Length of each dash")), (1, tr!("Gap length"), tr!("Length of each gap"))] { + if let Some(x) = v.get_mut(i) { + let r = ui.add(egui::DragValue::new(x).suffix(" px").speed(0.1).range(0.0..=1000.0).max_decimals(1)).named(name); + changed |= r.on_hover_text(hint).changed(); + } + } + if lengths.len() > 2 { + ui.label(text(Type::Caption, trn!("+{n} more", "+{n} more", lengths.len() - 2))).on_hover_text(tr!("This pattern has more dashes and gaps than these two; they stay as they are")); + } + // Without any gap the line would be solid: that is the Style menu's job. + if changed && v.iter().skip(1).step_by(2).sum::() > 0.0 { + edit = Some(LineEdit { label: tr_noop!("Dash length"), params: json!({"dash": v}), drag: true }); + } + }); + } + Some(Dash::Dotted { spacing }) => { + let mut sp = *spacing; + row(ui, tr!("Spacing"), |ui| { + let r = ui.add(egui::DragValue::new(&mut sp).suffix(" px").speed(0.1).range(0.0..=1000.0).max_decimals(1)).named(tr!("Dot spacing")); + if r.on_hover_text(tr!("Space between the dots")).changed() { + edit = Some(LineEdit { label: tr_noop!("Dot spacing"), params: json!({"dot_spacing": sp}), drag: true }); + } + }); + } + None => {} + } + row_prose(ui, tr!("Cap"), |ui| { + egui::ComboBox::from_id_salt((which, "line_cap")).width(110.0).selected_text(crate::i18n::t(st.cap.label())).show_ui(ui, |ui| { + for c in Cap::ALL { + if ui.selectable_label(c == st.cap, crate::i18n::t(c.label())).clicked() && c != st.cap { + edit = Some(LineEdit { label: tr_noop!("Stroke cap"), params: json!({"cap": c.key()}), drag: false }); + } + } + }) + .response + .on_hover_text(tr!("How open ends finish: flat at the end (None), rounded, or squared off past it")) + .set_name(tr!("Stroke cap")); + if kind == DashKind::Dotted { + ui.label(text(Type::Caption, tr!("dots are round"))); + } + }); + row_prose(ui, tr!("Join"), |ui| { + egui::ComboBox::from_id_salt((which, "line_join")).width(110.0).selected_text(crate::i18n::t(st.join.label())).show_ui(ui, |ui| { + for j in Join::ALL { + if ui.selectable_label(j == st.join, crate::i18n::t(j.label())).clicked() && j != st.join { + edit = Some(LineEdit { label: tr_noop!("Stroke join"), params: json!({"join": j.key()}), drag: false }); + } + } + }) + .response + .on_hover_text(tr!("How corners turn: sharp (Miter), rounded, or cut across (Bevel)")) + .set_name(tr!("Stroke join")); + }); + if st.join == Join::Miter { + let mut m = st.miter_limit; + row(ui, tr!("Miter"), |ui| { + let r = ui.add(egui::DragValue::new(&mut m).speed(0.05).range(1.0..=100.0).max_decimals(1)).named(tr!("Miter limit")); + if r.on_hover_text(tr!("Corners sharper than this are bevelled: how far a point may reach, in stroke widths")).changed() { + edit = Some(LineEdit { label: tr_noop!("Miter limit"), params: json!({"miter": m}), drag: true }); + } + }); + } + edit +} + /// 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()); @@ -1573,18 +1912,18 @@ fn library(app: &mut App, ui: &mut egui::Ui) { .map(|sym| LibraryRow { item: LibraryItem::Symbol(sym.id), name: sym.name.clone(), - detail: format!("{:?} · {}f", sym.kind, sym.timeline.frame_count()), + detail: tr!("{kind} · {frames}f", kind = symbol_kind_label(sym.kind), frames = sym.timeline.frame_count()), kind: Some(sym.kind), }) - .chain(doc.bitmaps.iter().map(|b| LibraryRow { item: LibraryItem::Bitmap(b.id), name: b.name.clone(), detail: format!("Bitmap · {}×{}", b.width, b.height), kind: None })) - .chain(doc.sounds.iter().map(|x| LibraryRow { item: LibraryItem::Sound(x.id), name: x.name.clone(), detail: format!("Sound · {:.1} s", x.seconds()), kind: None })) + .chain(doc.bitmaps.iter().map(|b| LibraryRow { item: LibraryItem::Bitmap(b.id), name: b.name.clone(), detail: tr!("Bitmap · {width}×{height}", width = b.width, height = b.height), kind: None })) + .chain(doc.sounds.iter().map(|x| LibraryRow { item: LibraryItem::Sound(x.id), name: x.name.clone(), detail: tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds())), kind: None })) .collect(); if rows.is_empty() { let key = |id: &str| app.keymap.primary(id).map(crate::platform::shortcut_label).unwrap_or_default(); - ui.label(text(Type::Caption, format!("No symbols, images or sounds yet. Select artwork and press {} to make a symbol, or import an image or a sound with {}.", key("modify.convert_to_symbol"), key("file.import")))); + ui.label(text(Type::Caption, tr!("No symbols, images or sounds yet. Select artwork and press {convert} to make a symbol, or import an image or a sound with {import}.", convert = key("modify.convert_to_symbol"), import = key("file.import")))); return; } - ui.label(text(Type::Caption, format!("{} {}", rows.len(), if rows.len() == 1 { "item" } else { "items" }))); + ui.label(text(Type::Caption, trn!("{n} item", "{n} items", rows.len()))); // Sounds go on the active layer's keyframe at the playhead, their span grown to fit. let place = |app: &mut App, item: LibraryItem| match item { LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), @@ -1626,7 +1965,7 @@ fn library(app: &mut App, ui: &mut egui::Ui) { } if let LibraryItem::Sound(id) = row.item { resp.context_menu(|ui| { - if ui.button("Delete Sound").clicked() { + if ui.button(tr!("Delete Sound")).clicked() { ui.close(); app.request("sound.delete", json!({"sound": id.0})); } @@ -1639,22 +1978,22 @@ fn library(app: &mut App, ui: &mut egui::Ui) { match can_place { Some(LibraryItem::Sound(id)) => { ui.horizontal(|ui| { - if ui.button("Preview").on_hover_text("Plays the sound on its own").clicked() + if ui.button(tr!("Preview")).on_hover_text(tr!("Plays the sound on its own")).clicked() && let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded()) { app.playing = false; app.sound.preview(dec.pcm.clone()); if let Some(e) = app.sound.error.take() { - app.status_err(format!("No sound: {e}")); + app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e.to_string()))); } } - if ui.button("Place on timeline").on_hover_text("Puts it on the active layer's keyframe at the playhead (or double-click it)").clicked() { + if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click it)")).clicked() { place(app, LibraryItem::Sound(id)); } }); } _ => { - if ui.add_enabled(can_place.is_some(), egui::Button::new("Place on stage")).on_hover_text("Adds it at the stage centre (or double-click an item)").clicked() + if ui.add_enabled(can_place.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre (or double-click an item)")).clicked() && let Some(item) = can_place { place(app, item); } diff --git a/src/pathtools.rs b/src/pathtools.rs index d8c098c5..7cfd838e 100644 --- a/src/pathtools.rs +++ b/src/pathtools.rs @@ -12,6 +12,7 @@ use crate::app::{App, Drag, Tool}; use crate::theme::T; +use anicraft_engine::cmds_rawsub::{Handle, RawPoints}; use anicraft_engine::doc::{ElementId, ElementKind}; use anicraft_engine::geom::edit::{ANCHOR, C1, C2}; use anicraft_engine::geom::{Affine, Path, PathCmd, Vec2}; @@ -150,18 +151,20 @@ pub enum PencilMode { } impl PencilMode { + /// The English name, translated where it is drawn (`crate::i18n::t`). pub fn label(self) -> &'static str { match self { - PencilMode::Smooth => "Smooth", - PencilMode::Straighten => "Straighten", - PencilMode::Ink => "Ink", + PencilMode::Smooth => tr_noop!("Smooth"), + PencilMode::Straighten => tr_noop!("Straighten"), + PencilMode::Ink => tr_noop!("Ink"), } } + /// The English hint, translated where it is drawn (`crate::i18n::t`). 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.", + PencilMode::Smooth => tr_noop!("Fits smooth curves to the stroke, keeping sharp corners."), + PencilMode::Straighten => tr_noop!("Turns the stroke into straight segments."), + PencilMode::Ink => tr_noop!("Follows the hand closely with little smoothing."), } } fn id(self) -> &'static str { @@ -201,8 +204,10 @@ fn selected_shapes(app: &App) -> Vec<(ElementId, Arc, Affine)> { app.s .visible_elements() .into_iter() - .filter(|e| app.s.selection.contains(&e.id)) + .filter(|e| app.s.selection.contains(app.s.layer, e.id)) .filter_map(|e| match &e.kind { + // Raw shapes show their shared points instead (ADR 0042, below). + ElementKind::Shape(sh) if sh.merge => None, ElementKind::Shape(sh) => Some((e.id, sh.path.clone(), e.transform)), ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => None, }) @@ -227,6 +232,7 @@ fn shown_handles(path: &Path, anchors: impl Iterator) -> Vec<(usiz /// Drops point references that no longer exist (after undo, deselection or a frame change). pub fn upkeep(app: &mut App) { + raw_upkeep(app); if app.points.is_empty() { return; } @@ -255,6 +261,9 @@ fn point_at(app: &App, at: Pos2, xf: Xf) -> Option { /// 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(d) = raw_drag_start(app, press, shift, xf) { + return d; + } if let Some(pt) = point_at(app, press, xf) { if !app.points.contains(&pt) { if !shift { @@ -262,21 +271,26 @@ pub fn subselect_drag_start(app: &mut App, press: Pos2, shift: bool, xf: Xf) -> } app.points.push(pt); } - app.s.begin_gesture("Move Points"); + // Undo labels stay English in the history and are translated where they show. + app.s.begin_gesture(tr_noop!("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) { + if let Some((layer, el)) = app.s.hit_test(sp, 3.0 * xf.unit()) { + if !app.s.selection.contains(layer, el) { app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); app.points.clear(); } - app.s.begin_gesture("Move"); + app.s.begin_gesture(tr_noop!("Move")); return Drag::Move { last: pos2(sp.x, sp.y) }; } if !shift { app.points.clear(); + app.raw_anchors.clear(); + app.raw_ends.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) } } + // A marquee shows the points of the shapes it touches on the active layer and selects the + // points inside it; it never cuts (that is the Selection tool's). + 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). @@ -289,11 +303,21 @@ pub fn move_points(app: &mut App, d: Vec2) { } } -/// Selects the anchors inside a stage-space marquee. +/// The Subselection marquee: the shapes it touches on the active layer are selected whole (raw +/// ones with everything connected to them, ADR 0042) and the anchors inside it are selected. 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(); + app.raw_anchors.clear(); + app.raw_ends.clear(); + } + if let Some(v) = app.run("raw.subselect_rect", json!({"x0": a.x, "y0": a.y, "x1": b.x, "y1": b.y, "add": shift})) { + for q in positions(&v["anchors"]) { + if !app.raw_anchors.iter().any(|p| p.distance(q) <= SNAP) { + app.raw_anchors.push(q); + } + } } for (id, path, m) in selected_shapes(app) { for (cmd, q) in path.editable_anchors() { @@ -308,6 +332,9 @@ pub fn marquee_points(app: &mut App, a: Pos2, b: Pos2, shift: bool) { /// 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 raw_click(app, at, shift, xf) { + return; + } if let Some(pt) = point_at(app, at, xf) { if shift { if let Some(i) = app.points.iter().position(|p| *p == pt) { @@ -323,6 +350,8 @@ pub fn subselect_click(app: &mut App, at: Pos2, shift: bool, xf: Xf) { let sp = xf.to_stage(at); app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); app.points.clear(); + app.raw_anchors.clear(); + app.raw_ends.clear(); } /// Double-click on a selected shape's outline adds a point there and selects it. @@ -339,7 +368,7 @@ fn add_point_on_selected(app: &mut App, at: Pos2, xf: Xf) -> bool { if let Ok(v) = r { app.points = v["cmd"].as_u64().map(|c| vec![(id, c as usize, ANCHOR)]).unwrap_or_default(); app.motion_anchors.clear(); - app.status_ok(format!("Added a point. {} to undo.", crate::platform::shortcut_label("Ctrl+Z"))); + app.status_ok(tr!("Added a point. {undo} to undo.", undo = app.undo_key())); return true; } } @@ -381,22 +410,232 @@ 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() { + if ui.button(tr!("Make Smooth")).clicked() { convert_points(app, true); ui.close(); } - if ui.button("Make Corner").clicked() { + if ui.button(tr!("Make Corner")).clicked() { convert_points(app, false); ui.close(); } ui.separator(); - if ui.button("Delete Point").clicked() { + if ui.button(tr!("Delete Point")).clicked() { delete_points(app); ui.close(); } true } +// ----- Subselection on raw shapes (ADR 0042) ------------------------------------------------- + +/// Two positions this close are one shared point. +const SNAP: f32 = anicraft_engine::geom::planar::SNAP; +/// How near (screen pixels) a press takes an anchor of a raw shape that isn't shown yet. +const GRAB_POINT: f32 = 6.0; + +fn is_raw(e: &anicraft_engine::doc::Element) -> bool { + matches!(&e.kind, ElementKind::Shape(sh) if sh.merge) +} + +/// The selected raw shapes on the active layer: Subselection shows their points. +fn raw_selected(app: &App) -> Vec { + app.s.visible_elements().iter().filter(|e| app.s.selection.contains(app.s.layer, e.id) && is_raw(e)).map(|e| e.id).collect() +} + +/// The anchors and handles of the selected raw shapes. +pub fn raw_shown(app: &App) -> RawPoints { + let ids = raw_selected(app); + if ids.is_empty() { RawPoints::default() } else { app.s.raw_points(&ids) } +} + +/// The handles that show: those of the selected anchors' curves and of the clicked edge. +fn visible_handles<'a>(app: &'a App, pts: &'a RawPoints) -> impl Iterator + 'a { + pts.handles.iter().filter(|h| app.raw_anchors.iter().chain(&app.raw_ends).any(|a| a.distance(h.anchor) <= SNAP)) +} + +fn positions(v: &serde_json::Value) -> Vec { + v.as_array().into_iter().flatten().filter_map(|p| Some(Vec2::new(p.get(0)?.as_f64()? as f32, p.get(1)?.as_f64()? as f32))).collect() +} + +/// What of the shown raw points is under a screen position: a handle (on top), else an anchor. +enum RawHit { + Handle(Handle), + Anchor(Vec2), +} + +fn raw_point_at(app: &App, pts: &RawPoints, at: Pos2, xf: Xf) -> Option { + let d = |q: Vec2| xf.to_screen(q).distance(at); + if let Some(h) = visible_handles(app, pts).filter(|h| d(h.at) <= PICK).min_by(|a, b| d(a.at).total_cmp(&d(b.at))) { + return Some(RawHit::Handle(*h)); + } + pts.anchors.iter().copied().filter(|q| d(*q) <= PICK).min_by(|a, b| d(*a).total_cmp(&d(*b))).map(RawHit::Anchor) +} + +/// Keeps the selected anchors on the points that are still there (after a drag merged, undo, or +/// a frame change), and drops them with their shapes. +fn raw_upkeep(app: &mut App) { + if app.raw_anchors.is_empty() && app.raw_ends.is_empty() { + return; + } + // A drag moves them itself. + if matches!(app.drag, Drag::RawPoint { .. } | Drag::RawHandle { .. } | Drag::SnapMove { .. }) { + return; + } + let pts = raw_shown(app); + let settle = |list: &mut Vec| { + let mut out: Vec = Vec::with_capacity(list.len()); + for q in list.iter() { + // A merge may have met it with a point nearby (at most `SNAP` away, ADR 0041). + if let Some(p) = pts.anchors.iter().copied().filter(|p| p.distance(*q) <= 2.5 * SNAP).min_by(|a, b| a.distance(*q).total_cmp(&b.distance(*q))) + && !out.contains(&p) + { + out.push(p); + } + } + *list = out; + }; + settle(&mut app.raw_anchors); + settle(&mut app.raw_ends); +} + +/// Shows the connected raw shapes at stage point `sp` (their layer becomes the active one). +/// False when there is no raw shape there. +fn raw_show_at(app: &mut App, sp: Vec2, shift: bool, xf: Xf) -> bool { + let slop = 3.0 * xf.unit(); + let Some((layer, id)) = app.s.hit_test(sp, slop) else { return false }; + // On the active layer, look first; another layer's shape is for the engine to say. + if layer == app.s.layer && !app.s.visible_elements().iter().any(|e| e.id == id && is_raw(e)) { + return false; + } + let Some(v) = app.run("raw.subselect", json!({"x": sp.x, "y": sp.y, "add": shift, "slop": slop})) else { return false }; + if v["raw"] != json!(true) { + return false; + } + if !shift { + app.raw_anchors.clear(); + } + app.raw_ends = positions(&v["ends"]); + app.points.clear(); + true +} + +/// A press with Subselection on raw shapes: a shown handle bends its curve, a shown anchor moves +/// (with the other selected anchors), an anchor of a raw shape not shown yet shows its shapes and +/// moves, and a raw line or fill shows its connected shapes and moves all of them. `None` when +/// the press is not on raw artwork. +fn raw_drag_start(app: &mut App, press: Pos2, shift: bool, xf: Xf) -> Option { + let sp = xf.to_stage(press); + let pts = raw_shown(app); + let anchor = match raw_point_at(app, &pts, press, xf) { + Some(RawHit::Handle(h)) => { + app.s.begin_gesture(tr_noop!("Move Handle")); + app.raw_touched.clear(); + return Some(Drag::RawHandle { id: h.id, cmd: h.cmd, slot: h.slot, last: pos2(sp.x, sp.y) }); + } + Some(RawHit::Anchor(q)) => Some(q), + // An unselected raw shape's corner or end: show its shapes, then take the point. + None => match app.s.raw_grab(sp, 3.0 * xf.unit(), GRAB_POINT * xf.unit()) { + Some((_, anicraft_engine::cmds_raw::Grab::Point { at })) if raw_show_at(app, at, false, xf) => Some(at), + _ => None, + }, + }; + if let Some(q) = anchor { + if !app.raw_anchors.iter().any(|p| p.distance(q) <= SNAP) { + if !shift { + app.raw_anchors.clear(); + } + app.raw_anchors.push(q); + } + app.raw_with = app.raw_anchors.iter().copied().filter(|p| p.distance(q) > SNAP).collect(); + app.raw_points = serde_json::Value::Null; + app.raw_touched.clear(); + app.s.begin_gesture(tr_noop!("Move Points")); + return Some(Drag::RawPoint { at: pos2(q.x, q.y), off: pos2(q.x, q.y) - pos2(sp.x, sp.y) }); + } + // A raw line or fill: everything connected to it moves (Animate's Subselection drag). + let on_shown = app.s.hit_test(sp, 3.0 * xf.unit()).is_some_and(|(l, id)| l == app.s.layer && app.s.selection.contains(l, id) && app.s.visible_elements().iter().any(|e| e.id == id && is_raw(e))); + if !on_shown && !raw_show_at(app, sp, shift, xf) { + return None; + } + app.s.begin_gesture(tr_noop!("Move")); + Some(Drag::SnapMove { start: pos2(sp.x, sp.y), applied: egui::Vec2::ZERO }) +} + +/// A click with Subselection on raw shapes: an anchor toggles into the selection (Shift adds or +/// removes it), a raw line or fill shows everything connected to it. False when it wasn't on +/// raw artwork. +fn raw_click(app: &mut App, at: Pos2, shift: bool, xf: Xf) -> bool { + let pts = raw_shown(app); + match raw_point_at(app, &pts, at, xf) { + Some(RawHit::Anchor(q)) => { + match app.raw_anchors.iter().position(|p| p.distance(q) <= SNAP) { + Some(i) if shift => { + app.raw_anchors.remove(i); + } + _ if shift => app.raw_anchors.push(q), + _ => app.raw_anchors = vec![q], + } + true + } + Some(RawHit::Handle(_)) => true, + None => raw_show_at(app, xf.to_stage(at), shift, xf), + } +} + +/// The selected raw anchors moved by the arrow keys: every shape sharing them moves too, and +/// they merge where they land (points within 0.2 px meet, ADR 0041). One undo step a press. +fn raw_nudge(app: &mut App, d: Vec2) { + let Some((&first, rest)) = app.raw_anchors.split_first() else { return }; + let with: Vec<[f32; 2]> = rest.iter().map(|q| [q.x, q.y]).collect(); + let p = json!({"x": first.x, "y": first.y, "to_x": first.x + d.x, "to_y": first.y + d.y, "with": with}); + if app.run("raw.move_point", p).is_some() { + for q in app.raw_anchors.iter_mut().chain(app.raw_ends.iter_mut()) { + *q = *q + d; + } + } +} + +/// While raw points are dragged, the selected anchors follow by `d` (the move this frame), and +/// the clicked edge's ends too when they move (`all`: the whole drawing moves). +pub fn raw_follow(app: &mut App, d: Vec2, all: bool) { + if d == Vec2::ZERO { + return; + } + let moving = app.raw_anchors.clone(); + for q in app.raw_anchors.iter_mut() { + *q = *q + d; + } + for q in app.raw_ends.iter_mut().filter(|q| all || moving.iter().any(|m| m.distance(**q) <= SNAP)) { + *q = *q + d; + } +} + +/// The raw shapes' outlines, handles and anchors (hollow squares; selected ones solid). +fn draw_raw(app: &App, painter: &egui::Painter, xf: Xf) { + let ids = raw_selected(app); + if ids.is_empty() { + return; + } + let line = Stroke::new(1.0, T.selection); + let to_px = Affine::translate(xf.origin.x, xf.origin.y).mul(&Affine::scale(xf.zoom, xf.zoom)); + for e in app.s.visible_elements().iter().filter(|e| ids.contains(&e.id)) { + let ElementKind::Shape(sh) = &e.kind else { continue }; + for pl in sh.path.flatten(&to_px.mul(&e.transform), 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 pts = app.s.raw_points(&ids); + for h in visible_handles(app, &pts) { + let (hs, a) = (xf.to_screen(h.at), xf.to_screen(h.anchor)); + painter.line_segment([a, hs], line); + painter.circle_filled(hs, 3.0, T.selection); + } + for q in pts.anchors.iter().take(20_000) { + anchor_box(painter, xf.to_screen(*q), app.raw_anchors.iter().any(|p| p.distance(*q) <= SNAP)); + } +} + // ----- keys ---------------------------------------------------------------------------------- /// Keys the path tools own while they are busy, taken before the global shortcuts (so Enter @@ -423,6 +662,48 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) { if take(Key::Escape) { app.points.clear(); } + if let Some(d) = arrow_nudge(ctx, app.view.zoom) { + move_points_step(app, d); + } + } + if app.tool == Tool::Subselect && !app.raw_anchors.is_empty() { + if take(Key::Delete) || take(Key::Backspace) { + app.status_err(tr!("Points of merged drawings can't be deleted yet. Select the parts with the Selection tool (V) and delete them.")); + } + if take(Key::Escape) { + app.raw_anchors.clear(); + } + if let Some(d) = arrow_nudge(ctx, app.view.zoom) { + raw_nudge(app, d); + } + } +} + +/// An arrow key press (taken): 1 screen pixel, Shift 10, as Animate's (issue #42 section 4). +fn arrow_nudge(ctx: &egui::Context, zoom: f32) -> Option { + let mut d = Vec2::ZERO; + ctx.input_mut(|i| { + for (k, v) in [(Key::ArrowLeft, Vec2::new(-1.0, 0.0)), (Key::ArrowRight, Vec2::new(1.0, 0.0)), (Key::ArrowUp, Vec2::new(0.0, -1.0)), (Key::ArrowDown, Vec2::new(0.0, 1.0))] { + // Shift first: a plain chord also matches a press with Shift held. + for (m, step) in [(Modifiers::SHIFT, 10.0), (Modifiers::NONE, 1.0)] { + while i.consume_key(m, k) { + d = d + v * (step / zoom.max(1e-3)); + } + } + } + }); + (d != Vec2::ZERO).then_some(d) +} + +/// Selected points of drawing objects nudged by the arrow keys: one undo step. +fn move_points_step(app: &mut App, d: Vec2) { + let own = !app.s.in_gesture(); + if own { + app.s.begin_gesture(tr_noop!("Move Points")); + } + move_points(app, d); + if own { + app.s.end_gesture(); } } @@ -444,6 +725,7 @@ fn anchor_box(painter: &egui::Painter, c: Pos2, filled: bool) { 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 { + draw_raw(app, painter, xf); 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) { @@ -527,6 +809,87 @@ mod tests { assert!(s.execute("draw.path", &json!({"d": pen.to_svg(true)})).is_ok()); } + /// Subselection on a merged drawing (ADR 0042), on a headless app: a raw rectangle with + /// its outline at the stage origin, stage and screen coordinates the same. + mod raw { + use super::*; + + const XF: Xf = Xf { origin: Pos2::ZERO, zoom: 1.0 }; + + fn app_and_ctx() -> (App, egui::Context) { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::Document::default()); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + app.run("draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000", "object": false})); + app.run("edit.deselect", json!({})); + app.tool = Tool::Subselect; + app.view.zoom = 1.0; + (app, ctx) + } + + fn has(list: &[Vec2], x: f32, y: f32) -> bool { + list.iter().any(|q| q.distance(Vec2::new(x, y)) < 1e-2) + } + + #[test] + fn a_click_shows_the_connected_points_and_selects_anchors() { + let (mut app, _) = app_and_ctx(); + subselect_click(&mut app, pos2(50.0, 0.0), false, XF); + assert_eq!(app.s.selection.len(), 5, "the fill and its four sides"); + assert_eq!(raw_shown(&app).anchors.len(), 4); + assert!(has(&app.raw_ends, 0.0, 0.0) && has(&app.raw_ends, 100.0, 0.0), "{:?}", app.raw_ends); + subselect_click(&mut app, pos2(100.0, 0.0), false, XF); + assert_eq!(app.raw_anchors.len(), 1); + subselect_click(&mut app, pos2(0.0, 0.0), true, XF); + assert_eq!(app.raw_anchors.len(), 2, "Shift adds"); + subselect_click(&mut app, pos2(0.0, 0.0), true, XF); + assert_eq!(app.raw_anchors.len(), 1, "and removes"); + subselect_click(&mut app, pos2(500.0, 500.0), false, XF); + assert!(app.s.selection.is_empty() && app.raw_anchors.is_empty()); + } + + #[test] + fn arrow_keys_move_the_selected_anchors_with_every_shape_on_them() { + let (mut app, ctx) = app_and_ctx(); + subselect_click(&mut app, pos2(50.0, 0.0), false, XF); + subselect_click(&mut app, pos2(100.0, 0.0), false, XF); + subselect_click(&mut app, pos2(0.0, 0.0), true, XF); + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::Key { key: Key::ArrowUp, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); + let mut out = ctx.run_ui(input, |ui| consume_keys(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(has(&app.raw_anchors, 0.0, -10.0) && has(&app.raw_anchors, 100.0, -10.0), "{:?}", app.raw_anchors); + upkeep(&mut app); + assert_eq!(app.raw_anchors.len(), 2, "still on the moved points"); + let pts = raw_shown(&app); + assert!(has(&pts.anchors, 0.0, -10.0) && has(&pts.anchors, 100.0, 80.0) && pts.anchors.len() == 4, "{:?}", pts.anchors); + assert!(app.s.can_undo()); + } + + #[test] + fn a_press_takes_an_anchor_or_moves_everything_connected() { + let (mut app, _) = app_and_ctx(); + // An anchor of a drawing not shown yet: it shows, and the point is taken. + assert!(matches!(subselect_drag_start(&mut app, pos2(100.0, 80.0), false, XF), Drag::RawPoint { .. })); + assert_eq!(app.s.selection.len(), 5); + assert!(has(&app.raw_anchors, 100.0, 80.0)); + app.s.end_gesture(); + // With another anchor selected, Shift: both move. + assert!(matches!(subselect_drag_start(&mut app, pos2(0.0, 80.0), true, XF), Drag::RawPoint { .. })); + assert_eq!(app.raw_with.len(), 1); + app.s.end_gesture(); + // Inside the fill: the whole connected drawing moves. + assert!(matches!(subselect_drag_start(&mut app, pos2(50.0, 40.0), false, XF), Drag::SnapMove { .. })); + app.s.end_gesture(); + // Empty space: a marquee, which selects the anchors inside it. + assert!(matches!(subselect_drag_start(&mut app, pos2(300.0, 300.0), false, XF), Drag::PointMarquee { .. })); + marquee_points(&mut app, pos2(90.0, -10.0), pos2(120.0, 10.0), false); + assert_eq!(app.s.selection.len(), 5); + assert_eq!(app.raw_anchors.len(), 1); + assert!(has(&app.raw_anchors, 100.0, 0.0)); + } + } + #[test] fn handles_shown_for_a_selected_smooth_anchor() { let mut p = Path::new(); diff --git a/src/platform.rs b/src/platform.rs index baa32d4b..551fd8a5 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -31,13 +31,14 @@ pub const OS: Os = if cfg!(target_os = "macos") { }; impl Os { + /// The platform's name in the interface language (Preferences shows it). pub fn name(self) -> &'static str { match self { - Os::Mac => "macOS", - Os::Windows => "Windows", - Os::Linux => "Linux / BSD", - Os::Web => "web browser", - Os::Other => "other", + Os::Mac => tr!("macOS"), + Os::Windows => tr!("Windows"), + Os::Linux => tr!("Linux / BSD"), + Os::Web => tr!("web browser"), + Os::Other => tr!("other"), } } } @@ -45,6 +46,13 @@ impl Os { /// The web build runs in a browser (ADR 0036). pub const WEB: bool = cfg!(target_arch = "wasm32"); +/// The language the system's interface is in, as a BCP 47 tag (`de-DE`, `pt-BR`): Windows' +/// user locale, macOS' preferred languages, `LC_ALL` / `LC_MESSAGES` / `LANG` on Linux and the +/// BSDs, the browser's languages on the web (ADR 0040). `None` when it can't be told. +pub fn system_locale() -> Option { + sys_locale::get_locale().filter(|l| !l.is_empty() && l.len() <= 64) +} + /// Whether the active fonts can draw ⌘ ⇧ ⌥ ⌃ (set once fonts are installed). static MAC_GLYPHS: AtomicBool = AtomicBool::new(false); @@ -108,7 +116,7 @@ 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::Mac => env("HOME").map(|p| p.join("Library").join("Application Support").join("AniCraft")), // i18n-exempt: folder names // A web page has no folders: settings go to browser storage (`load_settings`). Os::Web => None, Os::Linux | Os::Other => env("XDG_CONFIG_HOME").or_else(|| env("HOME").map(|h| h.join(".config"))).map(|p| p.join("anicraft")), @@ -120,7 +128,7 @@ pub fn config_dir() -> Option { pub fn recovery_dir() -> Option { match std::env::var_os("ANICRAFT_RECOVERY_DIR").filter(|v| !v.is_empty()) { Some(d) => Some(PathBuf::from(d)), - None => config_dir().map(|d| d.join("Recovery")), + None => config_dir().map(|d| d.join("Recovery")), // i18n-exempt: a folder name } } @@ -129,12 +137,12 @@ pub fn recovery_dir_overridden() -> bool { std::env::var_os("ANICRAFT_RECOVERY_DIR").is_some_and(|v| !v.is_empty()) } -/// Where settings are kept, for Preferences. +/// Where settings are kept, for Preferences (in the interface language). pub fn settings_place() -> String { if WEB { - return "this browser's storage for this site".into(); + return tr!("this browser's storage for this site").into(); } - config_dir().map_or_else(|| "memory only".to_string(), |d| d.display().to_string()) + config_dir().map_or_else(|| tr!("memory only").to_string(), |d| d.display().to_string()) } /// The saved preferences (JSON): `prefs.json` in the settings folder, or browser storage. @@ -151,7 +159,7 @@ pub fn save_settings(json: &str) -> Result<(), String> { return crate::web::storage_set(crate::web::PREFS_KEY, json); #[cfg(not(target_arch = "wasm32"))] { - let dir = config_dir().ok_or("no settings folder on this system")?; + let dir = config_dir().ok_or(tr!("no settings folder on this system"))?; std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; let (path, tmp) = (dir.join("prefs.json"), dir.join("prefs.json.tmp")); std::fs::write(&tmp, json).map_err(|e| e.to_string())?; @@ -166,8 +174,8 @@ pub fn unavailable(cmd: &str) -> Option<&'static str> { return None; } match cmd { - "file.export_video" => Some("Video export runs ffmpeg, which a web browser can't start: use the desktop app, or export an animated GIF or a PNG sequence"), - "plugin.install" | "plugin.remove" | "plugin.reload" => Some("Plug-ins are installed into a folder on your computer: use the desktop app"), + "file.export_video" => Some(tr_noop!("Video export runs ffmpeg, which a web browser can't start: use the desktop app, or export an animated GIF or a PNG sequence")), + "plugin.install" | "plugin.remove" | "plugin.reload" => Some(tr_noop!("Plug-ins are installed into a folder on your computer: use the desktop app")), _ => None, } } @@ -223,23 +231,24 @@ pub fn forced_renderer(arg: Option<&str>) -> Option { // ----- native file dialogs ---------------------------------------------------------------------- -/// File type filters per command. +/// File type filters per command: the filter's name (English, translated where it is shown) +/// and its extensions. pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { match cmd { - "file.export_png" => ("PNG image", &["png"]), - "file.export_gif" => ("Animated GIF", &["gif"]), - "file.export_svg" => ("SVG image", &["svg"]), - "file.export_lottie" => ("Lottie animation", &["json"]), - "file.export_html" => ("Web page", &["html", "htm"]), - "file.import" => ("Drawing, image or sound", &["svg", "png", "jpg", "jpeg", "wav", "ogg", "mp3"]), - "file.import_to_library" => ("Sound or image", &["wav", "ogg", "mp3", "png", "jpg", "jpeg"]), - "file.export_audio" => ("WAV sound", &["wav"]), - "file.export_sprite_sheet" => ("PNG sprite sheet", &["png"]), - "file.export_video" => ("Video (WebM or MP4)", &["webm", "mp4"]), + "file.export_png" => (tr_noop!("PNG image"), &["png"]), + "file.export_gif" => (tr_noop!("Animated GIF"), &["gif"]), + "file.export_svg" => (tr_noop!("SVG image"), &["svg"]), + "file.export_lottie" => (tr_noop!("Lottie animation"), &["json"]), + "file.export_html" => (tr_noop!("Web page"), &["html", "htm"]), + "file.import" => (tr_noop!("Drawing, image or sound"), &["svg", "png", "jpg", "jpeg", "wav", "ogg", "mp3"]), + "file.import_to_library" => (tr_noop!("Sound or image"), &["wav", "ogg", "mp3", "png", "jpg", "jpeg"]), + "file.export_audio" => (tr_noop!("WAV sound"), &["wav"]), + "file.export_sprite_sheet" => (tr_noop!("PNG sprite sheet"), &["png"]), + "file.export_video" => (tr_noop!("Video (WebM or MP4)"), &["webm", "mp4"]), // Opening also imports .fla archives and .xfl packages. - "file.open" => ("Documents", &["anicraft", "fla", "xfl"]), - "plugin.install" => ("WebAssembly plug-in", &["wasm"]), - _ => ("AniCraft document", &["anicraft"]), + "file.open" => (tr_noop!("Documents"), &["anicraft", "fla", "xfl"]), + "plugin.install" => (tr_noop!("WebAssembly plug-in"), &["wasm"]), + _ => (tr_noop!("AniCraft document"), &["anicraft"]), } } @@ -248,12 +257,12 @@ pub fn reads_file(cmd: &str) -> bool { matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library") } -/// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal). -/// `None` when cancelled. +/// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal), with +/// `title` already in the interface language. `None` when cancelled. #[cfg(not(target_arch = "wasm32"))] 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); + let (label, d) = (crate::i18n::t(label), rfd::FileDialog::new().set_title(title)); match cmd { c if reads_file(c) => d.add_filter(label, exts).pick_file(), "file.export_png_sequence" => d.pick_folder(), diff --git a/src/plugins_ui.rs b/src/plugins_ui.rs index a8934fab..79d9e43a 100644 --- a/src/plugins_ui.rs +++ b/src/plugins_ui.rs @@ -35,10 +35,10 @@ pub fn load_at_start(app: &mut App) { Ok(v) => { let failed: Vec = v["failed"].as_array().into_iter().flatten().map(|f| format!("{} ({})", f["file"].as_str().unwrap_or(""), f["error"].as_str().unwrap_or(""))).collect(); if !failed.is_empty() { - app.status_err(format!("Some plug-ins could not be loaded: {}", failed.join("; "))); + app.status_err(tr!("Some plug-ins could not be loaded: {list}", list = failed.join("; "))); } } - Err(e) => app.status_err(format!("Plug-ins: {e}")), + Err(e) => app.status_err(tr!("Plug-ins: {error}", error = e)), } } @@ -49,9 +49,9 @@ fn plugin(app: &App, id: &str) -> Option> { /// Why `p` can't run now (it works on the selection and nothing is selected). fn blocked(s: &Session, p: &Plugin) -> Option<&'static str> { if p.manifest().kind == anicraft_engine::plugins::Kind::FrameScript { - return Some("A frame script: it runs while the movie plays. Pick it for a keyframe in the Actions panel (F9)"); + return Some(tr!("A frame script: it runs while the movie plays. Pick it for a keyframe in the Actions panel (F9)")); } - (p.manifest().selection == SelectionNeed::Required && s.selection.is_empty()).then_some("Select some artwork first") + (p.manifest().selection == SelectionNeed::Required && s.selection.is_empty()).then(|| tr!("Select some artwork first")) } /// Plug-ins that run as commands (frame scripts run from keyframes instead). @@ -69,11 +69,11 @@ pub fn label(p: &Plugin) -> String { /// otherwise through its dialog. pub fn run_or_ask(app: &mut App, id: &str) { let Some(p) = plugin(app, id) else { - app.status_err(format!("The plug-in “{id}” is no longer installed")); + app.status_err(tr!("The plug-in “{id}” is no longer installed", id = id)); return; }; if let Some(why) = blocked(&app.s, &p) { - app.status_err(format!("{}: {why}", p.manifest().name)); + app.status_err(tr!("{plugin}: {reason}", plugin = p.manifest().name, reason = why)); return; } if p.manifest().params.is_empty() { @@ -114,11 +114,11 @@ fn preview(app: &mut App) { /// The Commands menu: the installed plug-ins, then the plug-in commands from the registry. pub fn menu(app: &mut App, ui: &mut egui::Ui, cmds: &[CommandSpec], item: impl Fn(&mut App, &mut egui::Ui, &CommandSpec)) { - ui.menu_button("Plug-ins", |ui| { + ui.menu_button(tr!("Plug-ins"), |ui| { ui.set_min_width(220.0); let list: Vec> = app.s.plugins.list().filter(|p| is_command(p)).cloned().collect(); if list.is_empty() { - ui.label(text(Type::Caption, "No plug-ins installed yet")); + ui.label(text(Type::Caption, tr!("No plug-ins installed yet"))); } for p in list { let why = blocked(&app.s, &p); @@ -211,7 +211,7 @@ fn dialog(app: &mut App, ctx: &egui::Context) { ui.label(text(Type::Title, m.name.clone())); let by = [m.author.as_str(), m.version.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" · "); if !by.is_empty() { - ui.label(text(Type::Caption, format!("Plug-in · {by}"))); + ui.label(text(Type::Caption, tr!("Plug-in · {by}", by = by))); } if !m.description.is_empty() { ui.add_space(2.0); @@ -223,7 +223,7 @@ fn dialog(app: &mut App, ctx: &egui::Context) { form_row(ui, FORM_LABEL_DOCK + 40.0, &spec.label, |ui| changed |= control(ui, &spec.label, &spec.kind, v)); } ui.add_space(6.0); - if theme::checkbox(ui, &mut d.preview, "Preview on the stage").changed() { + if theme::checkbox(ui, &mut d.preview, tr!("Preview on the stage")).changed() { changed = true; } if let Some(e) = &d.error { @@ -232,18 +232,18 @@ fn dialog(app: &mut App, ctx: &egui::Context) { } ui.add_space(10.0); ui.horizontal(|ui| { - if ui.add(egui::Button::new("Cancel").min_size(egui::vec2(96.0, TARGET + 4.0))).clicked() { + if ui.add(egui::Button::new(tr!("Cancel")).min_size(egui::vec2(96.0, TARGET + 4.0))).clicked() { cancel = true; } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let run = egui::Button::new(text(Type::Body, "OK").strong()).fill(T.accent_dim).min_size(egui::vec2(96.0, TARGET + 4.0)); + let run = egui::Button::new(text(Type::Body, tr!("OK")).strong()).fill(T.accent_dim).min_size(egui::vec2(96.0, TARGET + 4.0)); if ui.add(run).clicked() { ok = true; } }); }); ui.add_space(2.0); - ui.label(text(Type::Caption, "Enter applies · Esc cancels · one undo step")); + ui.label(text(Type::Caption, tr!("Enter applies · Esc cancels · one undo step"))); }); let (esc, enter) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, Key::Escape), i.consume_key(egui::Modifiers::NONE, Key::Enter))); cancel |= esc; @@ -255,7 +255,7 @@ fn dialog(app: &mut App, ctx: &egui::Context) { app.s.revert_gesture(); app.s.end_gesture(); app.plugin_dialog = None; - app.status_ok("Cancelled"); + app.status_ok(tr!("Cancelled")); } else if ok { finish(app); } @@ -275,17 +275,18 @@ fn finish(app: &mut App) { let name = app.s.plugins.get(&d.id).map_or_else(String::new, |p| p.manifest().name.clone()); app.s.end_gesture(); app.plugin_dialog = None; - app.status_ok(format!("{name} — Ctrl+Z to undo")); + app.status_ok(tr!("{name} — {undo} to undo", name = name, undo = app.undo_key())); } /// Commands › Manage Plug-ins: what's installed, where it came from, and the folder. fn manager(app: &mut App, ctx: &egui::Context) { let mut open = app.show_plugins; let mut action: Option<(&'static str, String)> = None; - let shown = egui::Window::new("Plug-ins").open(&mut open).collapsible(false).resizable(false).default_width(560.0).show(ctx, |ui| { + let title = tr!("Plug-ins"); + let shown = egui::Window::new(title).id(egui::Id::new("plugins_window")).open(&mut open).collapsible(false).resizable(false).default_width(560.0).show(ctx, |ui| { let list: Vec> = app.s.plugins.list().cloned().collect(); if list.is_empty() { - ui.label(text(Type::Label, "No plug-ins installed yet. Plug-ins are WebAssembly (.wasm) files that add commands, such as generators and selection effects.")); + ui.label(text(Type::Label, tr!("No plug-ins installed yet. Plug-ins are WebAssembly (.wasm) files that add commands, such as generators and selection effects."))); } for p in &list { let m = p.manifest(); @@ -295,11 +296,11 @@ fn manager(app: &mut App, ctx: &egui::Context) { ui.label(text(Type::Data, m.version.clone())); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("Remove…").clicked() { + if ui.button(tr!("Remove…")).clicked() { action = Some(("plugin.remove", p.id().to_string())); } let why = blocked(&app.s, p); - let r = ui.add_enabled(why.is_none(), egui::Button::new(if m.params.is_empty() { "Run" } else { "Run…" })); + let r = ui.add_enabled(why.is_none(), egui::Button::new(if m.params.is_empty() { tr!("Run") } else { tr!("Run…") })); if let Some(w) = why { r.on_disabled_hover_text(w); } else if r.clicked() { @@ -310,8 +311,10 @@ fn manager(app: &mut App, ctx: &egui::Context) { if !m.description.is_empty() { ui.label(text(Type::Label, m.description.clone())); } - let by = if m.author.is_empty() { String::new() } else { format!("by {} · ", m.author) }; - ui.label(text(Type::Caption, format!("{by}{} · {} KB", m.id, Plugin::size(p).div_ceil(1024)))); + let kb = Plugin::size(p).div_ceil(1024); + // i18n-exempt: an id and a size (data) + let line = if m.author.is_empty() { format!("{} · {kb} KB", m.id) } else { tr!("by {author} · {id} · {size} KB", author = m.author, id = m.id, size = kb) }; + ui.label(text(Type::Caption, line)); if let Some(src) = p.source() { ui.label(text(Type::Path, src.display().to_string()).color(T.text_faint)); } @@ -319,26 +322,26 @@ fn manager(app: &mut App, ctx: &egui::Context) { } ui.add_space(4.0); let folder = app.s.plugins.folder().map(|f| f.to_path_buf()); - form_row(ui, 96.0, "Folder", |ui| { - ui.label(text(Type::Path, folder.as_ref().map_or_else(|| "none".to_string(), |f| f.display().to_string()))); + form_row(ui, 96.0, tr!("Folder"), |ui| { + ui.label(text(Type::Path, folder.as_ref().map_or_else(|| tr!("none").to_string(), |f| f.display().to_string()))); }); ui.add_space(6.0); ui.horizontal(|ui| { - if ui.button("Install Plug-in…").clicked() { + if ui.button(tr!("Install Plug-in…")).clicked() { action = Some(("plugin.install", String::new())); } - if ui.add_enabled(folder.is_some(), egui::Button::new("Reload")).clicked() { + if ui.add_enabled(folder.is_some(), egui::Button::new(tr!("Reload"))).clicked() { action = Some(("plugin.reload", String::new())); } if let Some(f) = &folder - && ui.add_enabled(f.exists(), egui::Button::new("Show Folder")).clicked() + && ui.add_enabled(f.exists(), egui::Button::new(tr!("Show Folder"))).clicked() { action = Some(("show", f.display().to_string())); } }); - ui.label(text(Type::Caption, "Plug-ins run sandboxed: they can change the open document through AniCraft's commands, never your files.")); + ui.label(text(Type::Caption, tr!("Plug-ins run sandboxed: they can change the open document through AniCraft's commands, never your files."))); }); - a11y::name_title_bar(&shown, "Plug-ins"); + a11y::name_title_bar(&shown, title); app.show_plugins = open; match action { Some(("plugin.run", id)) => run_or_ask(app, &id), @@ -346,7 +349,7 @@ fn manager(app: &mut App, ctx: &egui::Context) { Some(("plugin.install", _)) => app.invoke("plugin.install"), Some(("plugin.reload", _)) => app.invoke("plugin.reload"), Some(("show", f)) => match crate::app::open_in_system(std::path::Path::new(&f)) { - Ok(()) => app.status_ok("Opened the plug-ins folder"), + Ok(()) => app.status_ok(tr!("Opened the plug-ins folder")), Err(e) => app.status_err(e), }, _ => {} @@ -362,20 +365,35 @@ pub fn show(app: &mut App, ctx: &egui::Context) { pub fn status(app: &mut App, id: &str, v: &Value) { match id { "plugin.run" => { - let last = v["log"].as_array().and_then(|l| l.last()).and_then(Value::as_str).map(|m| format!(": {m}")).unwrap_or_default(); - app.status_ok(format!("{}{last} — Ctrl+Z to undo", v["name"].as_str().unwrap_or("Plug-in"))); + // The plug-in's name and its last log line are its own text, shown as written. + let name = v["name"].as_str().unwrap_or(tr!("Plug-in")); + let msg = match v["log"].as_array().and_then(|l| l.last()).and_then(Value::as_str) { + Some(m) => tr!("{name}: {message} — {undo} to undo", name = name, message = m, undo = app.undo_key()), + None => tr!("{name} — {undo} to undo", name = name, undo = app.undo_key()), + }; + app.status_ok(msg); } "plugin.install" => { let i = &v["installed"]; - let verb = if v["replaced"].is_null() { "Installed" } else { "Updated" }; - app.status_ok(format!("{verb} {} {} — find it in Commands › Plug-ins", i["name"].as_str().unwrap_or(""), i["version"].as_str().unwrap_or(""))); + let (name, version) = (i["name"].as_str().unwrap_or(""), i["version"].as_str().unwrap_or("")); + if v["replaced"].is_null() { + app.status_ok(tr!("Installed {name} {version} — find it in Commands › Plug-ins", name = name, version = version)); + } else { + app.status_ok(tr!("Updated {name} {version} — find it in Commands › Plug-ins", name = name, version = version)); + } } - "plugin.remove" => app.status_ok(format!("Removed {}", v["name"].as_str().unwrap_or("the plug-in"))), + "plugin.remove" => match v["name"].as_str() { + Some(name) => app.status_ok(tr!("Removed {name}", name = name)), + None => app.status_ok(tr!("Removed the plug-in")), + }, "plugin.reload" => { let n = v["installed"].as_u64().unwrap_or(0); let failed = v["failed"].as_array().map_or(0, Vec::len); - let msg = format!("{n} plug-in{} installed", if n == 1 { "" } else { "s" }); - if failed > 0 { app.status_err(format!("{msg}; {failed} could not be loaded")) } else { app.status_ok(msg) } + if failed > 0 { + app.status_err(trn!("{n} plug-in installed; {failed} could not be loaded", "{n} plug-ins installed; {failed} could not be loaded", n, failed = failed)); + } else { + app.status_ok(trn!("{n} plug-in installed", "{n} plug-ins installed", n)); + } } _ => {} } diff --git a/src/prefs.rs b/src/prefs.rs index 5c95281b..256bdd5a 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -29,9 +29,9 @@ pub enum RenderMode { 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."), + (RenderMode::Auto, tr_noop!("Auto"), tr_noop!("Edits show immediately; heavy scenes render in the background with an outline preview.")), + (RenderMode::Immediate, tr_noop!("Immediate"), tr_noop!("Every edit renders before the next frame. Lowest latency; can stutter on very heavy scenes.")), + (RenderMode::Background, tr_noop!("Background"), tr_noop!("Always render off the UI thread. The window never waits; the picture can trail by a frame.")), ]; } @@ -49,14 +49,18 @@ pub enum StageRenderer { impl StageRenderer { pub const ALL: [(StageRenderer, &'static str, &'static str); 2] = [ - (StageRenderer::Gpu, "Graphics card (GPU)", "Draws the stage on the graphics card, and on the CPU when there is no card that can. The picture is the same either way."), - (StageRenderer::Cpu, "CPU (reference)", "The reference renderer: slower on large stages. Exports always use it."), + (StageRenderer::Gpu, tr_noop!("Graphics card (GPU)"), tr_noop!("Draws the stage on the graphics card, and on the CPU when there is no card that can. The picture is the same either way.")), + (StageRenderer::Cpu, tr_noop!("CPU (reference)"), tr_noop!("The reference renderer: slower on large stages. Exports always use it.")), ]; } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct Prefs { + /// The interface language (ADR 0040): a craft-i18n locale code (`de`, `pt-br`), or + /// `auto` to follow the system's. A code this build has no catalog for follows the system + /// too, and is kept, so a newer build that has it shows it again. + pub language: String, pub ui_font: FontChoice, pub data_font: FontChoice, /// Graphite or high contrast (ADR 0022). @@ -84,11 +88,45 @@ pub struct Prefs { pub autosave_secs: u32, /// Also make a copy after this many changes (0: by time only). pub autosave_edits: u32, + /// Onion skin options (ADR 0047), kept from session to session. + pub onion: OnionPrefs, +} + +/// Onion skin options that carry over between sessions (ADR 0047). Whether onion skin and Edit +/// Multiple Frames are on, and anchored markers, last for the session only, as in Animate. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct OnionPrefs { + /// Frames before and after the playhead the markers reach (unless Onion All). + pub before: u32, + pub after: u32, + /// Onion All: the markers span the whole timeline. + pub all: bool, + pub tint: bool, + pub fade: bool, + pub outlines: bool, + pub keyframes_only: bool, + /// The markers show on the frame ruler even while onion skin is off. + pub always_markers: bool, + /// The past and future colours the user picked (sRGB); `None`: the theme's. + pub past: Option<[u8; 3]>, + pub future: Option<[u8; 3]>, +} + +/// Most frames a marker reaches from the playhead in the preferences (the timeline's own +/// limit is far beyond what anyone onion-skins). +pub const ONION_REACH_MAX: u32 = 999; + +impl Default for OnionPrefs { + fn default() -> Self { + OnionPrefs { before: 2, after: 2, all: false, tint: true, fade: true, outlines: false, keyframes_only: false, always_markers: false, past: None, future: None } + } } impl Default for Prefs { fn default() -> Self { Prefs { + language: crate::i18n::AUTO.to_string(), ui_font: FontChoice::Bundled, data_font: FontChoice::Bundled, theme: crate::theme::Palette::Graphite, @@ -101,12 +139,13 @@ impl Default for Prefs { autosave: true, autosave_secs: 60, autosave_edits: 25, + onion: OnionPrefs::default(), } } } /// Autosave intervals offered in Preferences: `(seconds, label)`. -pub const AUTOSAVE_INTERVALS: [(u32, &str); 5] = [(30, "30 seconds"), (60, "1 minute"), (120, "2 minutes"), (300, "5 minutes"), (600, "10 minutes")]; +pub const AUTOSAVE_INTERVALS: [(u32, &str); 5] = [(30, tr_noop!("30 seconds")), (60, tr_noop!("1 minute")), (120, tr_noop!("2 minutes")), (300, tr_noop!("5 minutes")), (600, tr_noop!("10 minutes"))]; pub const AUTOSAVE_SECS_RANGE: std::ops::RangeInclusive = 15..=600; pub const AUTOSAVE_EDITS_RANGE: std::ops::RangeInclusive = 0..=1000; @@ -124,9 +163,14 @@ impl Prefs { *f = FontChoice::Bundled; } } + // A locale code is short ASCII (`sr-latn`, `zh-hant`); anything else follows the system. + let lang = self.language.trim().to_ascii_lowercase(); + self.language = if lang.is_empty() || lang.len() > 35 || !lang.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { crate::i18n::AUTO.to_string() } else { lang }; self.shortcuts = crate::keymap::sanitize(std::mem::take(&mut self.shortcuts)); self.autosave_secs = self.autosave_secs.clamp(*AUTOSAVE_SECS_RANGE.start(), *AUTOSAVE_SECS_RANGE.end()); self.autosave_edits = self.autosave_edits.min(*AUTOSAVE_EDITS_RANGE.end()); + self.onion.before = self.onion.before.min(ONION_REACH_MAX); + self.onion.after = self.onion.after.min(ONION_REACH_MAX); self } @@ -209,6 +253,11 @@ mod tests { 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"); + assert_eq!(p.language, "auto", "older files follow the system's language"); + assert_eq!(Prefs::from_json(r#"{"language": " DE "}"#).language, "de"); + assert_eq!(Prefs::from_json(r#"{"language": "xx-new"}"#).language, "xx-new", "a code this build lacks is kept"); + assert_eq!(Prefs::from_json(r#"{"language": "