diff --git a/AUTHORS.md b/AUTHORS.md index f76dba78..c14cf24f 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -8,6 +8,8 @@ People who have contributed to AniCraft. The repository starts from one initial * lienatanael-dev: the live control port and its MCP bridge (#216). * mypenc: skew in Free Transform (#176). * Davit Matchakhelidze (devius): Georgian in the interface, with Noto Sans Georgian (#160). +* Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation; preset files with a byte-order mark, oversized indices, CLI numbers, guide anchors and the Windows build scripts. +* NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; eight-point ovals, smooth anchors that stay smooth when a segment is bent, and non-finite numbers in transforms, paths, scripts and saved files. * Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation. * NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; Trace Bitmap and Convert to Bitmap (#489). * jayzed80: flipped scales in Properties, CLI subcommand help and frame numbering; copy, cut and paste keys on the stage. @@ -20,4 +22,8 @@ People who have contributed to AniCraft. The repository starts from one initial * Koolskull: group registration at the centre of the artwork. * Kushagra Kumar (kk376): drawing with the camera layer hidden. * Oskar Raszkiewicz (oskarraszkiewicz): the macOS menu row. +* Wilder Ccasa (Call4han): fitting the stage by double-clicking the Hand tool (#457). +* Dylan M. Taylor (dylanmtaylor): no caller-chosen ffmpeg over serve and MCP, bounded request lines, safer XFL folder reads. +* Agapenor (Agapenordev): XFL folder paths with backslashes, the frame limit on loaded documents, the report behind the evaluation allowance. +* rcoenen: Animate's shape hints (`morphHintsList`), default text line spacing and default dash gap, from files Animate saved. * Hagai Baram (hrb9): the Hebrew fallback face, `iw` read as Hebrew, and right-to-left language detection (#486). diff --git a/CHANGELOG.md b/CHANGELOG.md index 9da68a76..0fcf40b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,44 @@ ## Unreleased +* **Fixes and hardening from the community** (M8). Thank you to everyone named here. + * **Double-click the Hand tool to fit the stage in the window**, as in Animate; a single click + still only selects the tool (#457, Wilder Ccasa). + * **A new oval has eight points**, one every 45°, as Animate draws it (#459, NetterSilver). + * **Bending an oval's edge with the Selection tool keeps its ends smooth**: the curves beside + the one you drag turn with it, as when a handle is dragged (#460, NetterSilver). + * **Animate documents**, each learned from files Animate saved (rcoenen): shape hints come + across (Animate writes them as `morphHintsList`, which the importer didn't read); text that + leaves `lineSpacing` out gets Animate's 2 px between its lines, not 0; and a dashed stroke + that doesn't name its gap gets Animate's 6 px, not 3. + * **Security: an assistant can't choose the program that makes or reads video.** Over `serve` + and `mcp` (the live bridge too), Export Video, Import Video and every other command refuse + an `ffmpeg` param: set + `ANICRAFT_FFMPEG` yourself. `exec` and `run` keep it. A request line over 64 MiB is answered + with an error instead of growing without bound (Dylan M. Taylor). + * **Security: XFL folders.** A reference that climbs out of the package with backslashes + (`..\x.xml`) is no longer read on Windows (Agapenor); only regular files are read, and never + more than the size cap, however large a file claims to be (Dylan M. Taylor). + * **Security: hostile documents stay bounded.** A file whose keyframes sit past frame 100,000 + opens with them trimmed to the limit commands already keep (Agapenor). A library whose + symbols double at every level (2^32 shapes from 32 symbols) no longer hangs the stage or + runs out of memory: one frame, or one bounds query, visits at most a million elements and + draws what it reached (reported by Agapenor). + * **Never crash:** a scene index or SVG frame number at the top of its range is an error, not + an overflow; a rotation tween between huge or non-finite angles no longer hangs; `--fps` and + `--scale` refuse `NaN`, infinities and numbers too large instead of quietly using the + default (Mex, NetterSilver). + * **Files:** brush sets, filter presets and swatch files saved with a byte-order mark by + Windows editors import. A document that somehow holds a number that isn't finite still + saves to a file that opens again: such a number is written as 0, and a ruined transform as + no transform, where before it made the file unreadable (Mex, NetterSilver). + * **Small things put right:** a colour such as `#+1+2+3` is no longer read as a colour; a + script's Set Property values are clamped whenever a document loads; an object with a zero + x scale keeps its direction when taken apart and put back; guide headings such as "Foo", + "Foo", "Foo-1" get three different links (NetterSilver, Mex). + * **Building on Windows:** the web build and the signing script work from a folder with + square brackets in its name; `i18n-extract.ps1` gives back the caller's + `ANICRAFT_I18N_OUT`; `guide-shots.ps1` takes the document tabs picture too (Mex). * **From outside contributors** (M8; thank you). * **Trace Bitmap and Convert to Bitmap** (by NetterSilver, #489; fixes #463). **Modify › Bitmap › Trace Bitmap…** turns a placed bitmap into filled raw shapes, one per area of @@ -444,6 +482,7 @@ * **Floating windows open below the menu bar**: no dialog (the Custom Ease window among them) can cover File, Edit and View any more. * **Security: safer reads and temp files.** Import to Library checks an image's size (256 MiB) before reading it, and saves, audio exports and the video soundtrack write their temporary files under unguessable names, created exclusively. + * **Saved commands (command macros)** (ADR 0097, M6). * In the **History** panel, **Ctrl+click** steps (Shift+click a range) and choose **Save As Command…**: the steps come back at the end of the **Commands** menu, to run on whatever is diff --git a/crates/actions/src/lib.rs b/crates/actions/src/lib.rs index 7f0eb89f..14e13613 100644 --- a/crates/actions/src/lib.rs +++ b/crates/actions/src/lib.rs @@ -396,7 +396,14 @@ pub fn check_actions(list: &[Action]) -> Result<(), String> { /// Repairs a loaded list: at most [`MAX_ACTIONS`], malformed actions dropped. pub fn sanitize_actions(list: &mut Vec) { - if list.len() > MAX_ACTIONS || list.iter().any(|a| a.check().is_err()) { + let out_of_range = |a: &Action| match a { + Action::SetProperty { property, value, .. } => { + let (lo, hi) = property.range(); + *value < lo || *value > hi + } + _ => false, + }; + if list.len() > MAX_ACTIONS || list.iter().any(|a| a.check().is_err() || out_of_range(a)) { let old = std::mem::take(list); *list = old.into_iter().take(MAX_ACTIONS).filter_map(Action::sanitized).collect(); } @@ -724,6 +731,14 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn sanitize_clamps_set_property_even_when_the_list_is_otherwise_valid() { + let set = |property, value| Action::SetProperty { target: Target::this(), property, value }; + let mut list = vec![set(Property::Alpha, 5.0), set(Property::X, 1e12)]; + sanitize_actions(&mut list); + assert_eq!(list, vec![set(Property::Alpha, 1.0), set(Property::X, Property::X.range().1)]); + } + #[test] fn actions_read_and_write_as_small_json_objects() { let list = vec![ diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 377e0c28..c778aee4 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -89,6 +89,13 @@ impl Args { pub fn num(&self, k: &str) -> Result, String> { self.flag(k).map(|v| v.parse::().map_err(|_| format!("--{k} expects a number, got '{v}'"))).transpose() } + fn float(&self, k: &str) -> Result, String> { + let value = self.num::(k)?; + if value.is_some_and(|v| !v.is_finite()) { + return Err(format!("--{k} expects a finite number")); + } + Ok(value) + } } /// Opens a session from a path or `--sample`. @@ -210,7 +217,7 @@ pub fn run(argv: &[String]) -> Result { let mut s = session(&a, Some(src.ok_or("render needs a file or --sample")?))?; let out = a.flag("out").ok_or("render needs --out ")?; let mut p = json!({"path": out, "frame": one_based(&a, "frame")?.unwrap_or(0)}); - if let Some(sc) = a.num::("scale")? { + if let Some(sc) = a.float("scale")? { p["scale"] = json!(sc); } exec(&mut s, "file.export_png", &p).map(|v| v.to_string()) @@ -225,7 +232,7 @@ pub fn run(argv: &[String]) -> Result { if let Some(t) = one_based(&a, "to")? { p["to"] = json!(t); } - if let Some(sc) = a.num::("scale")? { + if let Some(sc) = a.float("scale")? { p["scale"] = json!(sc); } exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string()) @@ -242,7 +249,7 @@ pub fn run(argv: &[String]) -> Result { if let Some(t) = one_based(&a, "to")? { p["to"] = json!(t); } - if let Some(sc) = a.num::("scale")? { + if let Some(sc) = a.float("scale")? { p["scale"] = json!(sc); } if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") { @@ -274,7 +281,7 @@ pub fn run(argv: &[String]) -> Result { p[k] = json!(v); } } - if let Some(v) = a.num::("fps")? { + if let Some(v) = a.float("fps")? { p["fps"] = json!(v); } exec(&mut s, "file.new", &p)?; @@ -580,6 +587,50 @@ pub fn bench(a: &Args) -> Result { } } +/// Longest request line `serve` and `mcp` read (64 MiB: far above any real command, base64 images included). +pub(crate) const MAX_LINE: usize = 64 << 20; + +/// One input line, read with a bound. +pub(crate) enum Line { + Eof, + Text(String), + TooLong, +} + +/// Reads the next line, never holding more than `max` bytes of it; an overlong line is skipped to its end. +pub(crate) fn read_line(input: &mut R, max: usize) -> std::io::Result { + let mut buf = Vec::new(); + let n = std::io::Read::take(&mut *input, max as u64 + 1).read_until(b'\n', &mut buf)?; + if n == 0 { + return Ok(Line::Eof); + } + if buf.len() > max && buf.last() != Some(&b'\n') { + loop { + let mut skip = Vec::new(); + let k = std::io::Read::take(&mut *input, 1 << 20).read_until(b'\n', &mut skip)?; + if k == 0 || skip.last() == Some(&b'\n') { + return Ok(Line::TooLong); + } + } + } + while matches!(buf.last(), Some(b'\n' | b'\r')) { + buf.pop(); + } + String::from_utf8(buf).map(Line::Text).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) +} + +/// Over `serve` and `mcp` a caller may not name the program a command runs (ADR 0004 spirit: an +/// assistant must not start arbitrary executables); the person sets `ANICRAFT_FFMPEG` instead. +/// Direct CLI use (`exec`, `run`) keeps the `ffmpeg` parameter. Every command that takes one +/// means the same by it (Export Video, Import Video, video info, relinking a layer's video), so +/// the parameter is refused by name: a new command that runs ffmpeg is covered when it is added. +pub(crate) fn refuse_remote_ffmpeg(_cmd: &str, params: &Value) -> Result<(), String> { + if params.get("ffmpeg").is_some_and(|v| !v.is_null()) { + return Err("the ffmpeg parameter is not accepted here: set the ANICRAFT_FFMPEG environment variable to choose the program".into()); + } + Ok(()) +} + /// Answers one JSON request. pub fn handle_request(s: &mut Session, line: &str) -> Value { // Windows shells often prefix piped UTF-8 with a byte-order mark. @@ -595,7 +646,7 @@ pub fn handle_request(s: &mut Session, line: &str) -> Value { let params = req.get("params").cloned().unwrap_or_else(|| json!({})); let result = match cmd { "commands" => Ok(Value::Array(commands().iter().map(|c| c.to_json()).collect())), - _ => s.execute(cmd, ¶ms).map_err(|e| e.to_string()), + _ => refuse_remote_ffmpeg(cmd, ¶ms).and_then(|()| s.execute(cmd, ¶ms).map_err(|e| e.to_string())), }; match result { Ok(v) => json!({"id": id, "ok": true, "result": v, "revision": s.revision, "frame": s.frame}), @@ -607,8 +658,17 @@ pub fn handle_request(s: &mut Session, line: &str) -> Value { pub fn serve(s: &mut Session, input: R, out: &mut W) -> std::io::Result<()> { writeln!(out, "{}", json!({"ready": true, "app": "AniCraft", "version": env!("CARGO_PKG_VERSION")}))?; out.flush()?; - for line in input.lines() { - let line = line?; + let mut input = input; + loop { + let line = match read_line(&mut input, MAX_LINE)? { + Line::Eof => break, + Line::TooLong => { + writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request line too long"}))?; + out.flush()?; + continue; + } + Line::Text(l) => l, + }; if line.trim().is_empty() { continue; } @@ -627,6 +687,29 @@ pub fn serve(s: &mut Session, input: R, out: &mut W) -> st mod tests { use super::*; + #[test] + fn float_flags_reject_nonfinite_values_without_changing_numeric_parsing() { + for key in ["fps", "scale"] { + let flag = format!("--{key}"); + for value in ["NaN", "inf", "+inf", "-inf", "1e40", "-1e40"] { + let args = Args::parse(&[flag.clone(), value.into()]).unwrap(); + assert_eq!(args.float(key).unwrap_err(), format!("--{key} expects a finite number")); + } + for (value, expected) in [("0", 0.0), ("-1", -1.0), ("1.25", 1.25), ("1e2", 100.0)] { + let args = Args::parse(&[flag.clone(), value.into()]).unwrap(); + assert_eq!(args.float(key).unwrap(), Some(expected)); + } + let bad = Args::parse(&[flag.clone(), "oops".into()]).unwrap(); + assert_eq!(bad.float(key).unwrap_err(), format!("--{key} expects a number, got 'oops'")); + assert_eq!(Args::parse(&[]).unwrap().float(key).unwrap(), None); + assert!(Args::parse(&[flag]).is_err()); + } + let integer = Args::parse(&["--frame".into(), "12".into()]).unwrap(); + assert_eq!(integer.num::("frame").unwrap(), Some(12)); + let bad_integer = Args::parse(&["--frame".into(), "NaN".into()]).unwrap(); + assert_eq!(bad_integer.num::("frame").unwrap_err(), "--frame expects a number, got 'NaN'"); + } + /// #226: `info`, `render` and the other subcommands take an Animate document as File › Open /// does (an import, untitled), not only `.anicraft` files. #[test] @@ -638,6 +721,33 @@ mod tests { assert!(info.contains("\"layers\""), "{info}"); } + #[test] + fn serve_refuses_ffmpeg_path_but_exec_keeps_it() { + let mut s = Session::default(); + let r = handle_request(&mut s, r#"{"cmd":"file.export_video","params":{"path":"a.mp4","ffmpeg":"/bin/sh"}}"#); + assert_eq!(r["ok"], false); + assert!(r["error"].as_str().unwrap().contains("ANICRAFT_FFMPEG")); + // Every command that runs ffmpeg takes the same parameter, and none may be given it here. + let takes_it: Vec<&str> = commands().iter().filter(|c| c.params.contains("ffmpeg?")).map(|c| c.id).collect(); + assert!(takes_it.contains(&"file.export_video") && takes_it.contains(&"file.import_video"), "{takes_it:?}"); + for id in takes_it { + let r = handle_request(&mut s, &json!({"cmd": id, "params": {"path": "a.mp4", "ffmpeg": "/bin/sh"}}).to_string()); + assert!(r["error"].as_str().is_some_and(|e| e.contains("ANICRAFT_FFMPEG")), "{id}: {r}"); + } + // Direct CLI use is not filtered: the command runs and fails on the missing program, not on the parameter. + let e = exec(&mut s, "file.export_video", &json!({"path": "a.mp4", "ffmpeg": "/nonexistent/anicraft-ffmpeg"})).unwrap_err(); + assert!(!e.contains("ANICRAFT_FFMPEG environment variable"), "{e}"); + } + + #[test] + fn long_lines_are_bounded() { + let mut input = &b"abcdefghij\nok\r\nxy"[..]; + assert!(matches!(read_line(&mut input, 4).unwrap(), Line::TooLong)); + assert!(matches!(read_line(&mut input, 4).unwrap(), Line::Text(t) if t == "ok")); + assert!(matches!(read_line(&mut input, 4).unwrap(), Line::Text(t) if t == "xy")); + assert!(matches!(read_line(&mut input, 4).unwrap(), Line::Eof)); + } + #[test] fn serve_round_trip() { let mut s = Session::default(); diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 30432f97..bbbcbe6e 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -140,6 +140,7 @@ pub fn call_tool(h: &mut H, name: &str, args: &Value) -> Resul if !params.is_object() { return Err(format!("{id}: \"params\" must be an object")); } + crate::refuse_remote_ffmpeg(id, ¶ms).map_err(|e| format!("{id}: {e}"))?; h.execute(id, ¶ms).map_err(|e| format!("{id}: {e}")) }; Ok(match name { @@ -273,8 +274,17 @@ pub fn handle(s: &mut B, line: &str) -> Option { /// The stdio loop: one message per line in, one reply per line out, until stdin closes. /// Nothing but protocol messages is written to `out` (logs would corrupt the stream). pub fn serve(s: &mut B, input: R, out: &mut W) -> std::io::Result<()> { - for line in input.lines() { - let line = line?; + let mut input = input; + loop { + let line = match crate::read_line(&mut input, crate::MAX_LINE)? { + crate::Line::Eof => break, + crate::Line::TooLong => { + writeln!(out, "{}", json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32600, "message": "request line too long"}}))?; + out.flush()?; + continue; + } + crate::Line::Text(l) => l, + }; if line.trim().is_empty() { continue; } @@ -320,6 +330,18 @@ mod tests { assert_eq!(call(&mut s, 6, "tools/call", json!({"name": "nope"}))["error"]["code"], -32602); } + #[test] + fn mcp_refuses_a_caller_supplied_ffmpeg() { + let mut s = Session::default(); + for r in [ + tool(&mut s, "anicraft_run", json!({"command": "file.export_video", "params": {"path": "a.mp4", "ffmpeg": "/bin/sh"}})), + tool(&mut s, "anicraft_run_script", json!({"steps": [{"command": "file.export_video", "params": {"path": "a.mp4", "ffmpeg": "/bin/sh"}}]})), + ] { + assert_eq!(r["isError"], true); + assert!(r["content"][0]["text"].as_str().unwrap().contains("ANICRAFT_FFMPEG"), "{r}"); + } + } + #[test] fn tools_drive_the_engine() { let mut s = Session::default(); diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 2b7ab1d1..34362e8d 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -7,11 +7,30 @@ use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, La use anicraft_geom::walk::PathWalk; use anicraft_geom::{Affine, FillRule, Path}; use std::borrow::Cow; +use std::cell::Cell; use std::sync::Arc; /// Symbols nested deeper than this are not drawn (guards cyclic libraries). pub const MAX_SYMBOL_DEPTH: usize = 32; +/// Most elements one evaluation (or one bounds query) visits, nested symbols and groups +/// included. The depth cap alone leaves a symbol holding two instances of the next, 32 deep, +/// to expand 2^32 times, which no file may make AniCraft do: past the allowance the rest is +/// left out, so a hostile or damaged document draws in part instead of hanging or running +/// out of memory. Real scenes stay far below it (the heaviest benchmark has 50,000 shapes). +pub const MAX_EVAL_ELEMENTS: u32 = 1_000_000; + +/// Takes one visit from `work`; `false` once the allowance is spent. +pub(crate) fn spend(work: &Cell) -> bool { + match work.get().checked_sub(1) { + Some(left) => { + work.set(left); + true + } + None => false, + } +} + /// One shape to draw, fully resolved to stage space. #[derive(Clone, Debug)] pub struct DisplayItem { @@ -163,7 +182,8 @@ pub fn evaluate(doc: &Document, frame: u32) -> DisplayList { /// applied: what the stage shows while editing (and what picking and bounds use). pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList { let mut out = DisplayList::default(); - eval_timeline(doc, doc.timeline(scene), frame, &Ctx::top(Affine::IDENTITY), &mut out, None); + let work = Cell::new(MAX_EVAL_ELEMENTS); + eval_timeline(doc, doc.timeline(scene), frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None); out } @@ -172,7 +192,8 @@ pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList { /// top-level ones, as a scene's are in [`evaluate_scene`]. pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList { let mut out = DisplayList::default(); - eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY), &mut out, None); + let work = Cell::new(MAX_EVAL_ELEMENTS); + eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None); out } @@ -182,7 +203,8 @@ pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayLi /// skin or Edit Multiple Frames composes its frames (ADR 0051). pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affine) -> DisplayList { let mut out = DisplayList::default(); - eval_timeline(doc, tl, frame, &Ctx::top(xf), &mut out, None); + let work = Cell::new(MAX_EVAL_ELEMENTS); + eval_timeline(doc, tl, frame, &Ctx::top(xf, &work), &mut out, None); out } @@ -192,7 +214,8 @@ pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affin pub fn evaluate_scene_camera(doc: &Document, scene: usize, frame: u32) -> DisplayList { let tl = doc.timeline(scene); let mut out = DisplayList::default(); - eval_timeline(doc, tl, frame, &Ctx::through(tl.camera_at(frame, &doc.stage)), &mut out, None); + let work = Cell::new(MAX_EVAL_ELEMENTS); + eval_timeline(doc, tl, frame, &Ctx::through(tl.camera_at(frame, &doc.stage), &work), &mut out, None); out } @@ -201,9 +224,10 @@ pub fn evaluate_scene_camera(doc: &Document, scene: usize, frame: u32) -> Displa /// through the scene's camera. pub fn evaluate_player(doc: &Document, state: &PlayerState) -> DisplayList { let mut out = DisplayList::default(); + let work = Cell::new(MAX_EVAL_ELEMENTS); let play = Play { state, path: Vec::new() }; let tl = doc.timeline(state.scene); - eval_timeline(doc, tl, state.root.frame, &Ctx::through(tl.camera_at(state.root.frame, &doc.stage)), &mut out, Some(&play)); + eval_timeline(doc, tl, state.root.frame, &Ctx::through(tl.camera_at(state.root.frame, &doc.stage), &work), &mut out, Some(&play)); out } @@ -211,7 +235,8 @@ pub fn evaluate_player(doc: &Document, state: &PlayerState) -> DisplayList { /// clip's artwork, as the player sees it when `play` is given. pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Affine, play: Option<&Play<'_>>) -> DisplayList { let mut out = DisplayList::default(); - let mut cx = Ctx::top(xf); + let work = Cell::new(MAX_EVAL_ELEMENTS); + let mut cx = Ctx::top(xf, &work); cx.depth = 1; cx.stage = false; eval_timeline(doc, tl, frame, &cx, &mut out, play); @@ -576,7 +601,10 @@ fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(an /// What a timeline is evaluated inside of. #[derive(Clone, Copy)] -struct Ctx { +struct Ctx<'a> { + /// The evaluation's allowance of element visits ([`MAX_EVAL_ELEMENTS`]), shared by everything + /// nested in it. + work: &'a Cell, /// Local → stage transform and colour effect of the enclosing instance. xf: Affine, color: ColorTransform, @@ -603,14 +631,14 @@ struct Ctx { slice: Option, } -impl Ctx { - fn top(xf: Affine) -> Ctx { - Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } +impl<'a> Ctx<'a> { + fn top(xf: Affine, work: &'a Cell) -> Ctx<'a> { + Ctx { work, xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } } /// A main timeline seen through `camera`: its tint colours everything. - fn through(camera: Option) -> Ctx { - let mut cx = Ctx::top(Affine::IDENTITY); + fn through(camera: Option, work: &'a Cell) -> Ctx<'a> { + let mut cx = Ctx::top(Affine::IDENTITY, work); cx.stage = false; if let Some(c) = camera { cx.color = c.color(); @@ -672,7 +700,7 @@ fn follow(g: &PathWalk, orient: bool, from: &Affine, to: &Affine, t: f32, tw: Af if out.is_finite() { out } else { tw } } -fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut DisplayList, play: Option<&Play<'_>>) { +fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx<'_>, out: &mut DisplayList, play: Option<&Play<'_>>) { if cx.depth > MAX_SYMBOL_DEPTH { return; } @@ -794,7 +822,11 @@ struct LayerCtx<'a> { xf: Affine, } -fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) { +fn eval_element(doc: &Document, cx: &Ctx<'_>, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) { + // Every element drawn counts, however deep: see MAX_EVAL_ELEMENTS. + if !spend(cx.work) { + return; + } let LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf } = *lc; // In the player, a symbol instance has its own path, and maybe properties a script set. let child = match (&el.kind, play) { @@ -952,7 +984,7 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: }; // A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055). let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s }); - let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice }; + let inner = Ctx { work: cx.work, xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice }; eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref()); } } diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index 304840d3..987ffc60 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -832,3 +832,49 @@ fn keep_area_off_is_bit_exact_with_a_tween_that_never_had_it_and_files_stay_smal let back: Document = serde_json::from_str(&serde_json::to_string(&on).unwrap()).unwrap(); assert!(back.scenes[0].timeline.layers[0].keyframes[0].tween.as_ref().unwrap().keep_area); } + +/// A chain of symbols, each holding two instances of the next and the last one a square: 2^depth +/// squares from `depth` symbols, with no cycle anywhere and no nesting deeper than the cap. +fn doubling_doc(depth: u64) -> Document { + let mut d = Document::default(); + let instance = |id: u64, symbol: u64, x: f32| Element { + id: ElementId(id), + name: String::new(), + transform: Affine::translate(x, 0.0), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, + }; + for level in 0..depth { + let mut layer = Layer::new(LayerId(1000 + level), "l"); + layer.keyframes = vec![Arc::new(Keyframe::new(0, 1))]; + if level + 1 == depth { + push(&mut layer, 0, shape_el(5000, 0.0)); + } else { + push(&mut layer, 0, instance(2000 + level, 101 + level, 0.0)); + push(&mut layer, 0, instance(3000 + level, 101 + level, 1.0)); + } + let timeline = Timeline { layers: vec![Arc::new(layer)] }; + d.library.push(Arc::new(Symbol { id: SymbolId(100 + level), name: format!("s{level}"), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); + } + layer0(&mut d).keyframes = vec![Arc::new(Keyframe::new(0, 1))]; + push(layer0(&mut d), 0, instance(1, 100, 0.0)); + d +} + +/// #13: the depth cap alone lets symbols that double at each level expand without end. One +/// evaluation, and one bounds query, visit at most `MAX_EVAL_ELEMENTS` elements and then stop. +#[test] +fn symbols_that_double_at_each_level_stay_within_the_allowance() { + // Below the allowance nothing is left out: 2^10 squares. + let small = doubling_doc(11); + assert_eq!(evaluate(&small, 0).items.len(), 1 << 10); + assert!(!small.timeline(0).layers[0].keyframes[0].elements[0].bounds(&small).is_empty()); + // 2^30 squares would take minutes and gigabytes; the allowance ends it in well under a second. + let hostile = doubling_doc(31); + let started = std::time::Instant::now(); + let items = evaluate(&hostile, 0).items.len(); + assert!(items > 0 && items <= crate::MAX_EVAL_ELEMENTS as usize, "{items}"); + let bounds = hostile.timeline(0).layers[0].keyframes[0].elements[0].bounds(&hostile); + assert!(!bounds.is_empty(), "what was reached still counts"); + assert!(started.elapsed() < std::time::Duration::from_secs(30), "{:?}", started.elapsed()); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5fd0ca7f..cb3f397e 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -56,7 +56,7 @@ pub use aids::{Aids, GUIDE_REACH, Grid, Guide, GuideAxis, MAX_GUIDES}; pub use nine_slice::symbol_box; pub use rich_text::{BaselineShift, CharStyle, MAX_TEXT_RUNS, MAX_URL, ParagraphStyle, StyleSummary, TextFill, TextRun, safe_url}; 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_shown, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start}; +pub use eval::{DisplayItem, DisplayList, Group, MAX_EVAL_ELEMENTS, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_shown, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; @@ -105,7 +105,7 @@ impl Rgba { pub fn parse_hex(s: &str) -> Option { let s = s.trim(); let h = s.strip_prefix('#').unwrap_or(s); - if !h.is_ascii() || (h.len() != 6 && h.len() != 8) { + if !h.bytes().all(|c| c.is_ascii_hexdigit()) || (h.len() != 6 && h.len() != 8) { return None; } let byte = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| v as f32 / 255.0); @@ -1080,16 +1080,18 @@ impl Element { } /// Local-space bounds (control-point bounds for shapes, `None` for symbols). pub fn local_bounds(&self, doc: &Document) -> Rect { - element_bounds(doc, self, &Affine::IDENTITY, 0) + element_bounds(doc, self, &Affine::IDENTITY, 0, &std::cell::Cell::new(MAX_EVAL_ELEMENTS)) } /// Bounds in the parent's space. pub fn bounds(&self, doc: &Document) -> Rect { - element_bounds(doc, self, &self.transform, 0) + element_bounds(doc, self, &self.transform, 0, &std::cell::Cell::new(MAX_EVAL_ELEMENTS)) } } -fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize) -> Rect { - if depth > MAX_SYMBOL_DEPTH { +/// `work` is the query's allowance of element visits ([`MAX_EVAL_ELEMENTS`]): past it the rest +/// adds nothing, as in evaluation. +fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize, work: &std::cell::Cell) -> Rect { + if depth > MAX_SYMBOL_DEPTH || !eval::spend(work) { return Rect::EMPTY; } match &el.kind { @@ -1102,7 +1104,7 @@ fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize) -> Re ElementKind::Group { .. } => { let mut r = Rect::EMPTY; for child in el.kind.group_members() { - r = r.union(&element_bounds(doc, &child, &xf.mul(&child.transform), depth + 1)); + r = r.union(&element_bounds(doc, &child, &xf.mul(&child.transform), depth + 1, work)); } r } @@ -1113,7 +1115,7 @@ fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize) -> Re if let Some(kf) = layer.keyframes.first() { for child in &kf.elements { let m = xf.mul(&child.transform); - r = r.union(&element_bounds(doc, child, &m, depth + 1)); + r = r.union(&element_bounds(doc, child, &m, depth + 1, work)); } } } @@ -1892,6 +1894,19 @@ impl Default for Stage { /// Largest stage edge accepted from files and commands. pub const MAX_STAGE_EDGE: u32 = 16_384; +/// Last addressable frame (0-based); about 70 minutes at 24 fps. +pub const MAX_FRAME: u32 = 100_000; + +/// Drops keyframes past [`MAX_FRAME`] and trims durations to it (files skip command checks). +fn clamp_frames(l: &mut Layer) { + l.keyframes.retain(|k| k.start <= MAX_FRAME); + for k in &mut l.keyframes { + if k.end() > MAX_FRAME + 1 { + Arc::make_mut(k).duration = MAX_FRAME + 1 - k.start; + } + } +} + /// A scene: one part of the movie with its own main timeline. Scenes play in order. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Scene { @@ -2167,6 +2182,7 @@ impl Document { } let tl = &mut Arc::make_mut(scene).timeline; for l in &mut tl.layers { + clamp_frames(Arc::make_mut(l)); Arc::make_mut(l).normalize(); sanitize_scripts(l); sanitize_depth(l); @@ -2207,6 +2223,7 @@ impl Document { } let tl = &mut Arc::make_mut(sym).timeline; for l in &mut tl.layers { + clamp_frames(Arc::make_mut(l)); Arc::make_mut(l).normalize(); sanitize_scripts(l); // Only a scene has a camera; a symbol's camera layer is kept as a normal layer. @@ -2431,6 +2448,15 @@ mod parenting_tests; mod tests { use super::*; + #[test] + fn hex_with_signs_is_rejected() { + for bad in ["#+1+2+3", "#-1-2-3", "#12345g", "#12345+"] { + assert_eq!(Rgba::parse_hex(bad), None, "{bad}"); + } + assert!(Rgba::parse_hex("#0a1B2c").is_some()); + assert!(Rgba::parse_hex("#0a1B2cFF").is_some()); + } + #[test] fn keyframe_lookup() { let mut l = Layer::new(LayerId(1), "a"); @@ -2507,9 +2533,35 @@ mod tests { d.stage.width = 0; d.stage.fps = f32::NAN; d.next_id = 0; + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = [Keyframe::new(0, u32::MAX), Keyframe::new(u32::MAX - 1, 5)].map(Arc::new).to_vec(); d.sanitize(); + assert_eq!(d.frame_count(), MAX_FRAME + 1, "frames past the limit are dropped or trimmed"); + let keys = &d.timeline(0).layers[0].keyframes; + assert_eq!(keys.len(), 1); + assert_eq!((keys[0].start, keys[0].duration), (0, MAX_FRAME + 1)); assert_eq!(d.stage.width, 1); assert_eq!(d.stage.fps, 24.0); assert!(d.next_id > d.timeline(0).layers[0].id.0); } + + #[test] + fn sanitize_clamps_main_and_symbol_timelines_at_the_inclusive_limit() { + let cases = [ + (vec![Keyframe::new(MAX_FRAME, 10), Keyframe::new(MAX_FRAME + 1, 1)], vec![(MAX_FRAME, 1)]), + (vec![Keyframe::new(0, MAX_FRAME + 1)], vec![(0, MAX_FRAME + 1)]), + (vec![Keyframe::new(0, u32::MAX), Keyframe::new(u32::MAX - 1, 5)], vec![(0, MAX_FRAME + 1)]), + ]; + for (keys, expected) in cases { + let mut d = Document::default(); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = keys.into_iter().map(Arc::new).collect(); + let timeline = d.timeline(0).clone(); + d.library.push(Arc::new(Symbol { id: SymbolId(100), name: "boundary".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); + d.sanitize(); + for timeline in [d.timeline(0), &d.library[0].timeline] { + let actual: Vec<_> = timeline.layers[0].keyframes.iter().map(|k| (k.start, k.duration)).collect(); + assert_eq!(actual, expected); + assert_eq!(timeline.frame_count(), MAX_FRAME + 1); + } + } + } } diff --git a/crates/engine/src/brush_library.rs b/crates/engine/src/brush_library.rs index ba1bb6d5..76afa016 100644 --- a/crates/engine/src/brush_library.rs +++ b/crates/engine/src/brush_library.rs @@ -431,7 +431,8 @@ impl BrushLibrary { /// The presets in a brush set file (bad entries skipped; values clamped). pub fn parse_file(text: &str) -> Result> { - let f: BrushFile = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("not a brush set file: {e}")))?; + let f: BrushFile = + serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| EngineError::Param(format!("not a brush set file: {e}")))?; if f.format != FILE_FORMAT { return Err(EngineError::Param(format!("not a brush set file (its format is '{}')", f.format.chars().take(40).collect::()))); } @@ -483,6 +484,7 @@ mod tests { let mine = vec![BrushPreset { name: "A".into(), curve: PressureCurve::SOFT, jitter: 12.0, ..BrushPreset::default() }, builtin("dotted").unwrap()]; let text = BrushLibrary::file_json(&mine); assert_eq!(BrushLibrary::parse_file(&text).unwrap(), mine); + assert_eq!(BrushLibrary::parse_file(&format!("\u{feff}{text}")).unwrap(), mine); assert!(BrushLibrary::parse_file("{}").is_err()); assert!(BrushLibrary::parse_file(r#"{"format": "other", "version": 1, "brushes": []}"#).is_err()); assert!(BrushLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 99, "brushes": []}"#).is_err()); diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 8948dd62..eb279b83 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -169,7 +169,7 @@ fn draw_rect(s: &mut Session, p: &Value) -> Result { fn draw_ellipse(s: &mut Session, p: &Value) -> Result { let (x, y, w, h) = rect_params(p)?; let (fill, stroke) = style(s, p, true)?; - add_shape(s, "ellipse", Path::ellipse(0.0, 0.0, w / 2.0, h / 2.0), Vec2::new(x + w / 2.0, y + h / 2.0), fill, stroke, object_param(s, p)?) + add_shape(s, "ellipse", Path::ellipse8(0.0, 0.0, w / 2.0, h / 2.0), Vec2::new(x + w / 2.0, y + h / 2.0), fill, stroke, object_param(s, p)?) } fn draw_star(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 04717c06..6e3b671d 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -522,7 +522,7 @@ fn export_svg(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); if frame >= s.frame_count() { - return Err(EngineError::Param(format!("frame {} is past the end (the timeline has {} frames)", frame + 1, s.frame_count()))); + return Err(EngineError::Param(format!("frame {} is past the end (the timeline has {} frames)", u64::from(frame) + 1, s.frame_count()))); } let svg = frame_svg(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame)); crate::vfs::write(&path, svg.as_bytes())?; @@ -907,3 +907,31 @@ fn set_stage(s: &mut Session, p: &Value) -> Result { } Ok(json!({"width": s.doc.stage.width, "height": s.doc.stage.height, "fps": s.doc.stage.fps, "background": s.doc.stage.background.to_hex()})) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn oversized_svg_frame_is_an_error_without_writing() { + // Keep this test's memory-backed files off reused test worker threads. + std::thread::spawn(|| { + crate::vfs::use_memory(); + let mut s = Session::default(); + let info = s.info(); + let path = std::path::Path::new("frame.svg"); + crate::vfs::put(path, b"keep this file".to_vec()).unwrap(); + for (frame, shown) in [(u32::MAX, "4294967296"), (1, "2")] { + let error = s.execute("file.export_svg", &json!({"path": "frame.svg", "frame": frame, "confirm": true})).unwrap_err(); + assert_eq!(error.to_string(), format!("frame {shown} is past the end (the timeline has 1 frames)")); + assert_eq!(crate::vfs::read(path).unwrap(), b"keep this file"); + assert_eq!(s.info(), info); + } + s.execute("file.export_svg", &json!({"path": "frame.svg", "frame": 0, "confirm": true})).unwrap(); + assert!(crate::vfs::read_to_string(path).unwrap().contains(" Result { 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)?; + // Both handles move, so the curves beyond its ends that were smooth there turn with them + // (as when a handle is dragged, ADR 0045), and the ends stay smooth. + let starts = crate::cmds_rawsub::opposite_handle(&els, el, raw, &old, 1); + let ends = crate::cmds_rawsub::opposite_handle(&els, el, raw, &old, 2); + let mut changed = edit_edge(s, id, cmd, &old, &new, raw)?; + let mut turns = Vec::new(); + match (starts, ends) { + // One curve on both ends (a two-segment loop): turn both its handles at once. + (Some(f), Some(g)) if rawgeom::same_edge(&f, &g.reversed(), 1.5 * SNAP) => { + let (a, b) = (f.c[0], f.c[3]); + turns.push((f.c, [a, rawgeom::turned_opposite(a, new[1], f.c[1]), rawgeom::turned_opposite(b, new[2], f.c[2]), b])); + } + (f, g) => { + for (f, h) in [(f, new[1]), (g, new[2])] { + if let Some(f) = f { + let a = f.c[0]; + turns.push((f.c, [a, rawgeom::turned_opposite(a, h, f.c[1]), f.c[2], f.c[3]])); + } + } + } + } + for (was, turned) in turns { + for e in follow_edge(s, (!raw).then_some(id), &was, &turned)? { + if !changed.contains(&e) { + changed.push(e); + } + } + } let point = cubic_point(&new, t.clamp(0.02, 0.98)); if raw && merge_after { remerge_in_place(s, &changed)?; diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs index 93114ea8..58b162ad 100644 --- a/crates/engine/src/cmds_rawsub.rs +++ b/crates/engine/src/cmds_rawsub.rs @@ -403,7 +403,7 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { /// The other curve at the anchor of handle `slot` of `old` (stage space) when the anchor is smooth /// there: the one edge leaving it whose handle lies opposite this one ([`rawgeom::smooth_at`]), in /// any raw shape on the layer (or in `el` alone, a drawing object). Oriented from the anchor. -fn opposite_handle(els: &[Arc], el: &Element, raw: bool, old: &Cubic, slot: usize) -> Option { +pub(crate) fn opposite_handle(els: &[Arc], el: &Element, raw: bool, old: &Cubic, slot: usize) -> Option { let (a, h) = if slot == 1 { (old[0], old[1]) } else { (old[3], old[2]) }; let dragged = rawgeom::Seg { c: if slot == 1 { *old } else { [old[3], old[2], old[1], old[0]] }, line: false }; let tol = 1.5 * SNAP; diff --git a/crates/engine/src/cmds_scene.rs b/crates/engine/src/cmds_scene.rs index 4afdbceb..f48b844e 100644 --- a/crates/engine/src/cmds_scene.rs +++ b/crates/engine/src/cmds_scene.rs @@ -26,7 +26,10 @@ pub fn specs() -> Vec { pub(crate) fn target_scene(s: &Session, p: &Value) -> Result { match opt_u64(p, "scene")? { None => Ok(s.scene), - Some(i) => usize::try_from(i).ok().filter(|i| *i < s.doc.scenes.len()).ok_or_else(|| EngineError::Param(format!("there is no scene {} (the movie has {})", i + 1, s.doc.scenes.len()))), + Some(i) => usize::try_from(i) + .ok() + .filter(|i| *i < s.doc.scenes.len()) + .ok_or_else(|| EngineError::Param(format!("there is no scene {} (the movie has {})", u128::from(i) + 1, s.doc.scenes.len()))), } } @@ -193,3 +196,31 @@ fn step_scene(s: &mut Session, d: i64) -> Result { } Ok(scene_json(s)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn oversized_scene_indices_are_errors_without_edits() { + let mut s = Session::default(); + s.execute("scene.new", &json!({})).unwrap(); + s.execute("draw.rect", &json!({"x": 0, "y": 0, "w": 10, "h": 10})).unwrap(); + let before = s.doc.clone(); + let info = s.info(); + let params = json!({"scene": u64::MAX}); + assert!(s.confirmation("scene.delete", ¶ms).is_none()); + for id in ["scene.select", "scene.duplicate", "scene.rename", "scene.delete", "scene.move_up", "scene.move_down"] { + let mut p = params.clone(); + if id == "scene.rename" { + p["name"] = json!("Renamed"); + } + let error = s.execute(id, &p).unwrap_err(); + assert_eq!(error.to_string(), "there is no scene 18446744073709551616 (the movie has 2)", "{id}"); + assert_eq!(s.doc, before, "{id} changed the document"); + assert_eq!(s.info(), info, "{id} changed the view, revision or history"); + } + assert_eq!(target_scene(&s, &json!({"scene": 0})).unwrap(), 0); + assert_eq!(target_scene(&s, &json!({})).unwrap(), s.scene); + } +} diff --git a/crates/engine/src/cmds_swatch.rs b/crates/engine/src/cmds_swatch.rs index 01697060..7c0d3afe 100644 --- a/crates/engine/src/cmds_swatch.rs +++ b/crates/engine/src/cmds_swatch.rs @@ -253,7 +253,8 @@ pub fn parse_file(text: &str) -> Result> { if text.trim_start_matches('\u{feff}').trim_start().starts_with("GIMP Palette") { return parse_gpl(text).map(|(_, v)| v).map_err(EngineError::Param); } - let v: Value = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("this isn't a swatch file or a GIMP palette ({e})")))?; + let v: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')) + .map_err(|e| EngineError::Param(format!("this isn't a swatch file or a GIMP palette ({e})")))?; if v.get("format").and_then(Value::as_str) != Some(FORMAT) { return Err(EngineError::Param(format!("this JSON isn't a swatch file (its \"format\" must be \"{FORMAT}\")"))); } @@ -300,3 +301,16 @@ fn export(s: &mut Session, p: &Value) -> Result { crate::vfs::write(&path, text.as_bytes())?; Ok(json!({"written": path.display().to_string(), "swatches": s.doc.swatches.len(), "bytes": text.len()})) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_swatch_files_accept_a_utf8_byte_order_mark() { + let text = file_json(&default_set()); + let expected = parse_file(&text).unwrap(); + assert!(!expected.is_empty()); + assert_eq!(parse_file(&format!("\u{feff}{text}")).unwrap(), expected); + } +} diff --git a/crates/engine/src/ellipse_tests.rs b/crates/engine/src/ellipse_tests.rs new file mode 100644 index 00000000..d9691c7f --- /dev/null +++ b/crates/engine/src/ellipse_tests.rs @@ -0,0 +1,20 @@ +//! The Oval tool's default outline has eight nodes, like Animate's. + +use crate::Session; +use anicraft_doc::ElementKind; +use serde_json::json; + +#[test] +fn default_ellipse_has_eight_nodes() { + let mut s = Session::new(anicraft_doc::Document::default()); + s.execute("draw.ellipse", &json!({"x": 10.0, "y": 20.0, "w": 100.0, "h": 60.0})).unwrap(); + let counts: Vec = s + .visible_elements() + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.path.editable_anchors().len()), + _ => None, + }) + .collect(); + assert_eq!(counts, vec![8]); +} diff --git a/crates/engine/src/filter_library.rs b/crates/engine/src/filter_library.rs index 6b33143e..9f756e21 100644 --- a/crates/engine/src/filter_library.rs +++ b/crates/engine/src/filter_library.rs @@ -276,7 +276,8 @@ impl FilterLibrary { /// The presets in a preset file (bad entries skipped; values clamped). pub fn parse_file(text: &str) -> Result> { - let f: PresetFile = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("not a filter preset file: {e}")))?; + let f: PresetFile = + serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| EngineError::Param(format!("not a filter preset file: {e}")))?; if f.format != FILE_FORMAT { return Err(EngineError::Param(format!("not a filter preset file (its format is '{}')", f.format.chars().take(40).collect::()))); } @@ -323,6 +324,7 @@ mod tests { let text = FilterLibrary::file_json(&mine); assert!(text.contains("\"enabled\": false"), "a switched-off filter keeps its switch: {text}"); assert_eq!(FilterLibrary::parse_file(&text).unwrap(), mine); + assert_eq!(FilterLibrary::parse_file(&format!("\u{feff}{text}")).unwrap(), mine); assert!(FilterLibrary::parse_file("{}").is_err()); assert!(FilterLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 1, "presets": []}"#).is_err()); assert!(FilterLibrary::parse_file(r#"{"format": "anicraft-filter-presets", "version": 99, "presets": []}"#).is_err()); diff --git a/crates/engine/src/format.rs b/crates/engine/src/format.rs index 548d050c..2120a515 100644 --- a/crates/engine/src/format.rs +++ b/crates/engine/src/format.rs @@ -5,7 +5,7 @@ use anicraft_doc::{Document, path_table}; use anicraft_geom::Path; use craft_anicraft_format::PayloadDecoder; pub use craft_anicraft_format::{FORMAT_NAME, MAX_FILE_BYTES}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::sync::Arc; /// The newest envelope version this build reads (v1 inline paths; v2 shared path table; v3 @@ -40,11 +40,250 @@ impl PayloadDecoder> for DocumentDecoder { } } +/// Whether `e` has a transform JSON cannot hold (it would write `null`, which no longer loads). +fn bad_transform(e: &Arc) -> bool { + !e.transform.is_finite() +} + +/// Replaces non-finite element transforms with identity, so a ruined transform does not +/// collapse the element to a point. Returns `None`, without copying, when nothing needs repair; +/// otherwise only the scenes, items, layers, keyframes and elements that contain one are cloned. +fn repaired_for_save(doc: &Document) -> Option { + let layer_bad = |l: &Arc| l.keyframes.iter().any(|k| k.elements.iter().any(bad_transform)); + let tl_bad = |t: &anicraft_doc::Timeline| t.layers.iter().any(layer_bad); + if !doc.timelines().any(tl_bad) { + return None; + } + let fix = |t: &mut anicraft_doc::Timeline| { + for l in t.layers.iter_mut().filter(|l| layer_bad(l)) { + for k in Arc::make_mut(l).keyframes.iter_mut().filter(|k| k.elements.iter().any(bad_transform)) { + for e in Arc::make_mut(k).elements.iter_mut().filter(|e| bad_transform(e)) { + Arc::make_mut(e).transform = anicraft_geom::Affine::IDENTITY; + } + } + } + }; + let mut d = doc.clone(); + for s in d.scenes.iter_mut().filter(|s| tl_bad(&s.timeline)) { + fix(&mut Arc::make_mut(s).timeline); + } + for s in d.library.iter_mut().filter(|s| tl_bad(&s.timeline)) { + fix(&mut Arc::make_mut(s).timeline); + } + Some(d) +} + +/// Serializer adapter that writes a non-finite `f32`/`f64` as `0.0` instead of `null`, so one +/// bad number anywhere in the document (a colour, a width, a gradient stop) cannot make the +/// saved file unloadable. `0.0` is a safe stand-in because loading repairs the fields where it +/// would not be valid (`Document::sanitize` resets fps and clamps colours, sizes and camera +/// zoom); element transforms, where zero would collapse the element, are repaired to identity +/// first by `repaired_for_save`. +struct Finite(S); + +/// A value serialized through [`Finite`]. +struct Val<'a, T: ?Sized>(&'a T); + +impl Serialize for Val<'_, T> { + fn serialize(&self, s: S) -> Result { + self.0.serialize(Finite(s)) + } +} + +macro_rules! finite_prims { + ($($f:ident($t:ty)),*) => {$( + fn $f(self, v: $t) -> Result { + self.0.$f(v) + } + )*}; +} + +impl serde::Serializer for Finite { + type Ok = S::Ok; + type Error = S::Error; + type SerializeSeq = Finite; + type SerializeTuple = Finite; + type SerializeTupleStruct = Finite; + type SerializeTupleVariant = Finite; + type SerializeMap = Finite; + type SerializeStruct = Finite; + type SerializeStructVariant = Finite; + + finite_prims!( + serialize_bool(bool), + serialize_i8(i8), + serialize_i16(i16), + serialize_i32(i32), + serialize_i64(i64), + serialize_i128(i128), + serialize_u8(u8), + serialize_u16(u16), + serialize_u32(u32), + serialize_u64(u64), + serialize_u128(u128), + serialize_char(char), + serialize_str(&str), + serialize_bytes(&[u8]) + ); + + fn serialize_f32(self, v: f32) -> Result { + self.0.serialize_f32(if v.is_finite() { v } else { 0.0 }) + } + fn serialize_f64(self, v: f64) -> Result { + self.0.serialize_f64(if v.is_finite() { v } else { 0.0 }) + } + fn serialize_none(self) -> Result { + self.0.serialize_none() + } + fn serialize_some(self, v: &T) -> Result { + self.0.serialize_some(&Val(v)) + } + fn serialize_unit(self) -> Result { + self.0.serialize_unit() + } + fn serialize_unit_struct(self, name: &'static str) -> Result { + self.0.serialize_unit_struct(name) + } + fn serialize_unit_variant(self, name: &'static str, idx: u32, variant: &'static str) -> Result { + self.0.serialize_unit_variant(name, idx, variant) + } + fn serialize_newtype_struct(self, name: &'static str, v: &T) -> Result { + self.0.serialize_newtype_struct(name, &Val(v)) + } + fn serialize_newtype_variant( + self, + name: &'static str, + idx: u32, + variant: &'static str, + v: &T, + ) -> Result { + self.0.serialize_newtype_variant(name, idx, variant, &Val(v)) + } + fn serialize_seq(self, len: Option) -> Result { + self.0.serialize_seq(len).map(Finite) + } + fn serialize_tuple(self, len: usize) -> Result { + self.0.serialize_tuple(len).map(Finite) + } + fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result { + self.0.serialize_tuple_struct(name, len).map(Finite) + } + fn serialize_tuple_variant( + self, + name: &'static str, + idx: u32, + variant: &'static str, + len: usize, + ) -> Result { + self.0.serialize_tuple_variant(name, idx, variant, len).map(Finite) + } + fn serialize_map(self, len: Option) -> Result { + self.0.serialize_map(len).map(Finite) + } + fn serialize_struct(self, name: &'static str, len: usize) -> Result { + self.0.serialize_struct(name, len).map(Finite) + } + fn serialize_struct_variant( + self, + name: &'static str, + idx: u32, + variant: &'static str, + len: usize, + ) -> Result { + self.0.serialize_struct_variant(name, idx, variant, len).map(Finite) + } + fn is_human_readable(&self) -> bool { + self.0.is_human_readable() + } +} + +impl serde::ser::SerializeSeq for Finite { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_element(&mut self, v: &T) -> Result<(), Self::Error> { + self.0.serialize_element(&Val(v)) + } + fn end(self) -> Result { + self.0.end() + } +} +impl serde::ser::SerializeTuple for Finite { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_element(&mut self, v: &T) -> Result<(), Self::Error> { + self.0.serialize_element(&Val(v)) + } + fn end(self) -> Result { + self.0.end() + } +} +impl serde::ser::SerializeTupleStruct for Finite { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_field(&mut self, v: &T) -> Result<(), Self::Error> { + self.0.serialize_field(&Val(v)) + } + fn end(self) -> Result { + self.0.end() + } +} +impl serde::ser::SerializeTupleVariant for Finite { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_field(&mut self, v: &T) -> Result<(), Self::Error> { + self.0.serialize_field(&Val(v)) + } + fn end(self) -> Result { + self.0.end() + } +} +impl serde::ser::SerializeMap for Finite { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_key(&mut self, k: &T) -> Result<(), Self::Error> { + self.0.serialize_key(&Val(k)) + } + fn serialize_value(&mut self, v: &T) -> Result<(), Self::Error> { + self.0.serialize_value(&Val(v)) + } + fn end(self) -> Result { + self.0.end() + } +} +impl serde::ser::SerializeStruct for Finite { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_field(&mut self, key: &'static str, v: &T) -> Result<(), Self::Error> { + self.0.serialize_field(key, &Val(v)) + } + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + self.0.skip_field(key) + } + fn end(self) -> Result { + self.0.end() + } +} +impl serde::ser::SerializeStructVariant for Finite { + type Ok = S::Ok; + type Error = S::Error; + fn serialize_field(&mut self, key: &'static str, v: &T) -> Result<(), Self::Error> { + self.0.serialize_field(key, &Val(v)) + } + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + self.0.skip_field(key) + } + fn end(self) -> Result { + self.0.end() + } +} + pub fn to_json(doc: &Document) -> Result { + let repaired = repaired_for_save(doc); + let doc = repaired.as_ref().unwrap_or(doc); let paths = path_table::build_table(doc); let generator = format!("AniCraft {}", env!("CARGO_PKG_VERSION")); let version = version_for(doc); - path_table::write_with_paths(&paths, || craft_anicraft_format::write_version(version, &generator, &paths, doc)).map_err(|e| EngineError::Format(e.to_string())) + path_table::write_with_paths(&paths, || craft_anicraft_format::write_version(version, &generator, &paths, &Val(doc))).map_err(|e| EngineError::Format(e.to_string())) } pub fn from_json(text: &str) -> Result { @@ -87,6 +326,39 @@ mod tests { use super::*; use anicraft_doc::sample; + #[test] + fn non_finite_element_transform_still_reopens() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mut d = sample::demo(); + let l = Arc::make_mut(&mut Arc::make_mut(&mut d.scenes[0]).timeline.layers[0]); + let k = Arc::make_mut(&mut l.keyframes[0]); + Arc::make_mut(&mut k.elements[0]).transform.m[4] = bad; + let back = from_json(&to_json(&d).unwrap()).unwrap(); + let e = &back.timeline(0).layers[0].keyframes[0].elements[0]; + assert_eq!(e.transform, anicraft_geom::Affine::IDENTITY); + } + } + + #[test] + fn non_finite_stage_fps_still_reopens_as_default() { + for bad in [f32::NAN, f32::INFINITY] { + let mut d = sample::demo(); + d.stage.fps = bad; + let back = from_json(&to_json(&d).unwrap()).unwrap(); + assert_eq!(back.stage.fps, 24.0); + } + } + + #[test] + fn non_finite_colour_still_reopens() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mut d = sample::demo(); + d.stage.background.r = bad; + let back = from_json(&to_json(&d).unwrap()).unwrap(); + assert_eq!(back.stage.background.r, 0.0); + } + } + #[test] fn round_trip_is_lossless() { let d = sample::demo(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 039e2b73..2b9a98b6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -246,7 +246,7 @@ pub use cmds_layer::LAYER_COLORS; const GROUP_REFUSES: &[&str] = &["timeline.", "layer.", "camera.", "bone.", "motion.", "tween.", "frames.", "sound.place", "sound.to_keyframes", "sound.lip_sync", "script.set", "script.clear"]; /// Last addressable frame (0-based); about 70 minutes at 24 fps. -pub const MAX_FRAME: u32 = 100_000; +pub const MAX_FRAME: u32 = anicraft_doc::MAX_FRAME; /// 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; @@ -1459,6 +1459,8 @@ mod editing_tests; #[cfg(test)] mod brush_tests; #[cfg(test)] +mod ellipse_tests; +#[cfg(test)] mod brush_library_tests; #[cfg(test)] mod web_tests; diff --git a/crates/engine/src/raw_tests.rs b/crates/engine/src/raw_tests.rs index 16b4a58e..1e79b96d 100644 --- a/crates/engine/src/raw_tests.rs +++ b/crates/engine/src/raw_tests.rs @@ -148,6 +148,58 @@ fn bending_an_object_bends_only_it() { 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:?}"); } +/// Whether every anchor inside the subpaths of `e` (stage space) is smooth; the first that is +/// not, else. +fn smooth_everywhere(e: &Element) -> Result<(), Vec2> { + let ElementKind::Shape(sh) = &e.kind else { return Ok(()) }; + for sub in anicraft_geom::raw::subpaths(&sh.path.transformed(&e.transform)) { + let n = sub.segs.len(); + for i in 0..n { + if !sub.closed && i + 1 == n { + break; + } + let (a, b) = (sub.segs[i], sub.segs[(i + 1) % n]); + if !anicraft_geom::raw::smooth_at(a.c[3], a.c[2], b.c[1]) { + return Err(a.c[3]); + } + } + } + Ok(()) +} + +#[test] +fn bending_an_oval_edge_keeps_its_smooth_ends_smooth() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.ellipse", json!({"x": 0, "y": 0, "w": 200, "h": 100, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + for e in raw(&s) { + assert_eq!(smooth_everywhere(&e), Ok(()), "smooth before the drag"); + } + // Drag the middle of an arc on the south-east side inward (#460). An oval has a node every + // 45 degrees (#459), so the middle of its first arc is at 22.5. + let (sin, cos) = std::f32::consts::FRAC_PI_8.sin_cos(); + let at = Vec2::new(100.0 + 100.0 * cos, 50.0 + 50.0 * sin); + let r = run(&mut s, "path.bend_segment", json!({"x": at.x, "y": at.y, "dx": -25, "dy": -15})); + let got = Vec2::new(r["x"].as_f64().unwrap_or(0.0) as f32, r["y"].as_f64().unwrap_or(0.0) as f32); + assert!(got.distance(at + Vec2::new(-25.0, -15.0)) < 1e-2, "the grabbed point follows: {r}"); + for e in raw(&s) { + assert_eq!(smooth_everywhere(&e), Ok(()), "the ends of the bent arc stay smooth"); + } +} + +#[test] +fn bending_a_rectangle_side_keeps_its_corners() { + let mut s = rect_session(); + run(&mut s, "path.bend_segment", json!({"x": 50, "y": 0, "dx": 0, "dy": -30})); + // Only the bent side is a curve: no handle beside it was turned. + let curves = |e: &Arc| match &e.kind { + ElementKind::Shape(sh) => sh.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::CubicTo(..))).count(), + _ => 0, + }; + assert!(raw(&s).iter().all(|e| curves(e) <= 1)); +} + // ----- shared points ------------------------------------------------------------------------------ #[test] diff --git a/crates/engine/src/rawsub_tests.rs b/crates/engine/src/rawsub_tests.rs index 014d6b26..f0fd7d90 100644 --- a/crates/engine/src/rawsub_tests.rs +++ b/crates/engine/src/rawsub_tests.rs @@ -114,9 +114,9 @@ fn dragging_a_handle_changes_the_curve_in_both_shapes_that_share_it() { 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 + // A circle of eight arcs: two handles per arc, each listed once although the fill and the // outline both have it. - assert_eq!(handles.len(), 8, "{v}"); + assert_eq!(handles.len(), 16, "{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); diff --git a/crates/geom/src/affine.rs b/crates/geom/src/affine.rs index 5dce8e96..bfbcc2b8 100644 --- a/crates/geom/src/affine.rs +++ b/crates/geom/src/affine.rs @@ -101,15 +101,16 @@ impl Affine { pub fn decompose(&self) -> Decomposed { let [a, b, c, d, e, f] = self.m; let sx = (a * a + b * b).sqrt(); - let rotation = b.atan2(a); let det = a * d - b * c; - let (sy, skew) = if sx > 1e-12 { + let (rotation, sy, skew) = if sx > 1e-12 { let sy = det / sx; // col1 · col2 = sx · sy · skew let skew = if det.abs() > 1e-12 { (a * c + b * d) / det } else { 0.0 }; - (sy, skew) + (b.atan2(a), sy, skew) } else { - ((c * c + d * d).sqrt(), 0.0) + // Degenerate first column: take the rotation from the second column, which + // `compose` maps to (-sin r, cos r) · sy. + ((-c).atan2(d), (c * c + d * d).sqrt(), 0.0) }; Decomposed { tx: e, ty: f, sx, sy, rotation, skew } } @@ -147,12 +148,13 @@ impl Decomposed { /// Component-wise interpolation; rotation takes the shortest arc. pub fn lerp(&self, o: &Decomposed, t: f32) -> Decomposed { let mut dr = o.rotation - self.rotation; - let tau = std::f32::consts::TAU; - while dr > std::f32::consts::PI { - dr -= tau; - } - while dr < -std::f32::consts::PI { - dr += tau; + if dr.is_finite() { + let pi = std::f32::consts::PI; + if dr > pi || dr < -pi { + dr = (dr + pi).rem_euclid(std::f32::consts::TAU) - pi; + } + } else { + dr = 0.0; } Decomposed { tx: crate::lerp(self.tx, o.tx, t), @@ -173,6 +175,14 @@ mod tests { a.m.iter().zip(b.m.iter()).all(|(x, y)| (x - y).abs() < 1e-4) } + #[test] + fn decompose_roundtrip_zero_sx() { + for m in [[0.0, 0.0, -1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 3.0, 4.0], [0.0, 0.0, 2.0, -3.0, 1.0, 1.0]] { + let m = Affine { m }; + assert!(close(&m.decompose().compose(), &m), "{:?}", m.decompose().compose()); + } + } + #[test] fn inverse_roundtrip() { let m = Affine::translate(10.0, -4.0).mul(&Affine::rotate(0.7)).mul(&Affine::scale(2.0, 0.5)); @@ -222,4 +232,22 @@ mod tests { let m = Affine::translate(10.0, 0.0).mul(&Affine::scale(2.0, 2.0)); assert_eq!(m.apply(Vec2::new(1.0, 1.0)), Vec2::new(12.0, 2.0)); } + + #[test] + fn lerp_huge_rotation_terminates() { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let a = Decomposed::default(); + let r: Vec = [1e9_f32, f32::INFINITY, f32::NAN] + .iter() + .map(|&rot| a.lerp(&Decomposed { rotation: rot, ..Default::default() }, 0.5).rotation) + .collect(); + let _ = tx.send(r); + }); + let r = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("lerp did not terminate"); + assert!(r.iter().all(|x| x.is_finite()), "{r:?}"); + let d = Decomposed { rotation: 3.0, ..Default::default() }; + let e = Decomposed { rotation: -3.0, ..Default::default() }; + assert!((d.lerp(&e, 0.5).rotation - std::f32::consts::PI).abs() < 1e-5); + } } diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 676f1730..57d7e091 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -40,7 +40,9 @@ impl Path { use std::fmt::Write; let mut s = String::with_capacity(self.cmds.len() * 16); let pt = |s: &mut String, p: Vec2| { - let _ = write!(s, "{} {}", p.x, p.y); + // Non-finite values would be rejected by `from_svg`; write 0 so a save always reloads. + let f = |v: f32| if v.is_finite() { v } else { 0.0 }; + let _ = write!(s, "{} {}", f(p.x), f(p.y)); }; for c in &self.cmds { match *c { @@ -313,6 +315,28 @@ impl Path { p } + /// Ellipse centred at `(cx, cy)` built from eight cubic arcs (a node every 45 degrees, + /// starting at the right), as the Oval tool draws it. + pub fn ellipse8(cx: f32, cy: f32, rx: f32, ry: f32) -> Path { + // Control-arm length for a 45 degree arc: 4/3 * tan(pi / 16). + const K: f32 = 0.265_216_5; + const STEP: f32 = std::f32::consts::FRAC_PI_4; + let mut p = Path::new(); + p.move_to(Vec2::new(cx + rx, cy)); + for i in 0..8 { + let (s0, c0) = (i as f32 * STEP).sin_cos(); + let (s1, c1) = ((i + 1) as f32 * STEP).sin_cos(); + let end = if i == 7 { Vec2::new(cx + rx, cy) } else { Vec2::new(cx + rx * c1, cy + ry * s1) }; + p.cubic_to( + Vec2::new(cx + rx * (c0 - K * s0), cy + ry * (s0 + K * c0)), + Vec2::new(cx + rx * (c1 + K * s1), cy + ry * (s1 - K * c1)), + end, + ); + } + p.close(); + p + } + /// The PolyStar tool's outline (ADR 0080): a regular polygon of `sides` corners, or a star of /// `sides` points whose inner corners are at [`star_inner_radius`] for `point_size`, centred /// at `(cx, cy)` with the first corner straight up. @@ -628,6 +652,24 @@ mod tests { } } + #[test] + fn non_finite_coordinates_round_trip_as_zero() { + let mut p = Path::default(); + p.cmds.push(PathCmd::MoveTo(Vec2::new(0.0, 0.0))); + p.cmds.push(PathCmd::LineTo(Vec2::new(f32::INFINITY, 1.0))); + p.cmds.push(PathCmd::LineTo(Vec2::new(f32::NAN, f32::NEG_INFINITY))); + let json = serde_json::to_string(&p).unwrap(); + let back: Path = serde_json::from_str(&json).unwrap(); + assert_eq!( + back.cmds, + vec![ + PathCmd::MoveTo(Vec2::new(0.0, 0.0)), + PathCmd::LineTo(Vec2::new(0.0, 1.0)), + PathCmd::LineTo(Vec2::new(0.0, 0.0)), + ] + ); + } + #[test] fn flatten_rect_is_closed_polygon() { let pls = Path::rect(0.0, 0.0, 10.0, 5.0).flatten(&Affine::IDENTITY, 0.1); diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs index 2e136dbe..f6dfdef2 100644 --- a/crates/guide/src/lib.rs +++ b/crates/guide/src/lib.rs @@ -182,9 +182,14 @@ fn heading_text(rest: &[Event]) -> String { fn unique_slug(seen: &mut BTreeMap, text: &str) -> String { let base = slug(text); - let n = seen.entry(base.clone()).or_insert(0); - let id = if *n == 0 { base } else { format!("{base}-{n}") }; - *n += 1; + let mut id = base.clone(); + while seen.contains_key(&id) { + let n = seen.entry(base.clone()).or_insert(0); + *n += 1; + id = format!("{base}-{n}"); + } + // Reserve generated ids too: a literal "Foo-1" must not reuse the second "Foo". + seen.insert(id.clone(), 0); id } diff --git a/crates/guide/src/tests.rs b/crates/guide/src/tests.rs index aab56efe..f60ac4eb 100644 --- a/crates/guide/src/tests.rs +++ b/crates/guide/src/tests.rs @@ -78,6 +78,20 @@ fn slugs_match_github() { assert_eq!(slug("Préférences"), "préférences"); } +#[test] +fn numbered_headings_do_not_reuse_generated_slugs() { + for (headings, expected) in [ + (vec!["Foo", "Foo", "Foo-1", "Foo", "Foo-1"], vec!["foo", "foo-1", "foo-1-1", "foo-2", "foo-1-2"]), + (vec!["Foo-1", "Foo-2", "Foo", "Foo", "Foo"], vec!["foo-1", "foo-2", "foo", "foo-3", "foo-4"]), + (vec!["Préférences", "Préférences", "", "", "-1", "!!!"], vec!["préférences", "préférences-1", "", "-1", "-1-1", "-2"]), + (vec!["Onion skin", "Onion skin"], vec!["onion-skin", "onion-skin-1"]), + ] { + let mut seen = BTreeMap::new(); + let ids: Vec = headings.into_iter().map(|heading| unique_slug(&mut seen, heading)).collect(); + assert_eq!(ids, expected); + } +} + #[test] fn links_become_pages_and_headings_get_ids() { let pages = [Page { file: "index.md", markdown: "# Guide\n\nSee [the timeline](timeline.md#onion-skin) and [web](https://example.com/a.md).\n\n## Same\n\n## Same\n\nraw\n" }, Page { file: "timeline.md", markdown: "# Timeline\n\n## Onion skin\n" }]; diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 91e72edc..12c705ce 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -379,8 +379,10 @@ pub(crate) fn stroke(def: &X, bitmaps: &HashMap, report: &mut _ => Join::Round, }; let miter_limit = native.miter_limit().unwrap_or(anicraft_doc::stroke_style::DEFAULT_MITER_LIMIT); + // Animate leaves out `dash1` and `dash2` at its defaults, 6 and 6 px: the same strokes + // saved by Flash 8–CS4 store both lengths, 6 and 6 where the XFL has neither. let dash = match native.kind() { - NativeStroke::Dashed => Dash::dashed(native.dash1().unwrap_or(6.0), native.dash2().unwrap_or(3.0)), + NativeStroke::Dashed => Dash::dashed(native.dash1().unwrap_or(6.0), native.dash2().unwrap_or(6.0)), NativeStroke::Dotted => Dash::dotted(native.dot_space().unwrap_or(3.0)), NativeStroke::Solid => None, _ => { @@ -772,7 +774,7 @@ impl<'a> Builder<'a> { } // Shape hints sit on both keyframes of a shape tween; they are paired up below. let shape_hints = craft_xfl::shape_hints::ShapeHints::new(f); - if !shape_hints.is_empty() { + if !shape_hints.is_empty() || crate::morph_hints::list(f).next().is_some() { raw_hints.insert(start, self.raw_hints(f)); } // Frame scripts are kept verbatim (ADR 0013 tier 1); those in the subset run. @@ -899,20 +901,26 @@ impl<'a> Builder<'a> { /// hint; it gives its point on this keyframe as `x`/`y` (or `startPoint="x, y"`, or /// `startX`/`startY`), and may carry its end point too (`endPoint`, or `endX`/`endY`); /// otherwise the end comes from the same hint on the next keyframe. Points are in pixels. - /// The order is `index` (or a letter `name`), else the order in the file. + /// The order is `index` (or a letter `name`), else the order in the file. Without + /// `shapeHints`, Animate's own `morphHintsList` is read (`morph_hints`). fn raw_hints(&mut self, frame: &X) -> Vec { + const MAX_LISTED: usize = anicraft_doc::MAX_SHAPE_HINTS * 4; let hints = craft_xfl::shape_hints::ShapeHints::new(frame); - let to_vec = |point: Option| { - point.map(|point| Vec2::new(point.x, point.y)).filter(|point| point.x.abs() < 1e6 && point.y.abs() < 1e6) + let to_vec = |point: Option| point.map(|point| Vec2::new(point.x, point.y)); + let listed: Vec<(Option, Option, Option)> = if hints.is_empty() { + crate::morph_hints::list(frame).take(MAX_LISTED).map(|hint| (None, hint.start, hint.end)).collect() + } else { + hints.iter().take(MAX_LISTED).map(|hint| (hint.index(), to_vec(hint.start_point()), to_vec(hint.end_point()))).collect() }; + let in_range = |point: Option| point.filter(|point| point.x.abs() < 1e6 && point.y.abs() < 1e6); let mut out: Vec = Vec::new(); - for (n, hint) in hints.iter().enumerate().take(anicraft_doc::MAX_SHAPE_HINTS * 4) { - let order = hint.index().unwrap_or(n); - let Some(here) = to_vec(hint.start_point()) else { + for (n, (index, here, end)) in listed.into_iter().enumerate() { + let order = index.unwrap_or(n); + let Some(here) = in_range(here) else { self.report.skip("shape hints without a position"); continue; }; - out.push(RawHint { order, here, end: to_vec(hint.end_point()) }); + out.push(RawHint { order, here, end: in_range(end) }); } out.sort_by_key(|h| h.order); if out.len() > anicraft_doc::MAX_SHAPE_HINTS { @@ -1519,16 +1527,25 @@ pub fn import_path(path: &std::path::Path) -> Result<(Document, Report), XflErro let dir = if meta.is_dir() { path.to_path_buf() } else { path.parent().map(std::path::Path::to_path_buf).unwrap_or_default() }; let read = |p: &str| -> Result>, XflError> { // Only plain relative paths inside the package. - if p.split('/').any(|c| c == ".." || c.is_empty()) || p.contains(':') { + // Backslash too: Windows treats it as a separator, so `..\x` would leave the package. + if p.split(['/', '\\']).any(|c| c == ".." || c.is_empty()) || p.contains(':') { return Ok(None); } let full = dir.join(p); - match std::fs::read(&full) { - Ok(b) if b.len() <= xml::MAX_INPUT => Ok(Some(b)), - Ok(_) => Err(XflError::NotXfl(format!("{p} is too large"))), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(e) => Err(e.into()), + // Regular files only (a symlink to /dev/zero or a secret is not package content), and + // never more than the cap is read, however big the file claims to be. + match std::fs::symlink_metadata(&full) { + Ok(m) if m.is_file() => {} + Ok(_) => return Ok(None), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.into()), } + let mut b = Vec::new(); + std::io::Read::read_to_end(&mut std::io::Read::take(std::fs::File::open(&full)?, xml::MAX_INPUT as u64 + 1), &mut b)?; + if b.len() > xml::MAX_INPUT { + return Err(XflError::NotXfl(format!("{p} is too large"))); + } + Ok(Some(b)) }; import_with(&read) } diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index 118c6562..cd170c45 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -9,6 +9,7 @@ pub mod edges; mod end_record; pub mod import; +mod morph_hints; pub mod text; pub mod video; /// The shared XML reader (`anicraft-xml`), under its old path. diff --git a/crates/xfl/src/morph_hints.rs b/crates/xfl/src/morph_hints.rs new file mode 100644 index 00000000..2acccee3 --- /dev/null +++ b/crates/xfl/src/morph_hints.rs @@ -0,0 +1,108 @@ +//! Shape hints as Animate saves them (ADR 0023). +//! +//! Animate writes a shape tween's hints as a `` on the keyframe that starts the +//! tween, one `` per hint in letter order +//! (`a` first), each record carrying its point on both keyframes. Learned by observing files +//! Animate saved; no Animate code involved. +//! +//! Each coordinate is decimal or `#` hex fixed point (signed 24.8, as in `edges`), in units of +//! 256 twips: `#FFFFFB.FB, #0.84` is (-1029, 132) twips, a vertex of the start shape. `key` is +//! 0 in every file seen and is not read; nor is the `` inside a frame's +//! ``, which was empty in every file seen. +//! +//! craft-xfl's `shape_hints` reads only the `` spelling; this belongs there. + +use crate::xml::Element as X; +use anicraft_geom::Vec2; + +/// One native unit is 256 twips. +const TWIPS_PER_UNIT: f32 = 256.0; +const TWIPS_PER_PIXEL: f32 = 20.0; + +/// One ``: its points in pixels on the start and end keyframes, each `None` when +/// missing or malformed. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct MorphHint { + pub start: Option, + pub end: Option, +} + +/// The hints a frame lists in ``, in file order (any child counts as a hint). +pub(crate) fn list(frame: &X) -> impl Iterator + '_ { + frame.list("morphHintsList").iter().map(|h| MorphHint { start: point(h, "startPoint"), end: point(h, "endPoint") }) +} + +/// A `"x, y"` attribute in pixels. +fn point(hint: &X, name: &str) -> Option { + let mut parts = hint.attr(name)?.split([',', ' ']).filter(|p| !p.trim().is_empty()); + let (x, y) = (number(parts.next()?)?, number(parts.next()?)?); + parts.next().is_none().then(|| Vec2::new(x * TWIPS_PER_UNIT / TWIPS_PER_PIXEL, y * TWIPS_PER_UNIT / TWIPS_PER_PIXEL)) +} + +/// A decimal number, or `#` hex fixed point: up to eight whole digits (two's complement once +/// shifted into 24.8) and up to two fraction digits (a single one is the high nibble). +fn number(s: &str) -> Option { + let s = s.trim(); + let value = match s.strip_prefix('#') { + Some(hex) => { + let (whole, frac) = hex.split_once('.').unwrap_or((hex, "")); + let digits = |d: &str| d.bytes().all(|b| b.is_ascii_hexdigit()); + if !digits(whole) || !digits(frac) || whole.len() > 8 || frac.len() > 2 || (whole.is_empty() && frac.is_empty()) { + return None; + } + let whole = if whole.is_empty() { 0 } else { u32::from_str_radix(whole, 16).ok()? }; + let frac = if frac.is_empty() { 0 } else { u32::from_str_radix(frac, 16).ok()? << if frac.len() == 1 { 4 } else { 0 } }; + (whole.wrapping_shl(8) | frac) as i32 as f32 / 256.0 + } + None => s.parse::().ok()?, + }; + value.is_finite().then_some(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(xml: &str) -> X { + crate::xml::parse(xml.as_bytes()).unwrap() + } + + #[test] + fn reads_hex_and_decimal_points_in_units_of_256_twips() { + let f = frame( + r##" + + + "##, + ); + let hints: Vec<_> = list(&f).collect(); + assert_eq!(hints.len(), 2); + // (-1029, 132) twips; (-965, -2) twips. + assert_eq!(hints[0].start, Some(Vec2::new(-1029.0 / 20.0, 132.0 / 20.0))); + assert_eq!(hints[0].end, Some(Vec2::new(-965.0 / 20.0, -2.0 / 20.0))); + // (10708, 1221) twips; a single fraction digit is the high nibble: #28.A is 0x28A0. + assert_eq!(hints[1].start, Some(Vec2::new(10708.0 / 20.0, 1221.0 / 20.0))); + assert_eq!(hints[1].end, Some(Vec2::new(10400.0 / 20.0, 1280.0 / 20.0))); + } + + #[test] + fn malformed_points_are_none_never_a_panic() { + let bad = [ + "", ",", "1", "1,", "1, 2, 3", "#", "#.", "#G, 0", "#1.234, 0", "#123456789, 0", "nan, 0", "inf, 1", "1e40, 0", "#-1, 0", + "#+1, 0", "🙂, 1", "#FFFFFFFF.FF, #80000000", + ]; + for s in bad { + let f = frame(&format!(r#""#)); + let hint = list(&f).next().unwrap(); + assert_eq!(hint.end, None, "{s:?}"); + // The two largest hex values still decode, to finite numbers. + if s.starts_with("#FFFFFFFF") { + assert!(hint.start.is_some_and(|p| p.x.is_finite() && p.y.is_finite())); + } else { + assert_eq!(hint.start, None, "{s:?}"); + } + } + assert_eq!(list(&frame("")).count(), 0); + assert_eq!(list(&frame("")).count(), 0); + } +} diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 7968e0b4..5ab27f20 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -286,6 +286,26 @@ fn a_fla_archive_imports_the_same() { std::fs::remove_dir(&dir).ok(); } +#[test] +fn folder_import_ignores_backslash_escapes_and_symlinks() { + let dir = std::env::temp_dir().join(format!("anicraft-xfl-path-{}", std::process::id())); + let pkg = dir.join("pkg"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write(dir.join("secret.xml"), DOC).unwrap(); + // A reference that climbs out with backslashes is not read (here it would be the whole document). + std::fs::write(pkg.join("DOMDocument.xml"), "").unwrap(); + let (doc, _) = crate::import_path(&pkg).unwrap(); + assert_eq!(doc.library.len(), 0); + #[cfg(unix)] + { + std::fs::remove_file(pkg.join("DOMDocument.xml")).unwrap(); + std::os::unix::fs::symlink(dir.join("secret.xml"), pkg.join("DOMDocument.xml")).unwrap(); + let e = crate::import_path(&pkg).err().map(|e| e.to_string()); + assert!(e.is_some_and(|e| e.contains("no DOMDocument.xml")), "a symlink is not package content"); + } + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn hostile_packages_fail_cleanly() { let mut files = package(); @@ -434,6 +454,44 @@ fn shape_hints_come_across_in_either_form() { } } +#[test] +fn shape_hints_come_across_as_animate_writes_them() { + // `morphHintsList` on the start keyframe, both points per record, in units of 256 twips: + // (0, 0) and (300, 50) px, the end as hex fixed point and decimal. The list inside + // `MorphShape` is not the artist's and is left alone. + let hint = r##""##; + let doc = hinted_doc(&format!("{hint}{hint}{hint}"), ""); + let (d, report) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap(); + assert!(report.skipped.keys().all(|s| !s.contains("hint")), "{:?}", report.skipped); + let l = &d.timeline(0).layers[0]; + let k = &l.keyframes[0]; + assert_eq!(k.hints.len(), 1); + assert!(k.hints[0].start.distance(anicraft_geom::Vec2::new(0.0, 0.0)) < 1e-3, "{:?}", k.hints[0]); + assert!(k.hints[0].end.distance(anicraft_geom::Vec2::new(300.0, 50.0)) < 1e-3, "{:?}", k.hints[0]); + assert!(anicraft_doc::placed_on(&k.elements, k.hints[0].start).is_some()); + assert!(anicraft_doc::placed_on(&l.keyframes[1].elements, k.hints[0].end).is_some()); + // Either spelling gives the same hints. + let native = hinted_doc(r#""#, ""); + let (n, _) = import(&HashMap::from([("DOMDocument.xml", native)])).unwrap(); + assert_eq!(n.timeline(0).layers[0].keyframes[0].hints, k.hints); +} + +#[test] +fn odd_morph_hints_are_reported_not_fatal() { + let many: String = (0..30).map(|_| r##""##).collect(); + let odd = r##""##; + let doc = hinted_doc(&format!("{odd}{many}"), ""); + let (d, report) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap(); + assert_eq!(d.timeline(0).layers[0].keyframes[0].hints.len(), 26); + assert!(report.skipped.contains_key("shape hints past z"), "{:?}", report.skipped); + assert!(report.skipped.contains_key("shape hints without a position")); + // No end point, and no hints on the end keyframe to take one from. + let doc = hinted_doc(r#""#, ""); + let (d, report) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap(); + assert!(d.timeline(0).layers[0].keyframes[0].hints.is_empty()); + assert!(report.skipped.contains_key("shape hints missing on the end keyframe")); +} + #[test] fn odd_shape_hints_are_reported_not_fatal() { let many: String = (0..30).map(|i| format!(r#""#)).collect(); @@ -637,6 +695,10 @@ fn stroke_caps_joints_dashes_and_dots_come_across() { 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() }); + // Animate's defaults are a 6 px dash and a 6 px gap, each written only when it differs. + assert_eq!(read(r#""#).0.style.dash, Dash::dashed(6.0, 6.0)); + assert_eq!(read(r#""#).0.style.dash, Dash::dashed(6.0, 9.0)); + assert_eq!(read(r#""#).0.style.dash, Dash::dashed(10.0, 6.0)); // No gap draws solid. assert_eq!(read(r#""#).0.style.dash, None); assert_eq!(read(r#""#).0.style.dash, Dash::dotted(5.0)); @@ -834,3 +896,16 @@ fn grouped_instance_is_not_scaled_twice() { assert_eq!(els[0].transform.m, [0.5, 0.0, 0.0, 0.5, 50.0, 50.0]); assert_eq!(outer.transform.m, [1.0, 0.0, 0.0, 1.0, 10.0, 20.0]); } + +#[test] +fn folder_packages_refuse_backslash_paths_that_leave_the_package() { + let dir = std::env::temp_dir().join(format!("anicraft-xfl-escape-{}", std::process::id())); + std::fs::create_dir_all(dir.join("LIBRARY")).unwrap(); + std::fs::write(dir.join("DOMDocument.xml"), r#""#).unwrap(); + // On Windows this lands outside LIBRARY; elsewhere it is a file named `..\Ball.xml`. + std::fs::write(dir.join("LIBRARY/..\\Ball.xml"), BALL).unwrap(); + let (doc, report) = crate::import_path(&dir).unwrap(); + assert!(doc.library.is_empty(), "the escaping path was read"); + assert_eq!(report.skipped.get("missing library files"), Some(&1)); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/xfl/src/text.rs b/crates/xfl/src/text.rs index 9e122c01..813f367d 100644 --- a/crates/xfl/src/text.rs +++ b/crates/xfl/src/text.rs @@ -25,6 +25,12 @@ use std::sync::Arc; /// text fields. pub const GUTTER: f32 = 2.0; +/// The line spacing of a run whose `DOMTextAttrs` leaves `lineSpacing` out (pixels). Animate +/// writes the attribute only when it differs from 2 px: it writes `lineSpacing="0"` for 0, a +/// multi-line field's saved height fits 2 px between its lines, and legacy binary `.fla` files +/// store 40 twips (2 px) for exactly the runs whose XFL leaves it out. +pub const LINE_SPACING: f32 = 2.0; + /// Most runs read from one field. const MAX_RUNS: usize = anicraft_doc::MAX_TEXT_RUNS; @@ -44,7 +50,7 @@ struct Flags { /// PostScript name). fn run_style(attrs: Option>, url: &str, flags: &mut Flags) -> (CharStyle, ParagraphStyle) { let Some(a) = attrs else { - return (CharStyle { size: 12.0, ..CharStyle::default() }, ParagraphStyle::default()); + return (CharStyle { size: 12.0, ..CharStyle::default() }, ParagraphStyle { line_spacing: LINE_SPACING, ..ParagraphStyle::default() }); }; let clamp = |number: Option, lo: f32, hi: f32| number.unwrap_or(0.0).clamp(lo, hi); let align = match a.alignment() { @@ -78,7 +84,7 @@ fn run_style(attrs: Option>, url: &str, flags: indent: clamp(a.indent(), -1000.0, 1000.0), left_margin: clamp(a.left_margin(), 0.0, 1000.0), right_margin: clamp(a.right_margin(), 0.0, 1000.0), - line_spacing: clamp(a.line_spacing(), -1000.0, 1000.0), + line_spacing: a.line_spacing().unwrap_or(LINE_SPACING).clamp(-1000.0, 1000.0), }; (c, p) } diff --git a/crates/xfl/src/text_tests.rs b/crates/xfl/src/text_tests.rs index d995014e..7ea608b6 100644 --- a/crates/xfl/src/text_tests.rs +++ b/crates/xfl/src/text_tests.rs @@ -60,6 +60,24 @@ fn static_text_keeps_its_style_matrix_and_lines() { assert!(item.transform.translation().x > 100.0); } +#[test] +fn line_spacing_left_out_is_two_pixels() { + let Some((fonts, family)) = fonts() else { return }; + // Animate writes `lineSpacing` only when it isn't 2 px (it writes "0" for 0), so a run that + // leaves it out, or has no attributes at all, keeps 2 px between its lines. + let field = |attrs: &str| format!(r#"{}"#, run("One Two", &format!(r#"face="{family}" size="20" {attrs}"#))); + let bare = r#"One Two"#; + let (doc, report) = import_doc(&doc_with(&[field(""), field(r#"lineSpacing="0""#), field(r#"lineSpacing="-3""#), bare.to_string()].concat()), fonts); + let t = texts(&doc); + assert_eq!(t.len(), 4, "{report:?}"); + let spacing: Vec> = t.iter().map(|(_, b)| b.paragraph_styles().iter().map(|p| p.line_spacing).collect()).collect(); + assert_eq!(spacing, [vec![2.0, 2.0], vec![0.0, 0.0], vec![-3.0, -3.0], vec![2.0, 2.0]]); + assert_eq!(t[0].1.line_spacing, crate::text::LINE_SPACING); + // The default opens the lines 2 px further apart than an explicit 0. + let (default, zero) = (t[0].1.box_height, t[1].1.box_height); + assert!((default - zero - 2.0).abs() < 0.01, "{default} vs {zero}"); +} + #[test] fn fixed_width_fields_wrap_and_auto_size_ones_do_not() { let Some((fonts, family)) = fonts() else { return }; diff --git a/docs/adr/0023-shape-hints.md b/docs/adr/0023-shape-hints.md index ddd10f14..183d5821 100644 --- a/docs/adr/0023-shape-hints.md +++ b/docs/adr/0023-shape-hints.md @@ -77,6 +77,12 @@ literature on polygon and Bézier blending. Nothing was copied. the next keyframe's `shapeHints`. Points within 2 px of an edge snap onto it. Hints past `z`, without a position or without an end are reported, never fatal. If real files turn out to use another layout, only this reader changes. + *Update (2026-11-18):* files Animate saves use another layout, a `` on the + tween's start keyframe with one `` per + hint in letter order; coordinates are decimal or `#` hex fixed point in units of 256 twips + (observed: they land exactly on the shapes' edge vertices). The importer reads that list + when a frame has no `shapeHints` (`crates/xfl/src/morph_hints.rs`); both map to the same + hints. ## Consequences diff --git a/docs/guide/workspace.md b/docs/guide/workspace.md index 994a1ae8..3d415d6e 100644 --- a/docs/guide/workspace.md +++ b/docs/guide/workspace.md @@ -208,6 +208,7 @@ lets you change them (see [Preferences, shortcuts and accessibility](preferences | Zoom in | **View › Zoom In** (**Ctrl+=**), or click with the **Zoom** tool (**Z**) | | Zoom out | **View › Zoom Out** (**Ctrl+-**), or **Alt**-click with the Zoom tool | | Fit the whole stage in the window | **View › Fit in Window** (**Ctrl+0**, or **Ctrl+2**) | +| Fit the stage with the mouse | Double-click the **Hand** tool | | See the stage at actual size | **View › 100%** (**Ctrl+1**) | | Jump to a set zoom | the arrow beside the zoom field at the right of the edit bar: Fit in window, 25 % to 800 % | | Type a zoom | click the zoom field, type a percentage (5 to 6400) and press **Enter** | diff --git a/docs/mcp.md b/docs/mcp.md index ca1cc8ea..6cbbdc1b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -84,6 +84,9 @@ unlike `anicraft_run_script` a failing step leaves the document as it was. `macr before confirming. * Commands read and write files with your permissions, at the paths the assistant gives (open, save, import, export), as with the CLI. Only connect clients you trust with those files. +* An assistant can't choose the program that makes or reads video: over `mcp` and `serve`, every + command refuses an `ffmpeg` param (Export Video, Import Video and the rest). Set `ANICRAFT_FFMPEG` yourself, or have ffmpeg on the PATH. (`exec` + and `run`, which you type, keep the param.) * A failing command comes back as a tool result marked as an error, so the assistant can read the message and try again; it never stops the server. * Live (`--bridge`): an edit whose answer was lost (AniCraft closed mid-call) is never sent again, diff --git a/docs/roadmap.md b/docs/roadmap.md index dda0ec7f..b6f7c882 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -21,7 +21,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. **Live control** (ADR 0104, `docs/control-protocol.md`): `anicraft --control ` and `anicraft-cli mcp --bridge ` run the same tools on the open window, on this computer only, with a per-run token in `control.json`. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. **Output polish** (ADR 0095): the playhead follows the sound *heard* (the device's latency taken off, frames dropped rather than drifting; under a frame off over an hour in tests), event sounds play to their end across a loop and after the last frame (Enter stops all), a **monitor volume and mute** in the timeline header (Control › Mute Sounds; the listener's, in preferences, never in exports), **Control › Audio Scrubbing** (a slice of at least 1/20 s), a lost or missing device never crashes (silent playback, one notice, a log line, reopened on the next play; a new default device is followed), and the **web build plays sound through Web Audio**. The device sits behind an `Output` trait, so the clock and mixing paths are tested with a fake one. **Audio to keyframes and auto lip-sync, first slice** (ADR 0114, #332): `anicraft_audio::analysis` gives a sound's loudness per movie frame (RMS, normalised to the loudest frame, gated by a threshold, smoothed by a centred average) and, for speech, one of five mouth shapes per frame (rest, open, wide, round, closed) from band energies of a short FFT sorted by the vowels' public formant values, with no speech recognition; pure, deterministic and bounded (10 minutes of sound: levels in 19 ms, mouths in 135 ms). **Convert Audio to Keyframes** (`sound.to_keyframes`; Modify › Timeline, Properties › Sound) maps the loudness onto an object's scale, alpha, position or rotation offset, or a graphic symbol's first frame, as keyframes or as a motion tween's property curve; **Auto Lip-Sync** (`sound.lip_sync`; also beside Looping in Properties) keys the frames of a graphic symbol of mouth poses, found by its frame labels as the mouth chart template names them; `sound.analyse` reports both headless. One dialog previews everything live (a graph of loudness, threshold, value and key ticks, or a row per mouth; the keys themselves on the stage and timeline), one undo step. Not yet: driving the camera, armature layers or filter values from sound; classic tweens between the keys; more than five mouth shapes (F/V, L and the other consonants are placed by hand) or a script as input; the sound's effect and layer volume in the measured loudness; sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, choosing an output device other than the system's default, `stopAllSounds` as a timeline action. **Importing video** (#369, ADR 0116): File › Import › Import Video… reads any video the user's own ffmpeg reads (found as Export Video finds it; a clear message with how to install it when it is missing; no decoder in AniCraft, pictures cross a pipe as PPM with every size checked and both readers fuzzed). **Frames in the document**: bitmaps on a new layer from the playhead, one keyframe per picture at the document's frame rate (frame step 1–60, largest size, start and length), in a Library folder, with the sound track as a stream sound on its own layer; one undo step. **Reference layer**: a locked guide layer right under the active layer shows the video beneath what is drawn, for tracing, in no export; frames are decoded on demand in runs of 16 on their own thread and kept within 256 MB, the layer's opacity fades it, Layer Properties relinks or removes it. The dialog says up front how many pictures of what size and how much memory, and where a long video is cut (2000 pictures, 1 GB decoded); a progress window with Cancel; cancelling or failing leaves the document unchanged. Headless: `file.import_video`, `file.video_info`, `layer.set_video`. Not yet: sound with a reference layer, moving or scaling the reference with the tools, a reference inside a symbol, video with alpha, collecting footage with the document, compressed storage of the imported sound, video in the web build. | | Documents | **Several open at once** (ADR 0112): tabs above the edit bar, the shown document in `App`, the others parked whole (session, view, autosave) and exchanged in O(1) (0.2 µs median); the engine and the CLI/MCP stay one document per session. Cross-document paste remaps Library ids (`engine::transfer`). Not yet: a tab in its own window, another document's Library in the panel, session restore, a shared undo budget. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (WebP container writing delegates to shared `craft-webp`; APNG framing remains app-local; ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. One damaged bitmap, sound or library symbol is left out and reported rather than refusing the whole file (#226), and a document without a stage colour gets Animate's default white (#163). Archives whose end record overstates the directory's size, as Flash CS5 to Animate write most `.fla` files, open (#356; until the shared reader does it, storytold/craft-libs#1986). Binary `.fla` (Flash CS4 and earlier) is not read and says so (#163, #289: a stretch goal in `requirements.md`, no clean-room reader yet). Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). Shared `craft-xfl` readers now parse filters, shape hints, tween easing, and frame-sound envelopes; AniCraft retains document-model mapping and validation. The XFL schema audit remains in progress, including per-character styles and motion-tween records; **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`): each frame is evaluated, artwork that persists (same layer and element, or the same look on the same layer across keyframes) becomes one shape layer, and what changes is written as **keyframes with Lottie's Bézier eases** (ADR 0089): holds where values stay, eased keys wherever an ease of the document draws the frames exactly (linear, Classic, Bézier, custom curves, Quad/Cubic/Back/Bounce; a key per cubic piece), checked at every frame, and a hold key per frame only where nothing exact exists (Elastic, Sine…, reported once); moving artwork keeps its outline in its own space under an animated group transform (position, rotation, skew, scale), and shape tweens between outlines of one structure are shape keys; a playback parity test plays the file with a Lottie player written from the spec through the oracle at every frame (sample scenes, a movie of every ease, the XFL corpus); files 57–90 % smaller (demo 46.7 → 10.4 kB); one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. **Templates, SVG into the Library and drops on the timeline** (ADR 0065): six built-in templates made in code (banners 728 × 90 and 300 × 250, social square 1080 × 1080 at 30 fps, storyboard 16:9 panels, character turnaround, lip-sync mouth chart) with guides on a locked guide layer, on the start screen and File › New from Template; File › Save as Template keeps the document with a picture in the settings folder by category (replacing and deleting confirm); an SVG dropped on or imported to the Library becomes one graphic symbol named after the file, in the folder under the pointer; a sound dropped on a layer's frame goes onto that keyframe, an image or SVG onto that layer in a keyframe made there if needed, one undo step, with a highlight on the cell. Not yet: exact drop positions on the desktop (eframe 0.36 and 0.37 are on winit 0.30, which gives none during a drag; a drop waits for the first pointer move, else lands mid-view), user template descriptions and renaming, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (WebP container writing delegates to shared `craft-webp`; APNG framing remains app-local; ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. One damaged bitmap, sound or library symbol is left out and reported rather than refusing the whole file (#226), and a document without a stage colour gets Animate's default white (#163). Archives whose end record overstates the directory's size, as Flash CS5 to Animate write most `.fla` files, open (#356; until the shared reader does it, storytold/craft-libs#1986). Binary `.fla` (Flash CS4 and earlier) is not read and says so (#163, #289: a stretch goal in `requirements.md`, no clean-room reader yet). Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). Shared `craft-xfl` readers now parse filters, shape hints, tween easing, and frame-sound envelopes; AniCraft retains document-model mapping and validation. The XFL schema audit remains in progress, including per-character styles and motion-tween records; **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`): each frame is evaluated, artwork that persists (same layer and element, or the same look on the same layer across keyframes) becomes one shape layer, and what changes is written as **keyframes with Lottie's Bézier eases** (ADR 0089): holds where values stay, eased keys wherever an ease of the document draws the frames exactly (linear, Classic, Bézier, custom curves, Quad/Cubic/Back/Bounce; a key per cubic piece), checked at every frame, and a hold key per frame only where nothing exact exists (Elastic, Sine…, reported once); moving artwork keeps its outline in its own space under an animated group transform (position, rotation, skew, scale), and shape tweens between outlines of one structure are shape keys; a playback parity test plays the file with a Lottie player written from the spec through the oracle at every frame (sample scenes, a movie of every ease, the XFL corpus); files 57–90 % smaller (demo 46.7 → 10.4 kB); one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. **Templates, SVG into the Library and drops on the timeline** (ADR 0065): six built-in templates made in code (banners 728 × 90 and 300 × 250, social square 1080 × 1080 at 30 fps, storyboard 16:9 panels, character turnaround, lip-sync mouth chart) with guides on a locked guide layer, on the start screen and File › New from Template; File › Save as Template keeps the document with a picture in the settings folder by category (replacing and deleting confirm); an SVG dropped on or imported to the Library becomes one graphic symbol named after the file, in the folder under the pointer; a sound dropped on a layer's frame goes onto that keyframe, an image or SVG onto that layer in a keyframe made there if needed, one undo step, with a highlight on the cell. Not yet: exact drop positions on the desktop (eframe 0.36 and 0.37 are on winit 0.30, which gives none during a drag; a drop waits for the first pointer move, else lands mid-view), user template descriptions and renaming, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. **Hostile documents stay bounded**: keyframes past frame 100,000 are trimmed on load, and one evaluation or bounds query visits at most a million elements, so symbols that double at every level draw in part instead of hanging (not yet: the same allowance in the player's stepping and the other walks over nested symbols; a note to the artist when artwork was left out). A document holding a non-finite number saves to a file that opens again (the number as 0, a ruined element transform as identity). | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), **Trace Bitmap** and **Convert to Bitmap** in Modify (#463: a placed bitmap becomes filled raw shapes that tile, with Animate's four settings; a selection becomes one Library bitmap in its place; bounded at 4096 × 4096 pixels and 20,000 shapes; not yet: a live preview in the dialog, a progress bar for very large traces, tracing a bitmap fill inside another outline, a resolution choice for Convert to Bitmap), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Data-driven animation | **Data tables that drive animation, first slice** (ADR 0118, #416, #417, #418): numeric **tables kept in the document** as Library items, imported from **CSV, TSV or JSON** (File › Import › Import Data Table; through craft-csv; named columns, gaps, text-only columns left out and reported, a row per frame or a **key column** for a row per keyed time; 256 tables, 100 000 rows, 1 000 000 cells, files up to 32 MB; hostile input refused or cut to the limits), a **table viewer**, **Import Again** that keeps every binding; **bindings** that let a column drive a symbol instance's **X, Y, Scale X, Scale Y, Rotation, Alpha** or **the frame a graphic shows** over a span of frames, with scale, offset, linear or step interpolation and reversed key ranges, edited live in Properties › Data and evaluated purely in `evaluate` (stage, oracle, GPU stage, Test Movie and every export that draws frames agree); **Bake to Keyframes** (every frame looks as it did); `data.*` commands headless, over the CLI and MCP, and for plug-ins (all but reading a file). Not yet: bindings that follow copy, paste and duplicate; baking inside a motion tween and a Lottie export warning for live bindings; editing cells in the viewer, adding and renaming columns; text columns for captions; binding skew, tint, filter values, shapes, text and group members; expressions; audio amplitude into a table. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 44c48dd1..e4799e0b 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -42,7 +42,7 @@ function Find-SignTool { $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue if ($onPath) { return $onPath.Source } $kits = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\bin' - $found = Get-ChildItem -Path $kits -Recurse -Filter signtool.exe -ErrorAction SilentlyContinue | + $found = Get-ChildItem -LiteralPath $kits -Recurse -Filter signtool.exe -ErrorAction SilentlyContinue | Where-Object { $_.FullName -match '\\x64\\signtool\.exe$' } | Sort-Object FullName -Descending | Select-Object -First 1 if (-not $found) { throw 'signtool.exe not found (install the Windows SDK)' } @@ -54,7 +54,7 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } +$Files = $Files | ForEach-Object { (Resolve-Path -LiteralPath $_).Path } $haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) @@ -86,12 +86,12 @@ try { $pkg = Join-Path $tmp 'trusted-signing.zip' $version = $TrustedSigningClient.Version Invoke-WebRequest -Uri "https://www.nuget.org/api/v2/package/Microsoft.Trusted.Signing.Client/$version" -OutFile $pkg - $sha256 = (Get-FileHash -Algorithm SHA256 -Path $pkg).Hash + $sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $pkg).Hash if ($sha256 -ne $TrustedSigningClient.Sha256) { throw "Microsoft.Trusted.Signing.Client $version has SHA-256 $sha256, expected $($TrustedSigningClient.Sha256): refusing to load it" } - Expand-Archive -Path $pkg -DestinationPath (Join-Path $tmp 'client') -Force - $dlib = Get-ChildItem -Path (Join-Path $tmp 'client') -Recurse -Filter Azure.CodeSigning.Dlib.dll | + Expand-Archive -LiteralPath $pkg -DestinationPath (Join-Path $tmp 'client') -Force + $dlib = Get-ChildItem -LiteralPath (Join-Path $tmp 'client') -Recurse -Filter Azure.CodeSigning.Dlib.dll | Where-Object { $_.FullName -match '\\x64\\' } | Select-Object -First 1 if (-not $dlib) { throw 'Azure.CodeSigning.Dlib.dll not found in Microsoft.Trusted.Signing.Client' } $metadata = Join-Path $tmp 'metadata.json' @@ -99,12 +99,12 @@ try { Endpoint = $env:AZURE_SIGNING_ENDPOINT CodeSigningAccountName = $env:AZURE_SIGNING_ACCOUNT CertificateProfileName = $env:AZURE_CERT_PROFILE - } | ConvertTo-Json | Set-Content -Path $metadata -Encoding utf8 + } | ConvertTo-Json | Set-Content -LiteralPath $metadata -Encoding utf8 $ts = if ($env:WINDOWS_TIMESTAMP_URL) { $env:WINDOWS_TIMESTAMP_URL } else { 'http://timestamp.acs.microsoft.com' } Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) } finally { - Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue } diff --git a/packaging/windows/test-sign.ps1 b/packaging/windows/test-sign.ps1 new file mode 100644 index 00000000..45b12fe0 --- /dev/null +++ b/packaging/windows/test-sign.ps1 @@ -0,0 +1,71 @@ +# Run with pwsh. Tests the real signer with dummy material and a fake tool; no network or signing. +param([string] $SignScript = (Join-Path $PSScriptRoot 'sign.ps1')) +$ErrorActionPreference = 'Stop' +$SignScript = (Resolve-Path -LiteralPath $SignScript).Path +foreach ($expectFailure in @($false, $true)) { + $fixture = Join-Path ([IO.Path]::GetTempPath()) ('craft-sign-test-' + [guid]::NewGuid()) + New-Item -ItemType Directory -Path $fixture | Out-Null + try { + $temporaryRoot = Join-Path $fixture 'temp[1]' + $siblingRoot = Join-Path $fixture 'temp1' + [IO.Directory]::CreateDirectory($temporaryRoot) | Out-Null + $artifact = Join-Path $fixture 'artifact[1].exe' + [IO.File]::WriteAllText($artifact, 'Synthetic artifact; never executed') + [IO.File]::WriteAllText((Join-Path $fixture 'artifact1.exe'), 'Wrong artifact') + $calls = Join-Path $fixture 'calls.txt' + $fakeTool = Join-Path $fixture 'fake-signtool.ps1' + [IO.File]::WriteAllText($fakeTool, @' +param([Parameter(ValueFromRemainingArguments = $true)][string[]] $Arguments) +if ($Arguments[-1] -cne $env:CRAFT_SIGN_TEST_ARTIFACT) { throw 'Wrong artifact passed to signtool' } +[IO.File]::AppendAllLines($env:CRAFT_SIGN_TEST_CALLS, [string[]]@($Arguments[0])) +if ($Arguments[0] -eq 'sign') { + $certificate = $Arguments[[Array]::IndexOf($Arguments, '/f') + 1] + $generated = [IO.Path]::GetDirectoryName($certificate) + $sibling = Join-Path $env:CRAFT_SIGN_TEST_SIBLING ([IO.Path]::GetFileName($generated)) + [IO.Directory]::CreateDirectory($sibling) | Out-Null + [IO.File]::WriteAllText((Join-Path $sibling 'preserve.txt'), 'Keep the matching sibling') +} +$global:LASTEXITCODE = [int]$env:CRAFT_SIGN_TEST_EXIT +'@) + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = Join-Path $PSHOME 'pwsh.exe' + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + foreach ($argument in @('-NoProfile', '-File', $SignScript, $artifact)) { $start.ArgumentList.Add($argument) } + foreach ($name in @('WINDOWS_CERTIFICATE_PASSWORD', 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE')) { + $start.Environment.Remove($name) | Out-Null + } + $start.Environment['WINDOWS_CERTIFICATE'] = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Synthetic PFX; not a certificate or secret')) + $start.Environment['SIGNTOOL'] = $fakeTool + $start.Environment['TMP'] = $temporaryRoot + $start.Environment['TEMP'] = $temporaryRoot + $start.Environment['CRAFT_SIGN_TEST_ARTIFACT'] = $artifact + $start.Environment['CRAFT_SIGN_TEST_CALLS'] = $calls + $start.Environment['CRAFT_SIGN_TEST_SIBLING'] = $siblingRoot + $start.Environment['CRAFT_SIGN_TEST_EXIT'] = if ($expectFailure) { '42' } else { '0' } + $process = [Diagnostics.Process]::Start($start) + $output = $process.StandardOutput.ReadToEnd() + $errorOutput = $process.StandardError.ReadToEnd() + $process.WaitForExit() + $code = $process.ExitCode + $process.Dispose() + if (($code -eq 0) -eq $expectFailure) { throw "Unexpected exit ${code}: $output $errorOutput" } + $operations = [IO.File]::ReadAllLines($calls) -join ',' + $expected = if ($expectFailure) { 'sign' } else { 'sign,verify' } + if ($operations -ne $expected) { throw "Expected fake operations $expected, got $operations" } + $leftovers = @(Get-ChildItem -LiteralPath $temporaryRoot) + $markers = @(Get-ChildItem -LiteralPath $siblingRoot -Recurse -Filter preserve.txt -ErrorAction SilentlyContinue) + if ($leftovers.Count -ne 0 -or $markers.Count -ne 1) { + throw "Cleanup regression: $($leftovers.Count) temporary entries, $($markers.Count) matching sibling markers" + } + Write-Output "PASS exact artifact and cleanup paths (signing failure: $expectFailure)" + } finally { + $target = Get-Item -LiteralPath $fixture + if ($target.FullName -ne [IO.Path]::GetFullPath($fixture) -or ($target.Attributes -band [IO.FileAttributes]::ReparsePoint)) { + throw 'Unexpected test cleanup target' + } + Remove-Item -LiteralPath $target.FullName -Recurse -Force + } +} diff --git a/scripts/build-web.ps1 b/scripts/build-web.ps1 index 087fab99..e9e2b929 100644 --- a/scripts/build-web.ps1 +++ b/scripts/build-web.ps1 @@ -14,12 +14,12 @@ param([switch]$Dev) $ErrorActionPreference = 'Stop' $Root = Split-Path -Parent $PSScriptRoot -Set-Location $Root +Set-Location -LiteralPath $Root $CargoProfile = if ($Dev) { 'dev' } else { 'web' } # The CLI and the crate must be the same version, or the generated glue doesn't match. -$lock = Get-Content -Raw (Join-Path $Root 'Cargo.lock') +$lock = Get-Content -Raw -LiteralPath (Join-Path $Root 'Cargo.lock') $m = [regex]::Match($lock, '(?m)^name = "wasm-bindgen"\r?\nversion = "([^"]+)"') if (-not $m.Success) { throw 'Cargo.lock names no wasm-bindgen version' } $Want = $m.Groups[1].Value @@ -43,16 +43,16 @@ $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Pa $Dir = if ($Dev) { 'debug' } else { $CargoProfile } $Wasm = Join-Path $TargetDir "wasm32-unknown-unknown\$Dir\anicraft.wasm" $Out = Join-Path $Root 'web' -if (Test-Path $Out) { Remove-Item -Recurse -Force $Out } +if (Test-Path -LiteralPath $Out) { Remove-Item -Recurse -Force -LiteralPath $Out } New-Item -ItemType Directory -Force $Out | Out-Null & wasm-bindgen --target web --no-typescript --out-dir $Out --out-name anicraft $Wasm if ($LASTEXITCODE -ne 0) { throw 'wasm-bindgen failed' } -Copy-Item (Join-Path $Root 'packaging\web\index.html') (Join-Path $Out 'index.html') -Copy-Item (Join-Path $Root 'assets\app-icon\hicolor\128x128\apps\ai.storyteller.anicraft.png') (Join-Path $Out 'anicraft.png') +Copy-Item -LiteralPath (Join-Path $Root 'packaging\web\index.html') -Destination (Join-Path $Out 'index.html') +Copy-Item -LiteralPath (Join-Path $Root 'assets\app-icon\hicolor\128x128\apps\ai.storyteller.anicraft.png') -Destination (Join-Path $Out 'anicraft.png') # The user guide beside the editor: Help › User Guide opens guide/index.html (ADR 0069). cargo run -q -p anicraft-cli -- guide --out (Join-Path $Out 'guide') if ($LASTEXITCODE -ne 0) { throw 'writing the user guide failed' } -$Bytes = (Get-Item (Join-Path $Out 'anicraft_bg.wasm')).Length +$Bytes = (Get-Item -LiteralPath (Join-Path $Out 'anicraft_bg.wasm')).Length Write-Host ("web\ is ready: anicraft_bg.wasm is {0} KB." -f [math]::Floor($Bytes / 1024)) Write-Host 'Serve it locally, for example: python -m http.server --directory web 8080 (then open http://localhost:8080)' diff --git a/scripts/guide-shots.ps1 b/scripts/guide-shots.ps1 index c692b02a..21eaf4d2 100644 --- a/scripts/guide-shots.ps1 +++ b/scripts/guide-shots.ps1 @@ -22,6 +22,7 @@ if (-not (Test-Path $App)) { Write-Error "$App was not built" } # picture name, then the --open state ("-" for the window as it starts) $Shots = @( @("workspace", "-"), + @("document-tabs", "tabs"), @("start-screen", "start"), @("library", "library"), @("onion-skin", "timelinepolish"), diff --git a/scripts/i18n-extract.ps1 b/scripts/i18n-extract.ps1 index b40925d8..5fc81513 100644 --- a/scripts/i18n-extract.ps1 +++ b/scripts/i18n-extract.ps1 @@ -9,12 +9,13 @@ $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 } +$previousOut = $env:ANICRAFT_I18N_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 + $env:ANICRAFT_I18N_OUT = $previousOut Pop-Location } diff --git a/scripts/test-build-web.ps1 b/scripts/test-build-web.ps1 new file mode 100644 index 00000000..5b894d1b --- /dev/null +++ b/scripts/test-build-web.ps1 @@ -0,0 +1,68 @@ +# Exercises the actual web-build script without compiling Rust or running wasm-bindgen. +# Usage: pwsh scripts/test-build-web.ps1 +param([string]$BuildScript = (Join-Path $PSScriptRoot 'build-web.ps1')) +$ErrorActionPreference = 'Stop' +$source = [IO.File]::ReadAllText($BuildScript) +$scratch = Join-Path $PSScriptRoot ('web-path-check-' + [guid]::NewGuid().ToString('N')) +$previousTarget = $env:CARGO_TARGET_DIR +$previousLocation = Get-Location +function Assert([bool]$Condition, [string]$Message) { + if (-not $Condition) { throw $Message } +} +function cargo { + Assert ((Get-Location).Path -eq $checkout) "cargo ran outside the literal checkout: $(Get-Location) expected $checkout" + $calls.Add(@($args)) + if ($args[0] -eq 'run') { + $out = $args[-1] + New-Item -ItemType Directory -Force -Path $out | Out-Null + Set-Content -LiteralPath (Join-Path $out 'index.html') -Value 'guide' + } + $global:LASTEXITCODE = 0 +} +function rustup { 'wasm32-unknown-unknown'; $global:LASTEXITCODE = 0 } +function wasm-bindgen { + $global:LASTEXITCODE = 0 + if ($args[0] -eq '--version') { 'wasm-bindgen 0.2.100'; return } + $out = $args[[array]::IndexOf($args, '--out-dir') + 1] + Assert ($args[-1] -eq $expectedWasm) 'wrong wasm input' + Set-Content -LiteralPath (Join-Path $out 'anicraft_bg.wasm') -Value 'wasm' + Set-Content -LiteralPath (Join-Path $out 'anicraft.js') -Value 'glue' +} +try { + foreach ($dev in @($false, $true)) { + $script:checkout = [IO.Path]::GetFullPath((Join-Path $scratch ('checkout[1]-' + $dev))) + $neighbor = Join-Path $scratch ('checkout1-' + $dev) + foreach ($dir in @('scripts', 'packaging/web', 'assets/app-icon/hicolor/128x128/apps', 'web')) { + New-Item -ItemType Directory -Force -Path (Join-Path $checkout $dir) | Out-Null + } + New-Item -ItemType Directory -Force -Path (Join-Path $neighbor 'web') | Out-Null + Set-Content -LiteralPath (Join-Path $neighbor 'web/keep.txt') -Value 'neighbor' + Set-Content -LiteralPath (Join-Path $checkout 'web/stale.txt') -Value 'stale' + Set-Content -LiteralPath (Join-Path $checkout 'Cargo.lock') -Value "name = `"wasm-bindgen`"`nversion = `"0.2.100`"" + Set-Content -LiteralPath (Join-Path $checkout 'packaging/web/index.html') -Value 'editor' + Set-Content -LiteralPath (Join-Path $checkout 'assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png') -Value 'icon' + $scriptPath = Join-Path $checkout 'scripts/build-web.ps1' + [IO.File]::WriteAllText($scriptPath, $source) + $env:CARGO_TARGET_DIR = if ($dev) { Join-Path $scratch 'target[2]' } else { $null } + $target = if ($dev) { $env:CARGO_TARGET_DIR } else { Join-Path $checkout 'target' } + $profileDir = if ($dev) { 'debug' } else { 'web' } + $script:expectedWasm = Join-Path $target "wasm32-unknown-unknown/$profileDir/anicraft.wasm" + $calls = [Collections.Generic.List[object]]::new() + & $scriptPath -Dev:$dev + Assert ($calls.Count -eq 2 -and $calls[0][0] -eq 'build' -and $calls[1][0] -eq 'run') 'missing build or guide call' + Assert ($calls[0][-1] -eq $(if ($dev) { 'dev' } else { 'web' })) 'wrong cargo profile' + foreach ($file in @('index.html', 'anicraft.png', 'anicraft.js', 'anicraft_bg.wasm', 'guide/index.html')) { + Assert (Test-Path -LiteralPath (Join-Path $checkout "web/$file")) "missing output $file" + } + Assert (-not (Test-Path -LiteralPath (Join-Path $checkout 'web/stale.txt'))) 'stale output remains' + Assert ((Get-Content -Raw -LiteralPath (Join-Path $neighbor 'web/keep.txt')).Trim() -eq 'neighbor') 'neighbor changed' + } + 'PASS: release/dev builds use literal checkout/output paths and preserve wildcard neighbors' +} finally { + Set-Location -LiteralPath $previousLocation.Path + $env:CARGO_TARGET_DIR = $previousTarget + $base = [IO.Path]::GetFullPath($PSScriptRoot) + [IO.Path]::DirectorySeparatorChar + $owned = [IO.Path]::GetFullPath($scratch) + if (-not $owned.StartsWith($base, [StringComparison]::OrdinalIgnoreCase)) { throw 'scratch escaped test directory' } + if (Test-Path -LiteralPath $owned) { Remove-Item -LiteralPath $owned -Recurse -Force } +} diff --git a/src/panels.rs b/src/panels.rs index 0143028f..5bb9adb3 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -102,6 +102,10 @@ pub fn tools(app: &mut App, ui: &mut egui::Ui, flow: ToolFlow) { fn tool_items(app: &mut App, ui: &mut egui::Ui, area: Rect, flow: ToolFlow) { for tool in Tool::ALL { let (rect, resp) = ui.allocate_exact_size(vec2(TOOL_BUTTON, TOOL_BUTTON), Sense::click()); + #[cfg(test)] + if tool == Tool::Hand { + ui.ctx().data_mut(|data| data.insert_temp(egui::Id::new("test_hand_tool_rect"), rect)); + } let active = app.tool == tool; // The active tool sits on a lighter gray block with a white icon; the rest are a // step dimmer, so the one in hand stands out without colour. @@ -130,6 +134,10 @@ fn tool_items(app: &mut App, ui: &mut egui::Ui, area: Rect, flow: ToolFlow) { if resp.clicked() { app.tool = tool; } + // #457: the Hand tool's double-click uses the same fit as View > Fit in Window. + if tool == Tool::Hand && resp.double_clicked() { + app.view.fit = true; + } // Animate: double-clicking the Eraser erases everything on the stage (it asks first). if tool == Tool::Eraser && resp.double_clicked() { crate::erasertool::erase_everything(app); @@ -3468,6 +3476,60 @@ pub(crate) fn library(app: &mut App, ui: &mut egui::Ui) { mod tests { use super::*; + #[test] + fn double_clicking_the_hand_tool_fits_the_stage_but_a_single_click_only_selects_it() { + for flow in [ToolFlow::Column, ToolFlow::Row, ToolFlow::Grid] { + for zoom in [0.1, 8.0] { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(std::path::PathBuf::from("unused.png"))); + app.view.fit = false; + app.view.fitted = None; + app.view.zoom = zoom; + app.view.pan = vec2(120.0, -80.0); + let state = app.s.state; + let mut time = 0.0; + let mut draw = |app: &mut App, events| { + time += 0.05; + let input = egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1400.0))), + time: Some(time), + events, + ..Default::default() + }; + ctx.run_ui(input, |ui| tools(app, ui, flow)).textures_delta.clear(); + }; + draw(&mut app, Vec::new()); + let rect = ctx.data(|data| data.get_temp::(egui::Id::new("test_hand_tool_rect"))).expect("Hand tool drawn"); + let at = rect.center(); + let event = |pressed| vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ]; + draw(&mut app, event(true)); + draw(&mut app, event(false)); + assert_eq!(app.tool, Tool::Hand); + assert!(!app.view.fit, "a single click must not fit the view"); + assert_eq!(app.view.zoom, zoom); + assert_eq!(app.view.pan, vec2(120.0, -80.0)); + draw(&mut app, event(true)); + draw(&mut app, event(false)); + assert!(app.view.fit, "double-click must request Fit in Window ({flow:?})"); + for _ in 0..3 { + let input = egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1400.0))), + ..Default::default() + }; + ctx.run_ui(input, |ui| app.frame(ui)).textures_delta.clear(); + } + assert_eq!(app.view.pan, egui::Vec2::ZERO); + let canvas = app.stage_cache.canvas; + let size = vec2(app.s.doc.stage.width as f32, app.s.doc.stage.height as f32); + assert!(size.x * app.view.zoom <= canvas.width() && size.y * app.view.zoom <= canvas.height()); + assert_eq!(app.s.state, state, "fitting is view state, not a document edit"); + } + } + } + /// #252: the Pencil and the Line tool never fill, whatever the fill swatch says, so their /// Properties show no Fill row; the Pen and the shape tools still fill. #[test] diff --git a/src/stage_a11y.rs b/src/stage_a11y.rs index 6ea90309..5da4517e 100644 --- a/src/stage_a11y.rs +++ b/src/stage_a11y.rs @@ -96,7 +96,8 @@ pub fn shape_kind(p: &Path) -> &'static str { (3 | 4, 0, 1) if axis_aligned() => tr_noop!("Rectangle"), // A rounded rectangle: four sides and four corners. (4, 4, 1) => tr_noop!("Rectangle"), - (0, 4, 1) => tr_noop!("Oval"), + // Four arcs (an imported circle) or the Oval tool's eight (#459). + (0, 4 | 8, 1) => tr_noop!("Oval"), (n, 0, 1) if n >= 2 => tr_noop!("Polygon"), _ => tr_noop!("Shape"), } @@ -360,6 +361,7 @@ mod tests { assert_eq!(shape_kind(&Path::rect(0.0, 0.0, 10.0, 5.0)), "Rectangle"); assert_eq!(shape_kind(&Path::rounded_rect(0.0, 0.0, 10.0, 5.0, 2.0)), "Rectangle"); assert_eq!(shape_kind(&Path::ellipse(0.0, 0.0, 4.0, 3.0)), "Oval"); + assert_eq!(shape_kind(&Path::ellipse8(0.0, 0.0, 4.0, 3.0)), "Oval"); assert_eq!(shape_kind(&Path::star(0.0, 0.0, 10.0, 4.0, 5)), "Polygon"); assert_eq!(shape_kind(&Path::line(V::new(0.0, 0.0), V::new(3.0, 4.0))), "Line"); // A slanted quadrilateral is a polygon, not a rectangle.