From cceef7c01ea20015d83897c4634d526c9a3aad21 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:57:43 +0100 Subject: [PATCH 001/570] fix(doc): enforce the frame limit on loaded documents Commands keep keyframes within MAX_FRAME, but sanitize() did not, so a file could hold a keyframe ending near u32::MAX: playback stalled at the playhead cap and PNG sequence export defaulted to billions of frames. sanitize() now drops keyframes past MAX_FRAME and trims durations; the engine's MAX_FRAME is now the doc constant. --- crates/doc/src/lib.rs | 17 +++++++++++++++++ crates/engine/src/lib.rs | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 245e42b2..6dfa46a3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -569,6 +569,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 whole AniCraft document: a persistent (structurally shared) tree. /// /// `clone()` is O(layers + symbols) pointer copies, which makes undo snapshots and render-thread @@ -638,6 +651,7 @@ impl Document { } }; for l in &mut self.timeline.layers { + clamp_frames(Arc::make_mut(l)); Arc::make_mut(l).normalize(); scan(l, &mut max_id); } @@ -646,6 +660,7 @@ impl Document { max_id = max_id.max(sym.id.0); 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(); scan(l, &mut max_id); } @@ -733,7 +748,9 @@ mod tests { d.stage.width = 0; d.stage.fps = f32::NAN; d.next_id = 0; + Arc::make_mut(&mut d.timeline.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"); assert_eq!(d.stage.width, 1); assert_eq!(d.stage.fps, 24.0); assert!(d.next_id > d.timeline.layers[0].id.0); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index eb899e17..b9e99b5b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -103,7 +103,7 @@ pub fn find_command(id: &str) -> Option { pub use history::{Snapshot, StateId}; /// 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; /// Drawing defaults used by the drawing commands when params omit colours. #[derive(Clone, Copy, Debug)] From 7f6fc25a43de02cd4c23740fc42a27b1282774f4 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:58:03 +0100 Subject: [PATCH 002/570] fix(xfl): refuse backslash paths that leave an XFL folder package The folder reader only split library paths on '/', so on Windows an Include href like '..\x.xml' read files outside the package. --- crates/xfl/src/import.rs | 3 ++- crates/xfl/src/tests.rs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 60b34aef..66dc3176 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -370,7 +370,8 @@ 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); diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 12e42033..69f5b163 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -201,3 +201,16 @@ fn shape_tweens_come_across_as_shape_tweens() { let mid = evaluate(&d, 5).items[0].path.bounds(); assert!(mid.max.x > 110.0 && mid.min.x > 10.0, "{mid:?}"); } + +#[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(); +} From d3b46e7cabefebd04ce18f1d8ad3031e23359e1d Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:31:35 +0300 Subject: [PATCH 003/570] fix(text): text that mixes directions reads the right way round A paragraph was shaped as one run in the direction of its first letter, so a number or a Latin word inside Arabic came out reversed ("2026" as "6202", "AniCraft" as "tfarCinA"), and a wrapped Arabic paragraph was broken from its visual left, which put its last words on the first line. Layout now follows the Unicode bidi algorithm (UAX #9, the unicode-bidi crate, MIT OR Apache-2.0): each paragraph's level runs are shaped in their own direction to measure it, lines are found in reading order, and each line's runs are shaped and placed in visual order. Text that reads one way is laid out as before. A test pins the line breaks and, where the font has Arabic letters, the number's order and the wrapped paragraph's first line. --- Cargo.lock | 7 ++ crates/text/Cargo.toml | 2 + crates/text/src/lib.rs | 156 +++++++++++++++++++++++++++-------------- docs/adr/0012-text.md | 4 ++ docs/roadmap.md | 2 +- 5 files changed, 119 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7b4d91a..77042232 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -268,6 +268,7 @@ dependencies = [ "fontdb", "harfrust", "skrifa", + "unicode-bidi", ] [[package]] @@ -3147,6 +3148,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-general-category" version = "1.1.0" diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 6214daf1..79dfffa5 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -14,6 +14,8 @@ fontdb.workspace = true # Shaping (a HarfBuzz port) and outlines/metrics: both already in the tree through egui. harfrust = "0.12" skrifa = { version = "0.44", default-features = false, features = ["std"] } +# The Unicode bidi algorithm (UAX #9), for text that mixes right-to-left and left-to-right runs. +unicode-bidi = "0.3" [lints] workspace = true diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 950dfa6d..530030cf 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -199,64 +199,45 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let charmap = font.charmap(); let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count(); - // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. + // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. Text + // that mixes directions follows the Unicode bidi algorithm (UAX #9): a paragraph's lines are + // found in reading order, then each line's runs are shaped in their own direction and placed + // in visual order, so a number or a Latin word inside Arabic reads the right way round, and a + // wrapped Arabic paragraph starts on the first line. let mut lines: Vec<(f32, Vec<(Glyph, f32)>)> = Vec::new(); for para in text.split('\n') { let para = para.strip_suffix('\r').unwrap_or(para); - let mut buffer = harfrust::UnicodeBuffer::new(); - buffer.push_str(para); - buffer.guess_segment_properties(); - let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new()); - let run: Vec = shaped - .glyph_infos() - .iter() - .zip(shaped.glyph_positions()) - .map(|(info, pos)| Glyph { - id: skrifa::GlyphId::new(info.glyph_id), - cluster: info.cluster as usize, - x_offset: pos.x_offset as f32 * scale, - y_offset: pos.y_offset as f32 * scale, - advance: pos.x_advance as f32 * scale + style.letter_spacing, - }) - .collect(); - let is_space = |g: &Glyph| para.get(g.cluster..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace); - let mut line: Vec<(Glyph, f32)> = Vec::new(); - let mut x = 0.0f32; - // Where the current line could break: after its last space. - let mut break_at: Option = None; - for g in run { - let space = is_space(&g); - if let Some(w) = style.width - && !space - && x + g.advance > w - && !line.is_empty() - { - // Wrap: at the last space if there is one (dropping trailing spaces), else here. - let rest = match break_at { - Some(b) => line.split_off(b), - None => Vec::new(), - }; - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); + let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); + let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); + // Each byte's share of the width (a cluster's advance on its first byte), run by run. + let mut advance = vec![0.0f32; para.len()]; + let mut start = 0; + while start < para.len() { + let level = bidi.levels.get(start).copied(); + let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); + for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { + if let Some(a) = advance.get_mut(start + g.cluster) { + *a += g.advance; } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, std::mem::take(&mut line))); - let shift = rest.first().map_or(0.0, |(_, gx)| *gx); - line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect(); - x = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - break_at = None; } - line.push((g, x)); - x += line.last().map_or(0.0, |(g, _)| g.advance); - if space { - break_at = Some(line.len()); + start = end; + } + for range in break_lines(para, &advance, style.width) { + let mut line: Vec<(Glyph, f32)> = Vec::new(); + let mut x = 0.0f32; + if !range.is_empty() { + let (levels, runs) = bidi.visual_runs(range); + for run in runs { + let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl()); + for g in shape_run(run, rtl) { + let a = g.advance; + line.push((g, x)); + x += a; + } + } } + lines.push((x, line)); } - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); - } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, line)); } let box_width = style.width.unwrap_or_else(|| lines.iter().map(|(w, _)| *w).fold(0.0, f32::max)); @@ -279,6 +260,58 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing }) } +/// Shapes `text` in one direction. Glyphs come back in visual order (left to right), clusters +/// counted in bytes from the start of `text`. +fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { + let mut buffer = harfrust::UnicodeBuffer::new(); + buffer.push_str(text); + buffer.set_direction(if rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight }); + buffer.guess_segment_properties(); + let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new()); + shaped + .glyph_infos() + .iter() + .zip(shaped.glyph_positions()) + .map(|(info, pos)| Glyph { + id: skrifa::GlyphId::new(info.glyph_id), + cluster: info.cluster as usize, + x_offset: pos.x_offset as f32 * scale, + y_offset: pos.y_offset as f32 * scale, + advance: pos.x_advance as f32 * scale + letter_spacing, + }) + .collect() +} + +/// A paragraph's lines as byte ranges in reading order, given each byte's share of the width: +/// wrapped after the last space before `width` is passed (or within a word wider than the line), +/// with the spaces at a line's end left out. +fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec> { + let trimmed = |start: usize, end: usize| start..para.get(start..end).map_or(start, |s| start + s.trim_end().len()); + let mut lines = Vec::new(); + let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::); + for (i, c) in para.char_indices() { + let a = advance.get(i).copied().unwrap_or(0.0); + let space = c.is_whitespace(); + if let Some(w) = width + && !space + && x + a > w + && i > start + { + let end = break_at.unwrap_or(i); + lines.push(trimmed(start, end)); + start = end; + x = advance.get(start..i).map_or(0.0, |s| s.iter().sum()); + break_at = None; + } + x += a; + if space { + break_at = Some(i + c.len_utf8()); + } + } + lines.push(trimmed(start, para.len())); + lines +} + /// Draws glyph outlines (font space, y up) into a path (pixels, y down) at a pen position. struct Pen<'a> { cmds: &'a mut Vec, @@ -371,6 +404,27 @@ mod tests { assert!(boxed(Align::Right).min.x > 280.0); } + #[test] + fn mixed_directions_read_the_right_way_round() { + // Lines are found in reading order: after the last space that fits, or within a word. + assert_eq!(break_lines("ab cd ef", &[1.0; 8], Some(5.0)), vec![0..5, 6..8]); + assert_eq!(break_lines("abcdefgh", &[1.0; 8], Some(3.0)), vec![0..3, 3..6, 6..8]); + let Some(fonts) = fonts() else { return }; + let lay = |t: &str, width| fonts.layout(t, &Style { width, ..style(40.0) }).unwrap(); + let arabic = lay("مرحبا 2026", None); + if arabic.missing > 0 { + eprintln!("{} has no Arabic letters: right-to-left layout test skipped", arabic.family); + return; + } + // A number inside Arabic keeps its digits in order, at the line's left end ... + assert!(arabic.outline.cmds.starts_with(&lay("2026", None).outline.cmds)); + // ... and a wrapped Arabic paragraph starts with its first word, on the first line. + let first = lay("بيت", None); + let wrapped = lay("بيت جديد", Some(first.width + 1.0)); + assert!(wrapped.height > first.height * 1.8, "two lines: {}", wrapped.height); + assert!(wrapped.outline.cmds.starts_with(&first.outline.cmds)); + } + #[test] fn families_resolve_and_styles_are_clamped() { let Some(fonts) = fonts() else { return }; diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index 751dfa77..ff42d48c 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -34,6 +34,10 @@ so neither may depend on which fonts happen to be installed. embedded Inter), shapes with `harfrust` (a HarfBuzz port), reads outlines and metrics with `skrifa`, and breaks lines (paragraphs at line breaks; with a width, greedily at spaces). These crates are already in the dependency tree through egui, so no new licences. + Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the + Unicode bidi algorithm through `unicode-bidi` (MIT OR Apache-2.0): lines are found in + reading order, then each line's runs are shaped in their own direction and placed in + visual order. Bold and italic pick the matching face of the family; there is no synthetic styling. 5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's second Break Apart does. diff --git a/docs/roadmap.md b/docs/roadmap.md index f3a35188..3d3a9c7d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,7 +29,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; command macros. | | **M7** | Advanced animation | Bone/IK tool; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; crash-recovery autosave; documentation book. | From e90f3854a4e3fc2a88959e08df9d4a76b04e7342 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:41:40 +0300 Subject: [PATCH 004/570] fix(text): letters the chosen font lacks come from a fallback face Text was drawn with one face, so letters it doesn't have showed as boxes, and nothing said so: Arabic in Inter, the default family where the app embeds it, or in Consolas. Now each character the chosen face lacks comes from the first of FALLBACK_FAMILIES that has it (faces with wide coverage that come with Windows, macOS and common Linux desktops, then Noto's script families), character by character: the rest of the block keeps its face, and a letter's marks stay with it. The block's line metrics still come from the chosen face. Characters no face has are counted, and text.create and text.edit now say they show as boxes. --- crates/engine/src/cmds_text.rs | 12 ++- crates/text/src/lib.rs | 140 ++++++++++++++++++++++++++++----- docs/adr/0012-text.md | 4 +- docs/roadmap.md | 2 +- 4 files changed, 136 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 354e3c97..c46e5f45 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -105,7 +105,17 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu }, ) .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; - let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + let mut notes = Vec::new(); + if !style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim()) { + notes.push(format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + } + // Letters no installed font has (after the fallbacks) would otherwise show as boxes unsaid. + match layout.missing { + 0 => {} + 1 => notes.push("1 character isn't in any font on this computer and shows as a box".to_string()), + n => notes.push(format!("{n} characters aren't in any font on this computer and show as boxes")), + } + let note = (!notes.is_empty()).then(|| notes.join("; ")); let block = TextBlock { text: text.to_string(), font: layout.family, diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 530030cf..0c9b8814 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -158,11 +158,55 @@ impl Fonts { style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, }; let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let laid = self.db.with_face_data(id, |data, index| lay_out(data, index, text, style)).flatten().ok_or(TextError::NoFonts)?; + let face = |id| self.db.with_face_data(id, |data, index| (data.to_vec(), index)); + let mut faces = vec![face(id).ok_or(TextError::NoFonts)?]; + // Characters the face doesn't have (Arabic in Inter, say) come from the first fallback + // family that has them; everything else stays in the chosen face. + let charmap_lacks = |f: &(Vec, u32), c: char| skrifa::FontRef::from_index(&f.0, f.1).ok().is_none_or(|font| font.charmap().map(c).is_none()); + let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); + missing.sort_unstable(); + missing.dedup(); + missing.retain(|c| faces.first().is_none_or(|f| charmap_lacks(f, *c))); + for fallback in FALLBACK_FAMILIES { + if missing.is_empty() || faces.len() >= MAX_FACES { + break; + } + let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; + let Some(f) = face(fid) else { continue }; + let before = missing.len(); + missing.retain(|c| charmap_lacks(&f, *c)); + if missing.len() < before { + faces.push(f); + } + } + let laid = lay_out(&faces, text, style).ok_or(TextError::NoFonts)?; Ok(Layout { family, ..laid }) } } +/// Families tried, in order, for characters the chosen face doesn't have: faces with wide +/// coverage that come with Windows, macOS and common Linux desktops, then Noto's script families. +pub const FALLBACK_FAMILIES: &[&str] = &[ + "Segoe UI", + "Arial", + "Tahoma", + "Geeza Pro", + "Arial Unicode MS", + "DejaVu Sans", + "Noto Sans", + "Noto Sans Arabic", + "Noto Naskh Arabic", + "Noto Sans Hebrew", +]; + +/// Most faces one text block draws with (the chosen face and its fallbacks). +const MAX_FACES: usize = 6; + +/// A character that is drawn (not a space, a line break or another control). +fn needs_glyph(c: char) -> bool { + !c.is_control() && !c.is_whitespace() +} + /// Clamps a style to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px). pub fn sanitize(style: &Style) -> Style { let fin = |v: f32, d: f32| if v.is_finite() { v } else { d }; @@ -175,8 +219,10 @@ pub fn sanitize(style: &Style) -> Style { } } -/// One shaped glyph: id, where its pen position starts, its offsets and advance (pixels). +/// One shaped glyph: the face it comes from, its id, the byte it starts at in its paragraph, its +/// offsets and advance (pixels). struct Glyph { + face: usize, id: skrifa::GlyphId, cluster: usize, x_offset: f32, @@ -184,20 +230,22 @@ struct Glyph { advance: f32, } -fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option { +/// Lays `text` out with `faces`: the chosen face first (its metrics set the lines), then the +/// fallbacks for characters it doesn't have. +fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option { let style = sanitize(style); - let font = skrifa::FontRef::from_index(data, index).ok()?; + let fonts: Vec = faces.iter().filter_map(|(data, index)| skrifa::FontRef::from_index(data, *index).ok()).collect(); let size = skrifa::instance::Size::new(style.size); - let metrics = font.metrics(size, skrifa::instance::LocationRef::default()); - let upem = f32::from(metrics.units_per_em.max(1)); - let scale = style.size / upem; + let metrics = fonts.first()?.metrics(size, skrifa::instance::LocationRef::default()); let ascent = metrics.ascent; let line_height = (metrics.ascent - metrics.descent + metrics.leading).max(style.size * 0.5) + style.line_spacing; - let shaper_data = harfrust::ShaperData::new(&font); - let shaper = shaper_data.shaper(&font).build(); - let glyphs = font.outline_glyphs(); - let charmap = font.charmap(); - let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count(); + let shaper_data: Vec = fonts.iter().map(harfrust::ShaperData::new).collect(); + let shapers: Vec = fonts.iter().zip(&shaper_data).map(|(f, d)| d.shaper(f).build()).collect(); + let scales: Vec = fonts.iter().map(|f| style.size / f32::from(f.metrics(size, skrifa::instance::LocationRef::default()).units_per_em.max(1))).collect(); + let outlines: Vec<_> = fonts.iter().map(|f| f.outline_glyphs()).collect(); + let charmaps: Vec<_> = fonts.iter().map(|f| f.charmap()).collect(); + let has = |face: usize, c: char| charmaps.get(face).is_some_and(|m| m.map(c).is_some()); + let missing = text.chars().filter(|c| needs_glyph(*c) && !(0..fonts.len()).any(|f| has(f, *c))).count(); // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. Text // that mixes directions follows the Unicode bidi algorithm (UAX #9): a paragraph's lines are @@ -208,7 +256,35 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option for para in text.split('\n') { let para = para.strip_suffix('\r').unwrap_or(para); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); - let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); + // The face drawing each byte: the chosen one where it has the character, else the first + // fallback that does. Spaces and marks stay with what comes before them, so a letter and + // its harakat are shaped together. + let mut face_of = vec![0usize; para.len()]; + let mut current = 0; + for (i, c) in para.char_indices() { + let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); + if !joins || !has(current, c) { + current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(if joins { current } else { 0 }); + } + face_of.iter_mut().skip(i).take(c.len_utf8()).for_each(|f| *f = current); + } + // A run shaped in one direction, split where the face changes; glyphs in visual order. + let shape_run = |run: std::ops::Range, rtl: bool| { + let mut parts: Vec> = Vec::new(); + let mut start = run.start; + while start < run.end { + let face = face_of.get(start).copied().unwrap_or(0); + let end = (start..run.end).find(|i| face_of.get(*i).copied().unwrap_or(0) != face).unwrap_or(run.end); + if let (Some(s), Some(shaper)) = (para.get(start..end), shapers.get(face)) { + parts.push(shape(shaper, face, s, start, rtl, scales.get(face).copied().unwrap_or(1.0), style.letter_spacing)); + } + start = end; + } + if rtl { + parts.reverse(); + } + parts.into_iter().flatten().collect::>() + }; // Each byte's share of the width (a cluster's advance on its first byte), run by run. let mut advance = vec![0.0f32; para.len()]; let mut start = 0; @@ -216,7 +292,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { - if let Some(a) = advance.get_mut(start + g.cluster) { + if let Some(a) = advance.get_mut(g.cluster) { *a += g.advance; } } @@ -250,7 +326,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option }; let baseline = ascent + row as f32 * line_height; for (g, gx) in line { - let Some(glyph) = glyphs.get(g.id) else { continue }; + let Some(glyph) = outlines.get(g.face).and_then(|o| o.get(g.id)) else { continue }; let mut pen = Pen { cmds: &mut outline.cmds, x: shift + gx + g.x_offset, y: baseline - g.y_offset }; let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); let _ = glyph.draw(settings, &mut pen); @@ -260,9 +336,9 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing }) } -/// Shapes `text` in one direction. Glyphs come back in visual order (left to right), clusters -/// counted in bytes from the start of `text`. -fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { +/// Shapes `text` (which starts at byte `at` of its paragraph) with one face in one direction. +/// Glyphs come back in visual order (left to right), clusters counted from the paragraph's start. +fn shape(shaper: &harfrust::Shaper<'_>, face: usize, text: &str, at: usize, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { let mut buffer = harfrust::UnicodeBuffer::new(); buffer.push_str(text); buffer.set_direction(if rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight }); @@ -273,8 +349,9 @@ fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, lette .iter() .zip(shaped.glyph_positions()) .map(|(info, pos)| Glyph { + face, id: skrifa::GlyphId::new(info.glyph_id), - cluster: info.cluster as usize, + cluster: at + info.cluster as usize, x_offset: pos.x_offset as f32 * scale, y_offset: pos.y_offset as f32 * scale, advance: pos.x_advance as f32 * scale + letter_spacing, @@ -425,6 +502,31 @@ mod tests { assert!(wrapped.outline.cmds.starts_with(&first.outline.cmds)); } + #[test] + fn letters_the_font_lacks_come_from_a_fallback_face() { + let Some(fonts) = fonts() else { return }; + let has = |family: &str, c: char| { + let q = fontdb::Query { families: &[fontdb::Family::Name(family)], ..fontdb::Query::default() }; + fonts.db.query(&q).and_then(|id| fonts.db.with_face_data(id, |d, i| skrifa::FontRef::from_index(d, i).is_ok_and(|f| f.charmap().map(c).is_some()))).unwrap_or(false) + }; + // A family with Latin letters and no Arabic ones, and a fallback that has Arabic. + let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { return }; + if !FALLBACK_FAMILIES.iter().any(|f| has(f, 'ب')) { + eprintln!("no fallback family with Arabic letters here: fallback test skipped"); + return; + } + let lay = |t: &str| fonts.layout(t, &Style { family: latin.clone(), ..style(40.0) }).unwrap(); + let arabic = lay("بيت"); + assert_eq!((arabic.missing, arabic.family.as_str()), (0, latin.as_str()), "the block keeps its family"); + assert!(!arabic.outline.cmds.is_empty()); + // The Latin letters are still drawn in the chosen face, the Arabic ones after them. + let mixed = lay("ab بيت"); + assert!(mixed.outline.cmds.starts_with(&lay("ab").outline.cmds)); + assert!(mixed.outline.cmds.len() > lay("ab").outline.cmds.len()); + // A character no font has is counted, so the command can say so. + assert_eq!(lay("a\u{10FFFD}").missing, 1); + } + #[test] fn families_resolve_and_styles_are_clamped() { let Some(fonts) = fonts() else { return }; diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index ff42d48c..cc7138c7 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -37,7 +37,9 @@ so neither may depend on which fonts happen to be installed. Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the Unicode bidi algorithm through `unicode-bidi` (MIT OR Apache-2.0): lines are found in reading order, then each line's runs are shaped in their own direction and placed in - visual order. + visual order. Characters the chosen face doesn't have (Arabic in Inter, say) come from the + first of `FALLBACK_FAMILIES` that has them, character by character, so the rest of the block + keeps its face; any that no face has are counted, and the command says they show as boxes. Bold and italic pick the matching face of the family; there is no synthetic styling. 5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's second Break Apart does. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3d3a9c7d..164e9328 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,7 +29,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, fallback faces for letters the chosen font lacks, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; command macros. | | **M7** | Advanced animation | Bone/IK tool; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; crash-recovery autosave; documentation book. | From 5fb4c75d732101bbf70b0c5ab4b74876a7bda3f1 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sun, 8 Nov 2026 07:18:28 +0300 Subject: [PATCH 005/570] perf(text): read the chosen face in place and each fallback's charmap once Fallback faces had every face copied out of the memory-mapped font on each layout, the chosen one included, and a font parsed for every character checked against it. Now the chosen face is read in place, only fallback faces the text needs are copied, and each candidate's charmap is read once. The fallback test says when it skips, and checks the Arabic letters are the fallback face's (as wide as in that family) rather than boxes from the chosen face. --- crates/text/src/lib.rs | 80 +++++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 28 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 0c9b8814..cb5675d8 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -158,28 +158,37 @@ impl Fonts { style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, }; let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let face = |id| self.db.with_face_data(id, |data, index| (data.to_vec(), index)); - let mut faces = vec![face(id).ok_or(TextError::NoFonts)?]; - // Characters the face doesn't have (Arabic in Inter, say) come from the first fallback - // family that has them; everything else stays in the chosen face. - let charmap_lacks = |f: &(Vec, u32), c: char| skrifa::FontRef::from_index(&f.0, f.1).ok().is_none_or(|font| font.charmap().map(c).is_none()); - let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); - missing.sort_unstable(); - missing.dedup(); - missing.retain(|c| faces.first().is_none_or(|f| charmap_lacks(f, *c))); - for fallback in FALLBACK_FAMILIES { - if missing.is_empty() || faces.len() >= MAX_FACES { - break; - } - let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; - let Some(f) = face(fid) else { continue }; - let before = missing.len(); - missing.retain(|c| charmap_lacks(&f, *c)); - if missing.len() < before { - faces.push(f); - } - } - let laid = lay_out(&faces, text, style).ok_or(TextError::NoFonts)?; + // The chosen face is read in place (memory-mapped); only fallback faces the text needs are + // copied, so text in one script costs what it did before fallbacks. + let laid = self + .db + .with_face_data(id, |data, index| { + // Characters the face doesn't have (Arabic in Inter, say) come from the first + // fallback family that has them; everything else stays in the chosen face. + let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); + missing.sort_unstable(); + missing.dedup(); + keep_lacking(&mut missing, data, index); + let mut fallbacks: Vec<(Vec, u32)> = Vec::new(); + for fallback in FALLBACK_FAMILIES { + if missing.is_empty() || fallbacks.len() + 1 >= MAX_FACES { + break; + } + let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; + let helps = |d: &[u8], i: u32| { + let before = missing.len(); + keep_lacking(&mut missing, d, i); + (missing.len() < before).then(|| (d.to_vec(), i)) + }; + if let Some(face) = self.db.with_face_data(fid, helps).flatten() { + fallbacks.push(face); + } + } + let faces: Vec<(&[u8], u32)> = std::iter::once((data, index)).chain(fallbacks.iter().map(|(d, i)| (d.as_slice(), *i))).collect(); + lay_out(&faces, text, style) + }) + .flatten() + .ok_or(TextError::NoFonts)?; Ok(Layout { family, ..laid }) } } @@ -207,6 +216,14 @@ fn needs_glyph(c: char) -> bool { !c.is_control() && !c.is_whitespace() } +/// Drops from `chars` those the face in `data` has (its charmap read once). +fn keep_lacking(chars: &mut Vec, data: &[u8], index: u32) { + if let Ok(font) = skrifa::FontRef::from_index(data, index) { + let charmap = font.charmap(); + chars.retain(|c| charmap.map(*c).is_none()); + } +} + /// Clamps a style to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px). pub fn sanitize(style: &Style) -> Style { let fin = |v: f32, d: f32| if v.is_finite() { v } else { d }; @@ -232,7 +249,7 @@ struct Glyph { /// Lays `text` out with `faces`: the chosen face first (its metrics set the lines), then the /// fallbacks for characters it doesn't have. -fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option { +fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style) -> Option { let style = sanitize(style); let fonts: Vec = faces.iter().filter_map(|(data, index)| skrifa::FontRef::from_index(data, *index).ok()).collect(); let size = skrifa::instance::Size::new(style.size); @@ -266,7 +283,9 @@ fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option, rtl: bool| { @@ -510,15 +529,20 @@ mod tests { fonts.db.query(&q).and_then(|id| fonts.db.with_face_data(id, |d, i| skrifa::FontRef::from_index(d, i).is_ok_and(|f| f.charmap().map(c).is_some()))).unwrap_or(false) }; // A family with Latin letters and no Arabic ones, and a fallback that has Arabic. - let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { return }; - if !FALLBACK_FAMILIES.iter().any(|f| has(f, 'ب')) { + let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { + eprintln!("no family with Latin letters and no Arabic ones here: fallback test skipped"); + return; + }; + let Some(fallback) = FALLBACK_FAMILIES.iter().find(|f| has(f, 'ب')) else { eprintln!("no fallback family with Arabic letters here: fallback test skipped"); return; - } + }; let lay = |t: &str| fonts.layout(t, &Style { family: latin.clone(), ..style(40.0) }).unwrap(); let arabic = lay("بيت"); assert_eq!((arabic.missing, arabic.family.as_str()), (0, latin.as_str()), "the block keeps its family"); - assert!(!arabic.outline.cmds.is_empty()); + // The letters are the fallback face's (as wide as in that family), not the chosen face's boxes. + let direct = fonts.layout("بيت", &Style { family: fallback.to_string(), ..style(40.0) }).unwrap(); + assert!((arabic.width - direct.width).abs() < 0.01, "{} vs {} in {fallback}", arabic.width, direct.width); // The Latin letters are still drawn in the chosen face, the Arabic ones after them. let mixed = lay("ab بيت"); assert!(mixed.outline.cmds.starts_with(&lay("ab").outline.cmds)); From c9dd3163d1077ce6fd9e733d5f7a7bf4d25dc471 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 01:05:24 +0300 Subject: [PATCH 006/570] perf(text): skip bidi reordering for a paragraph with no right-to-left text (M5) --- crates/text/src/lib.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6e4ca3fd..c4037a55 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -318,7 +318,14 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option for range in break_lines(para, &advance, style.width) { let mut line: Vec<(Glyph, f32)> = Vec::new(); let mut x = 0.0f32; - if !range.is_empty() { + if !bidi.has_rtl() { + // All left to right: nothing to reorder (visual_runs copies the paragraph's levels per line). + for g in shape_run(range, false) { + let a = g.advance; + line.push((g, x)); + x += a; + } + } else if !range.is_empty() { let (levels, runs) = bidi.visual_runs(range); for run in runs { let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl()); From 912ceba1916d8c950675201983968b6fe94892a1 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 09:26:04 +0300 Subject: [PATCH 007/570] fix(text): invisible format characters aren't missing glyphs; the notice names the fonts it checked (M5) --- crates/engine/src/cmds_text.rs | 6 +++--- crates/text/src/lib.rs | 8 +++++++- docs/adr/0012-text.md | 5 +++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 9f1396e1..ededa328 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -109,11 +109,11 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu if !style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim()) { notes.push(format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); } - // Letters no installed font has (after the fallbacks) would otherwise show as boxes unsaid. + // Letters neither the font nor the fallback fonts have would otherwise show as boxes unsaid. match layout.missing { 0 => {} - 1 => notes.push("1 character isn't in any font on this computer and shows as a box".to_string()), - n => notes.push(format!("{n} characters aren't in any font on this computer and show as boxes")), + 1 => notes.push(format!("1 character isn't in {} or the fallback fonts and shows as a box", layout.family)), + n => notes.push(format!("{n} characters aren't in {} or the fallback fonts and show as boxes", layout.family)), } let note = (!notes.is_empty()).then(|| notes.join("; ")); let block = TextBlock { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7355a31a..6e35b879 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -280,7 +280,11 @@ const MAX_FACES: usize = 6; /// A character that is drawn (not a space, a line break or another control). fn needs_glyph(c: char) -> bool { - !c.is_control() && !c.is_whitespace() + // Invisible format characters (ZWNJ, ZWJ, direction marks and embeddings, variation + // selectors, the BOM) draw as nothing, and fonts often don't map them. + let invisible = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::BN + || matches!(c, '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'); + !c.is_control() && !c.is_whitespace() && !invisible } /// Drops from `chars` those the face in `data` has (its charmap read once). @@ -649,6 +653,8 @@ mod tests { assert!(mixed.outline.cmds.len() > lay("ab").outline.cmds.len()); // A character no font has is counted, so the command can say so. assert_eq!(lay("a\u{10FFFD}").missing, 1); + // Invisible format characters aren't boxes, so they aren't missing either. + assert_eq!(lay("a\u{200C}b\u{200D}\u{200F}\u{FE0F}").missing, 0); } #[test] diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index 7e06e2fc..1ca8e1b6 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -52,5 +52,6 @@ so neither may depend on which fonts happen to be installed. edited, and the user is told. * Text in Animate documents imports onto this model (ADR 0014). * Not yet: per-character styles in one block, vertical text, text along a path, input and - dynamic text fields (with scripting, M6), font embedding for export, glyph fallback across - fonts for missing characters (missing glyphs draw as the font's "notdef" box). + dynamic text fields (with scripting, M6), font embedding for export, fallback to installed + fonts outside the fallback list (a character none of the loaded faces has draws as the + font's "notdef" box, and the command says so). From c80f2c47e3ac4c33950caf10bf8c8f4f6bcd2898 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 10:54:49 +0300 Subject: [PATCH 008/570] perf(text): a block without a width skips the measuring pass that only line wrapping reads (M5) --- crates/text/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 44f64a56..d5a7efa5 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -307,9 +307,10 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let para = para.strip_suffix('\r').unwrap_or(para); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); - // Each byte's share of the width (a cluster's advance on its first byte), run by run. + // Each byte's share of the width (a cluster's advance on its first byte), run by run. Only wrapping + // reads it, so a block without a width skips this pass (it would shape every paragraph twice). let mut advance = vec![0.0f32; para.len()]; - let mut start = 0; + let mut start = if style.width.is_some() { 0 } else { para.len() }; while start < para.len() { let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); From a2acc2c70772ed9637d130e15cfe73ea62cfa6a6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 03:14:53 +0000 Subject: [PATCH 009/570] fix(cli): refuse a caller-supplied ffmpeg over serve/mcp, bound request lines --- crates/cli/src/lib.rs | 77 +++++++++++++++++++++++++++++++++++++++++-- crates/cli/src/mcp.rs | 26 +++++++++++++-- 2 files changed, 98 insertions(+), 5 deletions(-) diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 42a4cc5b..20e2615c 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -410,6 +410,48 @@ 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 = input.by_ref().take(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 = input.by_ref().take(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 Export Video 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. +pub(crate) fn refuse_remote_ffmpeg(cmd: &str, params: &Value) -> Result<(), String> { + if cmd == "file.export_video" && 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. @@ -425,7 +467,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}), @@ -437,8 +479,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; } @@ -457,6 +508,26 @@ pub fn serve(s: &mut Session, input: R, out: &mut W) -> st mod tests { use super::*; + #[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")); + // 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 44e3543e..e2f7cb57 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -109,6 +109,7 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result 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}"))?; s.execute(id, ¶ms).map_err(|e| format!("{id}: {e}")) }; Ok(match name { @@ -219,8 +220,17 @@ pub fn handle(s: &mut Session, 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 Session, 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; } @@ -266,6 +276,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(); From 045aa8cbbf6d8cedd2a8d0cf253850d17ce8356d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 03:25:53 +0000 Subject: [PATCH 010/570] docs: changelog --- CHANGELOG.md | 1 + crates/cli/src/lib.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3aee6023..4ba59683 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +* **Security: `serve` and `mcp` hardening.** Over `serve` and `mcp`, `file.export_video` refuses an `ffmpeg` parameter (set `ANICRAFT_FFMPEG` instead; `exec` and `run` keep it), and a request line over 64 MiB is answered with an error instead of growing without bound. * **Stroke caps, joins, miter limit, and dashed and dotted lines** (ADR 0046, M7). Properties › Stroke has Animate's rows: **Style** (Solid, Dashed with a dash and gap editor, Dotted with dot spacing), **Cap** (None, Round, Square), **Join** (Miter, Round, Bevel) and **Miter** diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 20e2615c..295e39cb 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -423,14 +423,14 @@ pub(crate) enum Line { /// 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 = input.by_ref().take(max as u64 + 1).read_until(b'\n', &mut buf)?; + 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 = input.by_ref().take(1 << 20).read_until(b'\n', &mut skip)?; + 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); } From 171e0080e89a6b6b5f96ea4ed7f247385bc6a004 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:59:05 +0100 Subject: [PATCH 011/570] Fix Decomposed::lerp hanging on huge or non-finite rotation Found while testing crates/geom/src/affine.rs:146 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/affine.rs | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/geom/src/affine.rs b/crates/geom/src/affine.rs index c64bfebd..1f17df21 100644 --- a/crates/geom/src/affine.rs +++ b/crates/geom/src/affine.rs @@ -145,12 +145,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), @@ -202,4 +203,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); + } } From fe6c50856b8121a0ddc7e57e74f04bca6d7c1742 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:20:06 +0100 Subject: [PATCH 012/570] Write non-finite path coordinates as 0 so saved paths reload Found while testing crates/geom/src/path.rs:39 (to_svg) and :141 (from_svg) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/path.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5c29dd2f..4dd34cdf 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 { @@ -499,6 +501,24 @@ pub fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 { mod tests { use super::*; + #[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); From ea3a95be51f81be45a00b89d10ef3d7f5956e2bf Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:22:19 +0100 Subject: [PATCH 013/570] Keep y-axis direction in Affine::decompose when x scale is zero Found while testing crates/geom/src/affine.rs:99-114 (decompose, the sx <= 1e-12 branch) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/affine.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/geom/src/affine.rs b/crates/geom/src/affine.rs index c64bfebd..98e6fc5d 100644 --- a/crates/geom/src/affine.rs +++ b/crates/geom/src/affine.rs @@ -99,15 +99,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 } } @@ -171,6 +172,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)); From a9c6fc0d3232086a8afa53332d715da7b41479ed Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Wed, 11 Nov 2026 09:23:55 +0300 Subject: [PATCH 014/570] fix(text): a combining mark the letter's face lacks takes the letter to a face with both (M5) Before, the mark alone went to the fallback face and was shaped apart from its letter, so it couldn't attach. Now the letter moves with it when one face has both; a mark no face pairs with still comes from the first face that has it. --- crates/text/src/lib.rs | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 86c3de5b..7e57000c 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -377,13 +377,26 @@ fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style) -> Option let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); // The face drawing each byte: the chosen one where it has the character, else the first // fallback that does. Spaces and marks stay with what comes before them, so a letter and - // its harakat are shaped together. + // its harakat are shaped together; a mark its letter's face lacks takes the letter to a + // face that has both, if there is one. let mut face_of = vec![0usize; para.len()]; let mut current = 0; + let mut base = (0, '\0'); // the last letter: its byte offset and character for (i, c) in para.char_indices() { let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); - if !joins || !has(current, c) { - current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(if joins { current } else { 0 }); + if !joins { + current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(0); + base = (i, c); + } else if !has(current, c) { + let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; + if let Some(both) = (0..fonts.len()).find(|f| mark && has(*f, base.1) && has(*f, c)) { + current = both; + if let Some(bytes) = face_of.get_mut(base.0..i) { + bytes.fill(both); + } + } else if let Some(f) = (0..fonts.len()).find(|f| has(*f, c)) { + current = f; + } } if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { bytes.fill(current); @@ -661,6 +674,21 @@ mod tests { assert_eq!(lay("a\u{10FFFD}").missing, 1); // Invisible format characters aren't boxes, so they aren't missing either. assert_eq!(lay("a\u{200C}b\u{200D}\u{200F}\u{FE0F}").missing, 0); + // A combining mark the chosen face lacks takes its letter along to a face with both, so + // the two are shaped together (the mark attaches) instead of in two faces. + let mark = '\u{0301}'; + if let (Some(latin), Some(both)) = ( + fonts.families().iter().find(|f| has(f, 'e') && !has(f, mark)), + FALLBACK_FAMILIES.iter().find(|f| has(f, mark)).filter(|f| has(f, 'e')), + ) { + let lay_in = |family: &str| fonts.layout("e\u{0301}", &Style { family: family.to_string(), ..style(40.0) }).unwrap(); + let (mixed, direct) = (lay_in(latin), lay_in(both)); + assert_eq!(mixed.missing, 0); + assert!((mixed.width - direct.width).abs() < 0.01, "{} vs {} in {both}", mixed.width, direct.width); + assert_eq!(mixed.outline.cmds.len(), direct.outline.cmds.len()); + } else { + eprintln!("no family with e and without U+0301 here: combining mark check skipped"); + } } #[test] From ca17bd518360b7062129cf6d9b2c253a3e4c6bce Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:55:44 +0100 Subject: [PATCH 015/570] Clamp out-of-range SetProperty values in sanitize_actions Found while testing crates/actions/src/lib.rs:398-403 (sanitize_actions) and :358-361 (Action::sanitized) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/actions/src/lib.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) 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![ From 63fc4718a50752d8cc22c2b9ec2a21cb399b54c3 Mon Sep 17 00:00:00 2001 From: nocturney Date: Wed, 11 Nov 2026 10:25:17 +0200 Subject: [PATCH 016/570] test(i18n): exempt exact product name and cover Hebrew dual plurals --- src/i18n/tests.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 971a0377..aa3b1c89 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -314,6 +314,24 @@ fn lookups_fall_back_from_app_to_shared_to_base_language_to_english() { assert_eq!(l.plural(0, "{n} frame", "{n} frames", 1), "{n} frame"); } +#[test] +fn hebrew_two_uses_the_second_catalog_plural_form() { + // Hebrew is not offered in production until RTL is supported; this exercises its + // existing parser and runtime by explicitly enabling the locale for this unit test. + let he_app = "@plural\t{n} frame|{n} frames\t{n} פריים|{n} פריימים (זוג)|{n} פריימים\n"; + let (languages, problems) = Languages::new(&[("he", "", he_app)], &["he"]); + assert!(problems.is_empty(), "{problems:?}"); + let he = languages.find("he").expect("fixture Hebrew should be offered"); + let get = |n| languages.plural(he, "{n} frame", "{n} frames", n); + assert_eq!(get(0), "{n} פריימים"); + assert_eq!(get(1), "{n} פריים"); + assert_eq!(get(2), "{n} פריימים (זוג)", "n=2 must not fall through to other"); + assert_eq!(get(3), "{n} פריימים"); + assert_eq!(get(21), "{n} פריימים"); + let n = 2u64; + assert_eq!(fill(get(n), &[("n", &n as &dyn std::fmt::Display)]), "2 פריימים (זוג)"); +} + #[test] fn every_lookup_kind_reads_the_catalog() { // The same paths `tr!`, `t_dyn`, `t_cmd` and `trn!` take with a catalog built in. @@ -467,6 +485,21 @@ fn screen() -> egui::RawInput { egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), ..Default::default() } } +// AniCraft is a product identifier, not an untranslated English UI label. Keep the +// exemption exact: a label like "AniCraft settings" must still be checked. +fn pseudo_name_is_translated_or_exempt(name: &str) -> bool { + name.chars().any(pseudo::is_accented) || EGUI_OWN.contains(&name) || name == "AniCraft" +} + +#[test] +fn pseudo_a11y_name_exception_is_only_the_product_name() { + assert!(pseudo_name_is_translated_or_exempt("AniCraft")); + assert!(pseudo_name_is_translated_or_exempt("[Šàvé ~~]")); + assert!(!pseudo_name_is_translated_or_exempt("Save")); + assert!(!pseudo_name_is_translated_or_exempt("AniCraft settings")); + assert!(!pseudo_name_is_translated_or_exempt("Save AniCraft")); +} + /// Names in `nodes` that are ours and still plain English. fn plain_names(what: &str, app: &crate::app::App, nodes: Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>) -> Vec { // Document text is the document's (layer, symbol and scene names): not ours to translate. @@ -479,7 +512,7 @@ fn plain_names(what: &str, app: &crate::app::App, nodes: Vec<(egui::accesskit::N for name in [n.label(), n.description()].into_iter().flatten() { // egui names its own window close button; it offers no way to name it ourselves // (docs/localisation.md › Not yet). - let translated = name.chars().any(pseudo::is_accented) || EGUI_OWN.contains(&name); + let translated = pseudo_name_is_translated_or_exempt(name); let ours = scan::is_prose(name) && !doc_text.contains(name) && !doc_text.iter().any(|d| name.contains(d.as_str())); if ours && !translated { found.insert(format!("[{what}] {:?} {name:?}", n.role())); From 307e496d55ef7c668694e72f4eb0e1a586de8523 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:28:08 +0000 Subject: [PATCH 017/570] Fix Vec2::length overflow for large vectors Found while testing crates/geom/src/lib.rs:46-52 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/lib.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index e0b75dd1..bfaf9db7 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -44,7 +44,7 @@ impl Vec2 { self.x * o.y - self.y * o.x } pub fn length(self) -> f32 { - self.dot(self).sqrt() + self.x.hypot(self.y) } pub fn normalized(self) -> Vec2 { let l = self.length(); @@ -197,4 +197,12 @@ mod tests { assert_eq!(v.perp().dot(v), 0.0); assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO); } + + #[test] + fn length_and_normalized_survive_huge_components() { + let v = Vec2::new(3e19, 4e19); + assert!((v.length() / 5e19 - 1.0).abs() < 1e-5, "len {}", v.length()); + let n = v.normalized(); + assert!((n.x - 0.6).abs() < 1e-5 && (n.y - 0.8).abs() < 1e-5, "{n:?}"); + } } From 5e59b2b4bf212e482ffb4a4b3fe7426468b284d6 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:17:50 +0100 Subject: [PATCH 018/570] Reject hex colours with more than one leading '#' Found while testing crates/svg/src/lib.rs:384-392 (color) via crates/doc/src/lib.rs:81-82 (Rgba::parse_hex, trim_start_matches('#')) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/lib.rs | 5 ++++- crates/svg/src/tests.rs | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 258e5431..522aed74 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -81,7 +81,8 @@ impl Rgba { } /// Parses `#rrggbb`, `rrggbb` or `#rrggbbaa`. pub fn parse_hex(s: &str) -> Option { - let h = s.trim().trim_start_matches('#'); + let s = s.trim(); + let h = s.strip_prefix('#').unwrap_or(s); if !h.is_ascii() || (h.len() != 6 && h.len() != 8) { return None; } @@ -1409,6 +1410,8 @@ mod tests { assert_eq!(c.to_hex(), "#ff8000"); assert!(Rgba::parse_hex("zz").is_none()); assert!(Rgba::parse_hex("ééé").is_none()); + assert!(Rgba::parse_hex("##ff0000").is_none()); + assert!(Rgba::parse_hex("ff0000").is_some()); } #[test] diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index a26e934a..2211303d 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -227,3 +227,10 @@ fn hostile_input_is_an_error_or_harmless() { assert!(i.report.skipped.contains_key("references nested too deeply")); assert!(i.report.skipped.contains_key("unreadable paths")); } + +#[test] +fn colour_rejects_multiple_leading_hashes() { + assert!(color("#abc").is_some()); + assert!(color("##abc").is_none()); + assert!(color("##aabbcc").is_none()); +} From 26872daa2a78fbcf3cd9a412a32e6c90ce6e8dd6 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:48:41 +0000 Subject: [PATCH 019/570] Reject malformed entries in the bezier easing param Found while testing crates/engine/src/params.rs:108-111 (opt_easing, the `bezier` branch) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/params.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs index 58363868..53bb4f9a 100644 --- a/crates/engine/src/params.rs +++ b/crates/engine/src/params.rs @@ -106,8 +106,8 @@ pub fn opt_easing(p: &Value, key: &str) -> Result> { return Ok(Some(Easing::Classic((s as f32).clamp(-100.0, 100.0)))); } if let Some(Value::Array(b)) = v.get("bezier") { - let n: Vec = b.iter().filter_map(Value::as_f64).filter(|f| f.is_finite()).map(|f| f as f32).collect(); - if let [x1, y1, x2, y2] = n[..] { + let n: Option> = b.iter().map(|x| x.as_f64().filter(|f| f.is_finite()).map(|f| f as f32)).collect(); + if let Some(&[x1, y1, x2, y2]) = n.as_deref() { return Ok(Some(Easing::CubicBezier(x1.clamp(0.0, 1.0), y1.clamp(-5.0, 5.0), x2.clamp(0.0, 1.0), y2.clamp(-5.0, 5.0)))); } } @@ -229,3 +229,18 @@ pub fn opt_stroke_style(p: &Value, base: &anicraft_doc::StrokeStyle, width: f32) }; Ok(Some(st.sanitized())) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn bezier_rejects_malformed_entries() { + for b in [json!([0.25, "oops", 0.1, 0.25, 1.0]), json!([0.25, null, 0.1, 0.25]), json!([0.25, true, 0.1, 0.25]), json!([0.25, 0.1, 0.25]), json!([0.25, 0.1, 0.25, 1.0, 0.5])] { + assert!(opt_easing(&json!({"e": {"bezier": b}}), "e").is_err(), "accepted {b}"); + } + let ok = opt_easing(&json!({"e": {"bezier": [0.25, 0.1, 0.25, 1.0]}}), "e").unwrap(); + assert_eq!(ok, Some(Easing::CubicBezier(0.25, 0.1, 0.25, 1.0))); + } +} From 4947b7d12d2b05d6e75459c9b3082c06f45404b7 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 16:38:04 +0400 Subject: [PATCH 020/570] feat(ui): draw and offer Georgian with Noto Sans Georgian from craft-fonts (M8) Embeds craft-fonts' NotoSansGeorgian.ttf (Geor) as a fallback face in every family, and offers Georgian (ka) only in builds that embedded it. Without CRAFT_FONTS_DIR nothing changes. --- ATTRIBUTION.md | 1 + build.rs | 5 +++-- docs/development.md | 2 +- docs/localisation.md | 5 +++-- src/i18n/mod.rs | 19 +++++++++++++++++-- src/i18n/tests.rs | 24 ++++++++++++++++++++++++ src/theme.rs | 15 ++++++++++++++- 7 files changed, 63 insertions(+), 8 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7cc10202..96f798ee 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -57,6 +57,7 @@ here. |---|---|---|---| | Inter Regular | UI prose (primary) | The Inter Project Authors (Rasmus Andersson) | SIL OFL 1.1, shipped as `OFL-Inter.txt` | | JetBrains Mono Regular | UI data: timeline, readouts, values, shortcuts (primary) | The JetBrains Mono Project Authors | SIL OFL 1.1, shipped as `OFL-JetBrainsMono.txt` | +| Noto Sans Georgian (variable) | Fallback face for Georgian (`Geor` in craft-fonts) | The Noto Project Authors | SIL OFL 1.1, shipped as `OFL-noto-sans-georgian.txt` | ### Optional build input: craft-i18n (not files in this repo) diff --git a/build.rs b/build.rs index fbd5c89c..482faedb 100644 --- a/build.rs +++ b/build.rs @@ -3,7 +3,8 @@ //! //! `CRAFT_FONTS_DIR= cargo build` embeds the UI typefaces chosen in //! ADR 0005: Inter (prose) and JetBrains Mono (data), both SIL OFL 1.1. Font files are never -//! committed to this repository. Without the variable the app uses egui's bundled defaults, and +//! committed to this repository. It also embeds Noto Sans Georgian (`Geor` in craft-fonts) as a +//! fallback face, which is what lets the interface offer Georgian. Without the variable the app uses egui's bundled defaults, and //! everything still works. //! //! `CRAFT_I18N_DIR=` embeds the interface catalogs (ADR 0040); without it @@ -12,7 +13,7 @@ use std::path::{Path, PathBuf}; /// Files we look for, and the generated constant each fills. -const FONTS: [(&str, &str); 2] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT")]; +const FONTS: [(&str, &str); 3] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT"), ("NotoSansGeorgian.ttf", "GEORGIAN_FONT")]; fn find(dir: &Path, name: &str, depth: u32) -> Option { let entries = std::fs::read_dir(dir).ok()?; diff --git a/docs/development.md b/docs/development.md index 167cd9f7..6a6364ed 100644 --- a/docs/development.md +++ b/docs/development.md @@ -14,7 +14,7 @@ cargo deny check licenses bans sources cargo run --release -p anicraft-cli -- bench # performance probe ``` -Fonts: builds embed Inter and JetBrains Mono when `CRAFT_FONTS_DIR` points at a craft-fonts +Fonts: builds embed Inter, JetBrains Mono and Noto Sans Georgian (the interface offers Georgian only then) when `CRAFT_FONTS_DIR` points at a craft-fonts checkout, or when one is found next to the repository (ADR 0005). Otherwise they use the built-in fallback fonts. diff --git a/docs/localisation.md b/docs/localisation.md index dc658d0b..b99691d6 100644 --- a/docs/localisation.md +++ b/docs/localisation.md @@ -96,7 +96,7 @@ and a trailing `…`. Then open a pull request in craft-i18n. Follow its clean-r from the plain meaning of the English, never from another product's translated interface. A language is offered once craft-i18n has its `anicraft.tsv` and it is in `i18n::READY` -(left-to-right Latin, Greek and Cyrillic scripts today). +(left-to-right Latin, Greek and Cyrillic scripts today, and Georgian in builds with its craft-fonts face). ## Building with translations @@ -118,7 +118,8 @@ shaping. So: | Script | Today | |---|---| | Latin, Greek, Cyrillic | Offered when a catalog exists. | -| Chinese, Japanese, Korean, Georgian | Draw correctly, but need a font the app doesn't bundle (a craft-fonts face), then a `READY` entry. | +| Georgian | Offered when a catalog exists and the build embedded Noto Sans Georgian from craft-fonts (`i18n::ready_codes`); without `CRAFT_FONTS_DIR` it stays hidden. | +| Chinese, Japanese, Korean | Draw correctly, but need a font the app doesn't bundle (a craft-fonts face), then a `READY` entry. | | Arabic, Hebrew, Persian, Urdu, Kurdish, Dhivehi | Not offered: right to left needs bidi and shaping in egui's text layout, and mirrored widgets. We follow upstream egui rather than fork it. | | Devanagari, Bengali, Tamil, Telugu, Thai, Lao | Not offered: they need shaping. | | Vietnamese | Not offered yet: needs a check that every fallback face has its letters. | diff --git a/src/i18n/mod.rs b/src/i18n/mod.rs index fe04cb2b..5d2c4721 100644 --- a/src/i18n/mod.rs +++ b/src/i18n/mod.rs @@ -39,11 +39,26 @@ pub const PSEUDO: &str = "pseudo"; /// Languages the interface can be drawn in today: written left to right, in scripts the bundled /// faces cover and egui lays out a letter at a time (Latin, Greek, Cyrillic). A catalog for any /// other locale is embedded but not offered (docs/localisation.md › Scripts and direction). -/// A regional variant (`es-mx`) is ready when its language is. +/// A regional variant (`es-mx`) is ready when its language is. Georgian is not listed here: its +/// face is not bundled, so [`ready_codes`] adds it only when the build embedded Noto Sans +/// Georgian from craft-fonts. pub const READY: &[&str] = &[ "az", "bg", "bs", "ca", "cs", "da", "de", "el", "es", "et", "fi", "fr", "gl", "hr", "hu", "id", "it", "kk", "lt", "lv", "nb", "nl", "pl", "pt", "pt-br", "ro", "ru", "sk", "sl", "sq", "sr", "sr-latn", "sv", "tr", "uk", ]; +/// [`READY`] plus the languages whose script needs a craft-fonts face this build embedded. +pub fn ready_codes() -> Vec<&'static str> { + ready_with(crate::theme::georgian_font().is_some()) +} + +fn ready_with(georgian_face: bool) -> Vec<&'static str> { + let mut codes = READY.to_vec(); + if georgian_face { + codes.push("ka"); + } + codes +} + enum Kind { English, Pseudo, @@ -177,7 +192,7 @@ impl Languages { static ENGLISH_LANGUAGE: Language = Language { code: String::new(), name: String::new(), kind: Kind::English }; static LANGUAGES: LazyLock = LazyLock::new(|| { - let (languages, problems) = Languages::new(CRAFT_I18N, READY); + let (languages, problems) = Languages::new(CRAFT_I18N, &ready_codes()); for p in problems { eprintln!("interface catalog: {p} (shown in English)"); } diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 971a0377..9cbd4ff8 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -293,6 +293,30 @@ fn offered_languages_have_their_own_catalog_and_a_ready_script() { assert_eq!(names, ["English", "Deutsch", "Português (Brasil)", "Русский", "Pseudo-locale (layout test)"]); } +#[test] +fn georgian_is_offered_only_when_its_face_is_embedded() { + let ka = [("ka", "", "@id\tlanguage.name\tქართული\n")]; + let offered = |face: bool| Languages::new(&ka, &ready_with(face)).0.list.iter().any(|l| l.code == "ka"); + assert!(!offered(false), "no face, no Georgian"); + assert!(offered(true)); + // The real build agrees with its own face. + assert_eq!(ready_codes().contains(&"ka"), crate::theme::georgian_font().is_some()); + // CRAFT_FONTS_REQUIRED=1 (release builds, CI with craft-fonts) makes a missing face a failure. + let face = crate::theme::georgian_font(); + if std::env::var("CRAFT_FONTS_REQUIRED").is_ok_and(|v| v == "1") && std::env::var_os("CRAFT_FONTS_DIR").is_some() { + assert!(face.is_some(), "CRAFT_FONTS_DIR has no NotoSansGeorgian.ttf (craft-fonts `Geor`)"); + } + let Some(face) = face else { + println!("georgian face test: skipped, this build embeds no Georgian face"); + return; + }; + let letters: String = ('\u{10D0}'..='\u{10FA}').collect(); + let fonts = anicraft_engine::text::Fonts::from_faces([face.to_vec()]); + let laid = fonts.layout(&letters, &anicraft_engine::text::Style::default()).expect("layout"); + assert_eq!(laid.missing, 0, "the face lacks some of U+10D0..U+10FA"); + println!("georgian face test: ran, {} letters covered", letters.chars().count()); +} + #[test] fn lookups_fall_back_from_app_to_shared_to_base_language_to_english() { let l = fixture(); diff --git a/src/theme.rs b/src/theme.rs index 7043277a..1d1fb1fc 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -368,6 +368,12 @@ pub fn embedded_fonts() -> Vec> { [craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect() } +/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded it. The interface offers +/// Georgian only then (`i18n::ready_codes`). +pub fn georgian_font() -> Option<&'static [u8]> { + craft_fonts::GEORGIAN_FONT +} + /// Which typefaces are active (for About and diagnostics), in the interface language. pub fn font_summary() -> String { match (craft_fonts::UI_FONT, craft_fonts::MONO_FONT) { @@ -383,7 +389,8 @@ pub type UserFont = (String, Vec, u32); /// Installs the UI typefaces (ADR 0005). Order in each family: the user's system font (from /// Preferences), then the craft-fonts pair (when embedded at build time), then egui's bundled -/// fonts, which stay as fallbacks for glyph coverage. +/// fonts, which stay as fallbacks for glyph coverage, then Noto Sans Georgian (when embedded) +/// for the letters none of them has. pub fn install_fonts(ctx: &egui::Context, ui_font: Option<&UserFont>, data_font: Option<&UserFont>) { use egui::{FontData, FontDefinitions, FontFamily}; use std::sync::Arc; @@ -394,6 +401,12 @@ pub fn install_fonts(ctx: &egui::Context, ui_font: Option<&UserFont>, data_font: defs.families.entry(family).or_default().insert(0, name.to_owned()); } } + if let Some(b) = craft_fonts::GEORGIAN_FONT { + defs.font_data.insert("craft-noto-sans-georgian".to_owned(), Arc::new(FontData::from_static(b))); + for family in [FontFamily::Proportional, FontFamily::Monospace] { + defs.families.entry(family).or_default().push("craft-noto-sans-georgian".to_owned()); + } + } for (user, family) in [(ui_font, FontFamily::Proportional), (data_font, FontFamily::Monospace)] { if let Some((name, bytes, index)) = user { let key = format!("user:{name}"); From 20cfea4aead772eb838f32b443c6c5a244676ab7 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 16:49:25 +0400 Subject: [PATCH 021/570] style: wrap the FONTS table at max_width (M8) --- build.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build.rs b/build.rs index 482faedb..aae5c0d7 100644 --- a/build.rs +++ b/build.rs @@ -13,7 +13,8 @@ use std::path::{Path, PathBuf}; /// Files we look for, and the generated constant each fills. -const FONTS: [(&str, &str); 3] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT"), ("NotoSansGeorgian.ttf", "GEORGIAN_FONT")]; +const FONTS: [(&str, &str); 3] = + [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT"), ("NotoSansGeorgian.ttf", "GEORGIAN_FONT")]; fn find(dir: &Path, name: &str, depth: u32) -> Option { let entries = std::fs::read_dir(dir).ok()?; From 39cc5484d5cb2fe9d1b49f449dac3fab6d04b3ad Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:13:21 +0400 Subject: [PATCH 022/570] fix(i18n): validate the Georgian face before offering or loading it; REQUIRED alone enforces it (M8) --- docs/localisation.md | 2 +- src/i18n/tests.rs | 12 ++++++++++-- src/theme.rs | 24 ++++++++++++++++++++---- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/docs/localisation.md b/docs/localisation.md index b99691d6..cbf65cbb 100644 --- a/docs/localisation.md +++ b/docs/localisation.md @@ -118,7 +118,7 @@ shaping. So: | Script | Today | |---|---| | Latin, Greek, Cyrillic | Offered when a catalog exists. | -| Georgian | Offered when a catalog exists and the build embedded Noto Sans Georgian from craft-fonts (`i18n::ready_codes`); without `CRAFT_FONTS_DIR` it stays hidden. | +| Georgian | Offered when a catalog exists and the build embedded a valid Noto Sans Georgian from craft-fonts (via `CRAFT_FONTS_DIR` or the nearby checkout `build.rs` discovers); hidden only when it did not (`i18n::ready_codes`). | | Chinese, Japanese, Korean | Draw correctly, but need a font the app doesn't bundle (a craft-fonts face), then a `READY` entry. | | Arabic, Hebrew, Persian, Urdu, Kurdish, Dhivehi | Not offered: right to left needs bidi and shaping in egui's text layout, and mirrored widgets. We follow upstream egui rather than fork it. | | Devanagari, Bengali, Tamil, Telugu, Thai, Lao | Not offered: they need shaping. | diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 9cbd4ff8..5680fcbd 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -303,8 +303,8 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { assert_eq!(ready_codes().contains(&"ka"), crate::theme::georgian_font().is_some()); // CRAFT_FONTS_REQUIRED=1 (release builds, CI with craft-fonts) makes a missing face a failure. let face = crate::theme::georgian_font(); - if std::env::var("CRAFT_FONTS_REQUIRED").is_ok_and(|v| v == "1") && std::env::var_os("CRAFT_FONTS_DIR").is_some() { - assert!(face.is_some(), "CRAFT_FONTS_DIR has no NotoSansGeorgian.ttf (craft-fonts `Geor`)"); + if std::env::var("CRAFT_FONTS_REQUIRED").is_ok_and(|v| v == "1") { + assert!(face.is_some(), "CRAFT_FONTS_REQUIRED=1 but this build embeds no valid NotoSansGeorgian.ttf (craft-fonts `Geor`)"); } let Some(face) = face else { println!("georgian face test: skipped, this build embeds no Georgian face"); @@ -314,6 +314,14 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { let fonts = anicraft_engine::text::Fonts::from_faces([face.to_vec()]); let laid = fonts.layout(&letters, &anicraft_engine::text::Style::default()).expect("layout"); assert_eq!(laid.missing, 0, "the face lacks some of U+10D0..U+10FA"); + // ... and through the families the app really builds (Proportional and Monospace). + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, None, None); + let _ = ctx.run(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let id = egui::FontId::new(14.0, family.clone()); + assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); + } println!("georgian face test: ran, {} letters covered", letters.chars().count()); } diff --git a/src/theme.rs b/src/theme.rs index 1d1fb1fc..b5f9541e 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -368,10 +368,26 @@ pub fn embedded_fonts() -> Vec> { [craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect() } -/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded it. The interface offers -/// Georgian only then (`i18n::ready_codes`). +/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded a face that parses. The +/// interface offers Georgian only then (`i18n::ready_codes`), and `install_fonts` loads the same +/// face: epaint panics on bytes it cannot parse, so a damaged file must never reach it. pub fn georgian_font() -> Option<&'static [u8]> { - craft_fonts::GEORGIAN_FONT + static FACE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *FACE.get_or_init(|| craft_fonts::GEORGIAN_FONT.filter(|b| parses_as_font(b))) +} + +/// Whether `bytes` is a font file (any face in it parses). +fn parses_as_font(bytes: &[u8]) -> bool { + !anicraft_engine::text::Fonts::from_faces([bytes.to_vec()]).families().is_empty() +} + +#[cfg(test)] +mod georgian_face_tests { + #[test] + fn garbage_bytes_are_not_a_font() { + assert!(!super::parses_as_font(b"not a font file at all")); + assert!(!super::parses_as_font(&[])); + } } /// Which typefaces are active (for About and diagnostics), in the interface language. @@ -401,7 +417,7 @@ pub fn install_fonts(ctx: &egui::Context, ui_font: Option<&UserFont>, data_font: defs.families.entry(family).or_default().insert(0, name.to_owned()); } } - if let Some(b) = craft_fonts::GEORGIAN_FONT { + if let Some(b) = georgian_font() { defs.font_data.insert("craft-noto-sans-georgian".to_owned(), Arc::new(FontData::from_static(b))); for family in [FontFamily::Proportional, FontFamily::Monospace] { defs.families.entry(family).or_default().push("craft-noto-sans-georgian".to_owned()); From 55a0b3442b7eca6faefd1ebb827de57a3addd094 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:14:24 +0400 Subject: [PATCH 023/570] fix(i18n): run the headless frame with run_ui (M8) --- src/i18n/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 5680fcbd..ecce0a7c 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -317,7 +317,7 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { // ... and through the families the app really builds (Proportional and Monospace). let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx, None, None); - let _ = ctx.run(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame + let _ = ctx.run_ui(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { let id = egui::FontId::new(14.0, family.clone()); assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); From 7f649051bc3d2e9a5669a166498a0a77bf9e7727 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:17:36 +0400 Subject: [PATCH 024/570] fix(i18n): clear the headless frame's texture deltas in the font test (M8) --- src/i18n/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index ecce0a7c..ae1bc903 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -317,7 +317,7 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { // ... and through the families the app really builds (Proportional and Monospace). let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx, None, None); - let _ = ctx.run_ui(egui::RawInput::default(), |_| {}); // fonts apply at the start of a frame + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); // fonts apply at the start of a frame for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { let id = egui::FontId::new(14.0, family.clone()); assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); From 2be050fcab3a813828caad2a80251d6636df9c09 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:24:57 +0400 Subject: [PATCH 025/570] test(i18n): check Georgian coverage through the Proportional family install_fonts builds (M8) --- src/i18n/tests.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index ae1bc903..221dee02 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -314,14 +314,13 @@ fn georgian_is_offered_only_when_its_face_is_embedded() { let fonts = anicraft_engine::text::Fonts::from_faces([face.to_vec()]); let laid = fonts.layout(&letters, &anicraft_engine::text::Style::default()).expect("layout"); assert_eq!(laid.missing, 0, "the face lacks some of U+10D0..U+10FA"); - // ... and through the families the app really builds (Proportional and Monospace). + // ... and through the Proportional family install_fonts builds. Not Monospace: epaint's + // has_glyph is a false negative there (the Georgian face is that chain's replacement-glyph face). let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx, None, None); ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); // fonts apply at the start of a frame - for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - let id = egui::FontId::new(14.0, family.clone()); - assert!(ctx.fonts_mut(|f| f.has_glyphs(&id, &letters)), "{family:?} lacks Georgian letters"); - } + let prop = egui::FontId::proportional(14.0); + assert!(ctx.fonts_mut(|f| f.has_glyphs(&prop, &letters)), "Proportional lacks Georgian letters"); println!("georgian face test: ran, {} letters covered", letters.chars().count()); } From 5b352fe2642de4f1cbe44fbd5c4b73acdc36faab Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 20:36:03 +0400 Subject: [PATCH 026/570] fix(i18n): offer Georgian only when the embedded face covers its letters (M8) --- src/theme.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/theme.rs b/src/theme.rs index b5f9541e..383ae498 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -368,7 +368,8 @@ pub fn embedded_fonts() -> Vec> { [craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect() } -/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded a face that parses. The +/// Noto Sans Georgian (craft-fonts `Geor`) when this build embedded a face that parses and covers +/// the Georgian letters. The /// interface offers Georgian only then (`i18n::ready_codes`), and `install_fonts` loads the same /// face: epaint panics on bytes it cannot parse, so a damaged file must never reach it. pub fn georgian_font() -> Option<&'static [u8]> { @@ -376,9 +377,11 @@ pub fn georgian_font() -> Option<&'static [u8]> { *FACE.get_or_init(|| craft_fonts::GEORGIAN_FONT.filter(|b| parses_as_font(b))) } -/// Whether `bytes` is a font file (any face in it parses). +/// Whether `bytes` is a font file that draws every Georgian letter (U+10D0..U+10FA). fn parses_as_font(bytes: &[u8]) -> bool { - !anicraft_engine::text::Fonts::from_faces([bytes.to_vec()]).families().is_empty() + let letters: String = ('\u{10D0}'..='\u{10FA}').collect(); + let fonts = anicraft_engine::text::Fonts::from_faces([bytes.to_vec()]); + fonts.layout(&letters, &anicraft_engine::text::Style::default()).is_ok_and(|laid| laid.missing == 0) } #[cfg(test)] From 30472641fb3712b65835f46db1ee7e2a8d216edc Mon Sep 17 00:00:00 2001 From: mypenc Date: Wed, 11 Nov 2026 23:28:44 +0000 Subject: [PATCH 027/570] feat(transform): skew/shear by dragging a box edge in Free Transform (#174) --- CHANGELOG.md | 3 +++ src/app.rs | 5 ++++- src/stage.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65528a94..a18830cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,9 @@ `prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes `cx`/`cy` and `layer: "active"`. +* **Free Transform: skew and shear** (#174). Dragging the line between two handles of the + selection box shears the artwork along that edge, as in Adobe Animate: the opposite edge stays + put and Alt skews about the centre. The cursor shows the direction. * **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5). * A sound on a button's **Over** or **Down** frame plays when the pointer goes over or presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format diff --git a/src/app.rs b/src/app.rs index e610aca4..8386fdf9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -129,7 +129,7 @@ impl Tool { Tool::Eraser => tr_noop!("Drag to erase lines and fills drawn with Object Drawing off (drawing objects and symbols are kept). [ and ] change the size; the options set the shape and erase mode, and the Faucet deletes a whole fill or line with a click. Double-click the tool to erase everything on the stage."), Tool::Width => tr_noop!("Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it."), Tool::Bone => tr_noop!("Drag from one symbol instance to another to join them with a bone (they move to an armature layer); start on a bone's end to continue the chain. Click a bone to select it. Pose the armature by dragging bones or instances with the Selection tool."), - Tool::Transform => tr_noop!("Drag a corner or edge to scale (Shift keeps proportions, Alt scales from the centre), just outside a corner to rotate (Shift snaps 15°), inside to move."), + Tool::Transform => tr_noop!("Drag a handle to scale (Shift keeps proportions, Alt scales from the centre), a line between handles to skew (Alt skews about the centre), just outside a corner to rotate (Shift snaps 15°), inside to move."), Tool::Rect => tr_noop!("Drag to draw a rectangle. Shift draws a square."), Tool::Oval => tr_noop!("Drag to draw an oval. Shift draws a circle."), Tool::Star => tr_noop!("Drag from the centre to draw a star."), @@ -247,6 +247,9 @@ pub enum XfKind { /// Handle position: -1/0/1 on each axis (corner, edge or centre). Scale { hx: i8, hy: i8 }, Rotate, + /// Dragging the line between two handles shears along that edge (the sign is which edge: + /// `hx` is -1/1 on the left/right edge, `hy` is -1/1 on the top/bottom, the other is 0). + Skew { hx: i8, hy: i8 }, } /// A small text prompt standing in for native file dialogs (M0). diff --git a/src/stage.rs b/src/stage.rs index 583b6e86..f71647ea 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -334,6 +334,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Some(XfKind::Scale { hx, hy }) if hx * hy < 0 => CursorIcon::ResizeNeSw, Some(XfKind::Scale { hx: 0, .. }) => CursorIcon::ResizeVertical, Some(XfKind::Scale { .. }) => CursorIcon::ResizeHorizontal, + Some(XfKind::Skew { hy: 0, .. }) => CursorIcon::ResizeVertical, + Some(XfKind::Skew { .. }) => CursorIcon::ResizeHorizontal, Some(XfKind::Rotate) => CursorIcon::Alias, Some(XfKind::Move) => CursorIcon::Move, None => CursorIcon::Default, @@ -1398,6 +1400,8 @@ fn text_editor(app: &mut App, ui: &mut egui::Ui, stage_origin: Pos2, zoom: f32) /// Screen-space handle size and the rotation zone just outside each corner. const HANDLE: f32 = 8.0; const ROTATE_ZONE: f32 = 22.0; +/// How far from a box edge line (screen space) a press still grabs it to skew. +const SKEW_ZONE: f32 = 5.0; fn bounds_arr(b: anicraft_engine::geom::Rect) -> Option<[f32; 4]> { (!b.is_empty()).then_some([b.min.x, b.min.y, b.max.x, b.max.y]) @@ -1416,6 +1420,19 @@ fn xf_zone(r: Rect, p: Pos2) -> Option { return Some(XfKind::Scale { hx, hy }); } } + // The line between two handles skews (Animate parity, #174); the handles above win at the ends. + let near = |a: f32, b: f32| (a - b).abs() <= SKEW_ZONE; + if (r.left() - SKEW_ZONE..=r.right() + SKEW_ZONE).contains(&p.x) && (r.top() - SKEW_ZONE..=r.bottom() + SKEW_ZONE).contains(&p.y) { + if near(p.y, r.top()) { + return Some(XfKind::Skew { hx: 0, hy: -1 }); + } else if near(p.y, r.bottom()) { + return Some(XfKind::Skew { hx: 0, hy: 1 }); + } else if near(p.x, r.left()) { + return Some(XfKind::Skew { hx: -1, hy: 0 }); + } else if near(p.x, r.right()) { + return Some(XfKind::Skew { hx: 1, hy: 0 }); + } + } if !r.contains(p) && [r.left_top(), r.right_top(), r.left_bottom(), r.right_bottom()].iter().any(|c| c.distance(p) <= ROTATE_ZONE) { return Some(XfKind::Rotate); } @@ -1463,6 +1480,20 @@ pub(crate) fn xf_total(kind: XfKind, b: [f32; 4], start: Pos2, cur: Pos2, shift: let clamp = |s: f32| if s.abs() < 0.01 { 0.01f32.copysign(if s == 0.0 { 1.0 } else { s }) } else { s }; about(px, py, Affine::scale(clamp(sx), clamp(sy))) } + XfKind::Skew { hx, hy } => { + // Top and bottom edges slide sideways, left and right edges slide up and down; the + // opposite edge stays put (Alt: the centre does), so the grabbed edge follows the pointer. + let k = |moved: f32, arm: f32| if arm.abs() < 1e-3 { 0.0 } else { (moved / arm).clamp(-8.0, 8.0) }; + if hy != 0 { + let py = if alt { cy } else { [y1, cy, y0][(hy + 1) as usize] }; + let shear = k(cur.x - start.x, start.y - py); + about(cx, py, Affine { m: [1.0, 0.0, shear, 1.0, 0.0, 0.0] }) + } else { + let px = if alt { cx } else { [x1, cx, x0][(hx + 1) as usize] }; + let shear = k(cur.y - start.y, start.x - px); + about(px, cy, Affine { m: [1.0, shear, 0.0, 1.0, 0.0, 0.0] }) + } + } XfKind::Rotate => { let a0 = (start.y - cy).atan2(start.x - cx); let a1 = (cur.y - cy).atan2(cur.x - cx); @@ -1601,11 +1632,34 @@ mod xf_tests { assert!((angle / 15.0 - (angle / 15.0).round()).abs() < 1e-3, "{angle}"); } + #[test] + fn dragging_the_top_edge_shears_sideways_about_the_bottom_edge() { + // B is 100 x 50: dragging the top edge 10 right moves the top edge 10 right. + let m = xf_total(XfKind::Skew { hx: 0, hy: -1 }, B, pos2(50.0, 0.0), pos2(60.0, 0.0), false, false); + assert_eq!(apply(&m, 0.0, 0.0), Vec2::new(10.0, 0.0)); + assert_eq!(apply(&m, 0.0, 50.0), Vec2::new(0.0, 50.0), "the opposite edge stays put"); + assert!((m.determinant() - 1.0).abs() < 1e-5, "a shear keeps the area"); + } + + #[test] + fn dragging_the_right_edge_shears_vertically_and_alt_pivots_on_the_centre() { + let m = xf_total(XfKind::Skew { hx: 1, hy: 0 }, B, pos2(100.0, 25.0), pos2(100.0, 35.0), false, false); + assert_eq!(apply(&m, 100.0, 0.0), Vec2::new(100.0, 10.0)); + assert_eq!(apply(&m, 0.0, 0.0), Vec2::new(0.0, 0.0)); + let m = xf_total(XfKind::Skew { hx: 1, hy: 0 }, B, pos2(100.0, 25.0), pos2(100.0, 35.0), false, true); + assert_eq!(apply(&m, 50.0, 25.0), Vec2::new(50.0, 25.0), "centre stays put"); + assert_eq!(apply(&m, 100.0, 25.0), Vec2::new(100.0, 35.0)); + } + #[test] fn zones() { let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); assert_eq!(xf_zone(r, pos2(300.0, 200.0)), Some(XfKind::Scale { hx: 1, hy: 1 })); assert_eq!(xf_zone(r, pos2(200.0, 100.0)), Some(XfKind::Scale { hx: 0, hy: -1 })); + assert_eq!(xf_zone(r, pos2(150.0, 101.0)), Some(XfKind::Skew { hx: 0, hy: -1 })); + assert_eq!(xf_zone(r, pos2(150.0, 199.0)), Some(XfKind::Skew { hx: 0, hy: 1 })); + assert_eq!(xf_zone(r, pos2(99.0, 130.0)), Some(XfKind::Skew { hx: -1, hy: 0 })); + assert_eq!(xf_zone(r, pos2(301.0, 130.0)), Some(XfKind::Skew { hx: 1, hy: 0 })); assert_eq!(xf_zone(r, pos2(312.0, 212.0)), Some(XfKind::Rotate)); assert_eq!(xf_zone(r, pos2(200.0, 150.0)), Some(XfKind::Move)); assert_eq!(xf_zone(r, pos2(500.0, 500.0)), None); From 882668b88c244f87971db50064860a3dfdbdee35 Mon Sep 17 00:00:00 2001 From: lienatanael1-beep Date: Thu, 12 Nov 2026 15:08:24 +0700 Subject: [PATCH 028/570] feat(control): live control port and MCP bridge `anicraft --control ` opens a JSON-lines control port on 127.0.0.1; `anicraft-cli mcp --bridge ` serves the same five MCP tools against the open window. The app runs the CLI's own `mcp::call_tool` (now generic over a `Host`), so live and headless share one dispatcher. A per-run token is written to control.json in the settings folder and removed on exit. Edits wait while the person drags, so undo steps never merge. ADR 0070, docs/control-protocol.md. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 + Cargo.lock | 2 + Cargo.toml | 3 + crates/cli/Cargo.toml | 5 +- crates/cli/src/control.rs | 493 +++++++++++++++++++++++++++++ crates/cli/src/control/tests.rs | 253 +++++++++++++++ crates/cli/src/lib.rs | 14 + crates/cli/src/mcp.rs | 82 ++++- docs/adr/0070-live-control-port.md | 99 ++++++ docs/adr/README.md | 1 + docs/control-protocol.md | 103 ++++++ docs/mcp.md | 30 ++ docs/roadmap.md | 2 +- src/app.rs | 10 + src/main.rs | 42 ++- src/panels.rs | 7 + src/platform.rs | 25 ++ src/remote.rs | 143 +++++++++ 18 files changed, 1308 insertions(+), 21 deletions(-) create mode 100644 crates/cli/src/control.rs create mode 100644 crates/cli/src/control/tests.rs create mode 100644 docs/adr/0070-live-control-port.md create mode 100644 docs/control-protocol.md create mode 100644 src/remote.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b58bef9f..f521c0a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +* **Remote control: assistants edit the open window live** (ADR 0070). + * `anicraft --control 9878` opens AniCraft as usual and lets an assistant edit the document you + have open, through a port on this computer only. Its edits appear at once and undo with + Ctrl+Z, like yours; the status bar says "Remote control on (port 9878)" while it is open. Also + `ANICRAFT_CONTROL_PORT`. + * `anicraft-cli mcp --bridge 9878`: the MCP server's five tools, acting on that window. It starts + before AniCraft is open, connects on the first call, says how to start AniCraft when it isn't + running, and reconnects after AniCraft is reopened. + * No setup: each run makes a fresh token and writes it to `control.json` in AniCraft's settings + folder (only you can read it), where the bridge finds it. `ANICRAFT_CONTROL_TOKEN` overrides it. + * While you drag, the assistant's edits wait until you let go, so the two never share an undo step. + * The protocol (`docs/control-protocol.md`): JSON lines on `127.0.0.1`; `hello`, `tools.list`, + `tools.call`; anything that isn't a JSON request (such as a web page's request to localhost) is + refused. + * **The user guide** (ADR 0069, M8). * **Help › User Guide** opens AniCraft's guide in your browser. It comes with the app, so it works offline; the web editor serves it beside the editor. It is also in the command palette. diff --git a/Cargo.lock b/Cargo.lock index c4297341..ed118141 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -219,6 +219,7 @@ name = "anicraft" version = "0.2.1" dependencies = [ "anicraft-audio", + "anicraft-cli", "anicraft-doc", "anicraft-engine", "anicraft-geom", @@ -269,6 +270,7 @@ dependencies = [ "anicraft-geom", "anicraft-guide", "anicraft-render", + "getrandom 0.3.4", "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 2c6d31cb..334a68e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -112,6 +112,9 @@ sys-locale = "0.3" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The user guide, bundled for Help › User Guide (ADR 0069). The web build serves it as pages instead. anicraft-guide.workspace = true +# The live control port and the tools it serves (ADR 0070): the same dispatcher as the +# headless MCP server, so live and headless never drift. +anicraft-cli = { path = "crates/cli" } craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" } eframe = { workspace = true, features = ["links"] } diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 621e7b3f..4d3a2546 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "anicraft-cli" -description = "AniCraft L4: headless CLI and JSON-lines control channel for agents and pipelines" +description = "AniCraft L4: headless CLI, MCP server and the desktop app's live control channel" version.workspace = true edition.workspace = true license.workspace = true @@ -21,6 +21,9 @@ anicraft-render.workspace = true anicraft-geom.workspace = true anicraft-guide.workspace = true serde_json.workspace = true +# The live control port's per-run token (ADR 0070): the operating system's random numbers. +# MIT OR Apache-2.0, already in the tree. +getrandom = "0.3" [lints] workspace = true diff --git a/crates/cli/src/control.rs b/crates/cli/src/control.rs new file mode 100644 index 00000000..adb1d256 --- /dev/null +++ b/crates/cli/src/control.rs @@ -0,0 +1,493 @@ +//! The live control channel (ADR 0070, `docs/control-protocol.md`): the desktop app's control +//! port, and the client `anicraft-cli mcp --bridge ` uses to reach it. +//! +//! The app listens on `127.0.0.1` only. Each connection carries one JSON object per line each +//! way, answered in order. Every request carries the run's token, which the app writes to +//! `control.json` in the AniCraft settings folder, so a client running as the same user finds it +//! with no setup. The tools are the MCP server's ([`crate::mcp::tools`], [`crate::mcp::call_tool`]), +//! so live and headless never drift. +//! +//! Nothing here touches the window: [`listen`] hands each tool call to whoever drains +//! [`Server::try_recv`] (the app's frame loop), with a channel for the answer. + +use crate::mcp; +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; +use std::time::{Duration, Instant}; + +/// The wire protocol's version, reported by `hello`. +pub const PROTOCOL: u32 = 1; +/// The port AniCraft's documentation and shortcuts use (VectorCraft 7979, CadCraft 7980, +/// FilmCraft 9876, EffectCraft 9877). +pub const DEFAULT_PORT: u16 = 9878; +/// Longest request or reply line, in bytes. +pub const MAX_LINE: usize = 4 * 1024 * 1024; +/// Most connections open at once. +pub const MAX_CONNECTIONS: usize = 16; +/// How long a tool call may wait for the app (a frame, or the end of the person's drag). +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); +/// Extra time the connection waits past the deadline: a call that started just before it +/// still gets its real answer. +const GRACE: Duration = Duration::from_secs(10); +/// Overrides the generated token on both sides (CI, power users). +pub const TOKEN_ENV: &str = "ANICRAFT_CONTROL_TOKEN"; +/// The port when `--control` isn't given. +pub const PORT_ENV: &str = "ANICRAFT_CONTROL_PORT"; +/// The file the app writes in the settings folder while its control port is open. +pub const CONTROL_FILE: &str = "control.json"; + +/// AniCraft's settings folder: %APPDATA%\AniCraft, ~/Library/Application Support/AniCraft, or +/// $XDG_CONFIG_HOME/anicraft (default ~/.config/anicraft). The shell's `platform::config_dir` +/// owns this rule; a shell test keeps the two the same (this crate can't use the shell). +pub fn settings_dir() -> Option { + let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from); + if cfg!(windows) { + env("APPDATA").map(|p| p.join("AniCraft")) + } else if cfg!(target_os = "macos") { + env("HOME").map(|p| p.join("Library").join("Application Support").join("AniCraft")) + } else { + env("XDG_CONFIG_HOME").or_else(|| env("HOME").map(|h| h.join(".config"))).map(|p| p.join("anicraft")) + } +} + +/// Where `control.json` lives. +pub fn control_file() -> Option { + settings_dir().map(|d| d.join(CONTROL_FILE)) +} + +/// `ANICRAFT_CONTROL_TOKEN`, when set and not blank. +pub fn token_from_env() -> Option { + std::env::var(TOKEN_ENV).ok().map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) +} + +/// A fresh token: 32 random bytes from the operating system, as 64 hex digits. +pub fn new_token() -> Result { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).map_err(|e| format!("no random numbers from the system: {e}"))?; + Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Reads a port: a number from 1 to 65535. +pub fn parse_port(s: &str) -> Result { + match s.trim().parse::() { + Ok(p) if p > 0 => Ok(p), + _ => Err(format!("'{s}' is not a port: use a number from 1 to 65535, such as {DEFAULT_PORT}")), + } +} + +/// What `control.json` holds. +#[derive(Clone, Debug, PartialEq)] +pub struct ControlFile { + pub port: u16, + pub token: String, + pub pid: u32, + pub version: String, +} + +impl ControlFile { + pub fn to_json(&self) -> Value { + json!({"port": self.port, "token": self.token, "pid": self.pid, "version": self.version}) + } + pub fn parse(text: &str) -> Result { + let v: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{CONTROL_FILE} is not JSON: {e}"))?; + let token = v.get("token").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| format!("{CONTROL_FILE} has no token"))?; + let port = v.get("port").and_then(Value::as_u64).and_then(|p| u16::try_from(p).ok()).ok_or_else(|| format!("{CONTROL_FILE} has no port"))?; + let pid = v.get("pid").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()).unwrap_or(0); + let version = v.get("version").and_then(Value::as_str).unwrap_or("").to_string(); + Ok(ControlFile { port, token: token.to_string(), pid, version }) + } +} + +/// Why a line could not be read. +#[derive(Debug)] +pub enum LineError { + TooLong, + NotText, + Io(std::io::Error), +} + +/// Reads one line (without its line break), at most `limit` bytes; `Ok(None)` at the end. +pub fn read_line(r: &mut R, limit: usize) -> Result, LineError> { + let mut buf = Vec::new(); + let cap = u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1); + let n = r.by_ref().take(cap).read_until(b'\n', &mut buf).map_err(LineError::Io)?; + if n == 0 { + return Ok(None); + } + if buf.last() == Some(&b'\n') { + buf.pop(); + } else if buf.len() > limit { + return Err(LineError::TooLong); + } + if buf.len() > limit { + return Err(LineError::TooLong); + } + if buf.last() == Some(&b'\r') { + buf.pop(); + } + String::from_utf8(buf).map(Some).map_err(|_| LineError::NotText) +} + +/// One request off the wire. +#[derive(Debug, PartialEq)] +pub struct Incoming { + pub id: Value, + pub token: Option, + pub method: String, + pub params: Value, +} + +/// Reads a request line: a JSON object with a string `method`. Anything else (an HTTP request +/// line, which is how a web page's `fetch` to localhost begins, included) is refused. +pub fn parse_request(line: &str) -> Result { + let v: Value = serde_json::from_str(line.trim_start_matches('\u{feff}')).map_err(|_| "expected one JSON object per line, such as {\"id\":1,\"token\":\"…\",\"method\":\"hello\"}".to_string())?; + let Value::Object(mut o) = v else { return Err("expected a JSON object".into()) }; + let method = match o.remove("method") { + Some(Value::String(m)) => m, + _ => return Err("the request needs a string \"method\"".into()), + }; + let token = match o.remove("token") { + Some(Value::String(t)) => Some(t), + _ => None, + }; + Ok(Incoming { id: o.remove("id").unwrap_or(Value::Null), token, method, params: o.remove("params").unwrap_or_else(|| json!({})) }) +} + +/// Compares tokens in time that doesn't depend on where they differ. +pub fn token_matches(given: Option<&str>, expected: &str) -> bool { + let Some(given) = given else { return false }; + let (a, b) = (given.as_bytes(), expected.as_bytes()); + a.len() == b.len() && !b.is_empty() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +fn ok(id: &Value, result: Value) -> Value { + json!({"id": id, "ok": true, "result": result}) +} + +fn fail(id: &Value, error: impl Into) -> Value { + json!({"id": id, "ok": false, "error": error.into()}) +} + +/// The message when a tool call never got its turn. +pub const BUSY: &str = "AniCraft was busy for 60 s (an edit in progress in the window, such as a drag, typing or a plug-in dialog), so this call was not run. Try again."; + +/// A tool call waiting for the app's frame loop. +pub struct Request { + pub name: String, + pub arguments: Value, + deadline: Instant, + reply: Sender>, +} + +impl Request { + /// Whether it can change the document (and so waits for the person's own gesture to end). + pub fn changes_document(&self) -> bool { + mcp::tool_changes_document(&self.name) + } + /// Past its deadline: it must not run any more (the client was told it didn't). + pub fn expired(&self) -> bool { + Instant::now() >= self.deadline + } + /// Runs it on `host` and sends the answer; an expired request is refused instead. + pub fn run(self, host: &mut H) { + let result = if self.expired() { Err(BUSY.to_string()) } else { mcp::call_tool(host, &self.name, &self.arguments) }; + let _ = self.reply.send(result); + } + /// Answers without running (the app is closing). + pub fn refuse(self, why: &str) { + let _ = self.reply.send(Err(why.to_string())); + } +} + +/// Wakes the app's frame loop (`egui::Context::request_repaint`), from any thread. +pub type Wake = Arc; + +/// An open control port. +pub struct Server { + pub port: u16, + rx: Receiver, +} + +impl Server { + /// The next waiting tool call, if any. + pub fn try_recv(&self) -> Option { + self.rx.try_recv().ok() + } +} + +/// Opens the control port on `127.0.0.1:port`. Tool calls arrive through [`Server::try_recv`]; +/// `wake` is called whenever one is waiting. +pub fn listen(port: u16, token: String, wake: Wake) -> std::io::Result { + let listener = TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))?; + let port = listener.local_addr()?.port(); + let (tx, rx) = channel(); + let token: Arc = token.into(); + std::thread::Builder::new().name("anicraft-control".into()).spawn(move || accept_loop(&listener, &token, &tx, &wake))?; + Ok(Server { port, rx }) +} + +fn accept_loop(listener: &TcpListener, token: &Arc, tx: &Sender, wake: &Wake) { + let active = Arc::new(AtomicUsize::new(0)); + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let _ = stream.set_write_timeout(Some(Duration::from_secs(10))); + if active.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS { + active.fetch_sub(1, Ordering::SeqCst); + let _ = writeln!(stream, "{}", fail(&Value::Null, format!("too many connections (at most {MAX_CONNECTIONS})"))); + continue; + } + let (token, tx, wake, active2) = (token.clone(), tx.clone(), wake.clone(), active.clone()); + let spawned = std::thread::Builder::new().name("anicraft-control-conn".into()).spawn(move || { + serve_connection(stream, &token, &tx, &wake); + active2.fetch_sub(1, Ordering::SeqCst); + }); + if spawned.is_err() { + active.fetch_sub(1, Ordering::SeqCst); + } + } +} + +/// One connection: requests in order, until the client leaves or sends something it shouldn't. +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, wake: &Wake) { + let Ok(read_half) = stream.try_clone() else { return }; + let mut reader = BufReader::new(read_half); + let mut out = stream; + loop { + let line = match read_line(&mut reader, MAX_LINE) { + Ok(Some(l)) => l, + Ok(None) | Err(LineError::Io(_)) => return, + Err(LineError::TooLong) => { + let _ = writeln!(out, "{}", fail(&Value::Null, format!("request longer than {} MiB", MAX_LINE / (1024 * 1024)))); + return; + } + Err(LineError::NotText) => { + let _ = writeln!(out, "{}", fail(&Value::Null, "the request is not UTF-8 text")); + return; + } + }; + if line.trim().is_empty() { + continue; + } + let (reply, keep_open) = answer(&line, token, tx, wake); + if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() || !keep_open { + return; + } + } +} + +/// The reply to one request line, and whether the connection stays open. +fn answer(line: &str, token: &str, tx: &Sender, wake: &Wake) -> (Value, bool) { + let req = match parse_request(line) { + Ok(r) => r, + Err(e) => return (fail(&Value::Null, e), false), + }; + if !token_matches(req.token.as_deref(), token) { + let why = if req.token.is_none() { "missing token" } else { "wrong token" }; + return (fail(&req.id, format!("{why}: send the \"token\" from {CONTROL_FILE} in AniCraft's settings folder (or {TOKEN_ENV})")), false); + } + let id = &req.id; + match req.method.as_str() { + "hello" => (ok(id, json!({"app": "AniCraft", "version": env!("CARGO_PKG_VERSION"), "protocol": PROTOCOL})), true), + "tools.list" => (ok(id, mcp::tools()), true), + "tools.call" => { + let Some(name) = req.params.get("name").and_then(Value::as_str) else { return (fail(id, "tools.call needs a tool \"name\" in params"), true) }; + let arguments = req.params.get("arguments").cloned().unwrap_or_else(|| json!({})); + let (reply, rx) = channel(); + let request = Request { name: name.to_string(), arguments, deadline: Instant::now() + REQUEST_TIMEOUT, reply }; + if tx.send(request).is_err() { + return (fail(id, "AniCraft is closing"), false); + } + wake(); + match rx.recv_timeout(REQUEST_TIMEOUT + GRACE) { + Ok(Ok(result)) => (ok(id, result), true), + Ok(Err(e)) => (fail(id, e), true), + Err(RecvTimeoutError::Timeout) => (fail(id, "AniCraft didn't answer in time; the call may still have run. Check with anicraft_document before trying again."), true), + Err(RecvTimeoutError::Disconnected) => (fail(id, "AniCraft closed before answering"), false), + } + } + other => (fail(id, format!("unknown method '{other}' (hello, tools.list, tools.call)")), true), + } +} + +// ----- the client: `anicraft-cli mcp --bridge` ------------------------------------------------- + +/// Reads `--bridge`'s value: a port, or `127.0.0.1:port` / `localhost:port`. Other hosts are +/// refused: the control port is for this computer only. +pub fn parse_bridge_target(s: &str) -> Result { + let s = s.trim(); + let (host, port) = match s.rsplit_once(':') { + Some((h, p)) => (h, p), + None => ("127.0.0.1", s), + }; + if !matches!(host, "127.0.0.1" | "localhost") { + return Err(format!("--bridge connects to this computer only: give a port, or 127.0.0.1: (not {host})")); + } + Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, parse_port(port)?))) +} + +/// The token to send: `ANICRAFT_CONTROL_TOKEN` when set, else the one in `control.json`. +pub fn find_token(env: Option, file: Option<&Path>) -> Result { + if let Some(t) = env { + return Ok(t); + } + let Some(file) = file else { return Err(not_running(None)) }; + match std::fs::read_to_string(file) { + Ok(text) => ControlFile::parse(&text).map(|c| c.token), + Err(_) => Err(not_running(None)), + } +} + +/// What to tell the person when the app isn't there. +fn not_running(port: Option) -> String { + let port = port.unwrap_or(DEFAULT_PORT); + format!( + "AniCraft isn't open with remote control on. Start it with `anicraft --control {port}` (the \"AniCraft (Claude)\" shortcut), then try again; there is no need to restart the assistant." + ) +} + +/// Why a bridged call failed. +#[derive(Debug, PartialEq)] +pub enum BridgeError { + /// Couldn't reach the app (not running, no token): nothing ran. + NotRunning(String), + /// The connection broke after the request went out: it may have run. + Lost(String), + /// The app refused the call (the headless server's protocol error). + Refused(String), +} + +struct Conn { + reader: BufReader, + writer: TcpStream, +} + +impl Conn { + /// Whether the app is still at the other end (an app that quit leaves the socket closed). + fn alive(&self) -> bool { + if self.writer.set_nonblocking(true).is_err() { + return false; + } + let r = self.writer.peek(&mut [0u8; 1]); + let back = self.writer.set_nonblocking(false).is_ok(); + back && matches!(r, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock) + } +} + +/// The bridge's link to the app: connected on the first call, again after a break. +pub struct Bridge { + addr: SocketAddr, + conn: Option, + next_id: u64, + /// Where the token comes from (tests point it elsewhere). + token_file: Option, +} + +impl Bridge { + /// Doesn't connect: the assistant starts its servers when it starts, often before AniCraft. + pub fn new(addr: SocketAddr) -> Bridge { + Bridge { addr, conn: None, next_id: 1, token_file: control_file() } + } + + pub fn with_token_file(addr: SocketAddr, file: Option) -> Bridge { + Bridge { addr, conn: None, next_id: 1, token_file: file } + } + + fn connect(&mut self) -> Result { + let token = find_token(token_from_env(), self.token_file.as_deref()).map_err(BridgeError::NotRunning)?; + if self.conn.as_ref().is_some_and(Conn::alive) { + return Ok(token); + } + self.conn = None; + let stream = TcpStream::connect_timeout(&self.addr, Duration::from_secs(3)).map_err(|_| BridgeError::NotRunning(not_running(Some(self.addr.port()))))?; + let _ = stream.set_nodelay(true); + let _ = stream.set_read_timeout(Some(REQUEST_TIMEOUT + GRACE + Duration::from_secs(5))); + let reader = BufReader::new(stream.try_clone().map_err(|e| BridgeError::NotRunning(e.to_string()))?); + self.conn = Some(Conn { reader, writer: stream }); + Ok(token) + } + + /// One round trip; any transport failure drops the connection. + fn round_trip(&mut self, token: &str, method: &str, params: Value) -> Result { + let id = self.next_id; + self.next_id += 1; + let line = json!({"id": id, "token": token, "method": method, "params": params}).to_string(); + let Some(conn) = self.conn.as_mut() else { return Err(BridgeError::NotRunning(not_running(Some(self.addr.port())))) }; + let sent = writeln!(conn.writer, "{line}").and_then(|()| conn.writer.flush()); + let reply = sent.map_err(|e| e.to_string()).and_then(|()| match read_line(&mut conn.reader, MAX_LINE) { + Ok(Some(l)) => Ok(l), + Ok(None) => Err("AniCraft closed the connection".to_string()), + Err(LineError::Io(e)) => Err(e.to_string()), + Err(_) => Err("unreadable reply".to_string()), + }); + let reply = match reply { + Ok(l) => l, + Err(e) => { + self.conn = None; + return Err(BridgeError::Lost(e)); + } + }; + let v: Value = serde_json::from_str(&reply).map_err(|e| { + self.conn = None; + BridgeError::Lost(format!("unreadable reply: {e}")) + })?; + if v.get("ok").and_then(Value::as_bool) == Some(true) { + return Ok(v.get("result").cloned().unwrap_or(Value::Null)); + } + let error = v.get("error").and_then(Value::as_str).unwrap_or("AniCraft refused the request").to_string(); + if v.get("id").is_some_and(Value::is_null) || error.starts_with("missing token") || error.starts_with("wrong token") { + // The app closes the connection after these (an old token: AniCraft was restarted + // and control.json has the new one by the next call). + self.conn = None; + } + Err(BridgeError::Refused(error)) + } + + /// Runs a tool in the app. An edit whose answer was lost is never sent again (the app may + /// have made it); a call that only reads is tried once more on a new connection. + pub fn call_tool(&mut self, name: &str, args: &Value) -> Result { + let retries = if mcp::tool_changes_document(name) { 0 } else { 1 }; + let mut attempt = 0; + loop { + let token = self.connect()?; + match self.round_trip(&token, "tools.call", json!({"name": name, "arguments": args})) { + Err(BridgeError::Lost(_)) if attempt < retries => attempt += 1, + Err(BridgeError::Refused(e)) if e.starts_with("wrong token") && attempt < 1 => attempt += 1, + other => return other, + } + } + } +} + +/// The bridge's instructions: the same tools, acting on the person's open window. +pub const BRIDGE_INSTRUCTIONS: &str = "AniCraft is a 2D animation studio, and these tools act on the AniCraft window the person \ +has open: every edit appears there immediately and can be undone with Ctrl+Z (or edit.undo). Every edit is a command: call \ +anicraft_commands to find one (filter by words such as 'tween' or 'export'), then anicraft_run with its id and params, or \ +anicraft_run_script for several in order. Frames in params are 0-based. Commands act on the current scene, layer, frame and \ +selection, which anicraft_document reports (the person may change them between your calls). Use anicraft_render to see a \ +frame. Commands that would lose work or replace a file refuse until params include \"confirm\": true; ask the person before \ +confirming. If AniCraft isn't open with remote control on, the tools say how to start it."; + +impl mcp::Backend for Bridge { + fn instructions(&self) -> &'static str { + BRIDGE_INSTRUCTIONS + } + fn call(&mut self, name: &str, args: &Value) -> Result { + match self.call_tool(name, args) { + Ok(v) => Ok(v), + Err(BridgeError::Refused(e)) => Err(e), + Err(BridgeError::NotRunning(e)) => Ok(mcp::text_result(&Value::String(e), true)), + Err(BridgeError::Lost(e)) => { + let what = if mcp::tool_changes_document(name) { " It may have been made: check with anicraft_document before trying again." } else { "" }; + Ok(mcp::text_result(&Value::String(format!("The connection to AniCraft broke ({e}).{what}")), true)) + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/cli/src/control/tests.rs b/crates/cli/src/control/tests.rs new file mode 100644 index 00000000..1c136fc6 --- /dev/null +++ b/crates/cli/src/control/tests.rs @@ -0,0 +1,253 @@ +use super::*; +use crate::mcp::Backend; +use anicraft_engine::Session; +use std::sync::atomic::AtomicBool; + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +/// A control port on a free port, with a stand-in for the app's frame loop running each call on +/// its own session (as `App::poll_remote` does). Stops when dropped. +struct App { + port: u16, + stop: Arc, + loop_thread: Option>, +} + +impl App { + fn start(session: Session) -> App { + let server = listen(0, TOKEN.into(), Arc::new(|| {})).unwrap(); + let port = server.port; + let stop = Arc::new(AtomicBool::new(false)); + let stop2 = stop.clone(); + let loop_thread = std::thread::spawn(move || { + let mut s = session; + while !stop2.load(Ordering::SeqCst) { + while let Some(r) = server.try_recv() { + r.run(&mut s); + } + std::thread::sleep(Duration::from_millis(2)); + } + s + }); + App { port, stop, loop_thread: Some(loop_thread) } + } + + fn session(mut self) -> Session { + self.stop.store(true, Ordering::SeqCst); + self.loop_thread.take().unwrap().join().unwrap() + } + + fn connect(&self) -> (BufReader, TcpStream) { + let s = TcpStream::connect(("127.0.0.1", self.port)).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + (BufReader::new(s.try_clone().unwrap()), s) + } +} + +impl Drop for App { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + } +} + +fn send(conn: &mut (BufReader, TcpStream), line: &str) -> Value { + writeln!(conn.1, "{line}").unwrap(); + serde_json::from_str(&read_line(&mut conn.0, MAX_LINE).unwrap().unwrap()).unwrap() +} + +/// The app closed the connection: nothing more to read. +fn closed(conn: &mut (BufReader, TcpStream)) -> bool { + matches!(read_line(&mut conn.0, MAX_LINE), Ok(None) | Err(LineError::Io(_))) +} + +#[test] +fn requests_are_json_objects_with_a_string_method() { + let r = parse_request(r#"{"id":3,"token":"t","method":"hello"}"#).unwrap(); + assert_eq!((r.id, r.token.as_deref(), r.method.as_str(), r.params), (json!(3), Some("t"), "hello", json!({}))); + // A web page's fetch to localhost starts with an HTTP request line: refused. + assert!(parse_request("GET / HTTP/1.1").is_err()); + assert!(parse_request("POST /tools HTTP/1.1").is_err()); + assert!(parse_request("[1,2]").is_err()); + assert!(parse_request(r#"{"id":1}"#).is_err(), "no method"); + assert!(parse_request(r#"{"id":1,"method":7}"#).is_err(), "method must be a string"); +} + +#[test] +fn tokens_must_match_exactly() { + assert!(token_matches(Some(TOKEN), TOKEN)); + assert!(!token_matches(None, TOKEN)); + assert!(!token_matches(Some(""), ""), "an empty token never opens the port"); + assert!(!token_matches(Some(&TOKEN[..63]), TOKEN)); + assert!(!token_matches(Some(&TOKEN.replace('f', "e")), TOKEN)); + let t = new_token().unwrap(); + assert_eq!(t.len(), 64); + assert!(t.bytes().all(|b| b.is_ascii_hexdigit())); + assert_ne!(t, new_token().unwrap(), "fresh each time"); +} + +#[test] +fn lines_are_capped() { + let mut r = &b"one\r\ntwo\nthree"[..]; + assert_eq!(read_line(&mut r, 10).unwrap().as_deref(), Some("one")); + assert_eq!(read_line(&mut r, 10).unwrap().as_deref(), Some("two")); + assert_eq!(read_line(&mut r, 10).unwrap().as_deref(), Some("three")); + assert!(read_line(&mut r, 10).unwrap().is_none()); + let mut exact = &b"0123456789\n"[..]; + assert_eq!(read_line(&mut exact, 10).unwrap().as_deref(), Some("0123456789")); + let mut long = &b"0123456789A\n"[..]; + assert!(matches!(read_line(&mut long, 10), Err(LineError::TooLong))); +} + +#[test] +fn ports_and_bridge_targets() { + assert_eq!(parse_port("9878"), Ok(9878)); + assert!(parse_port("0").is_err()); + assert!(parse_port("70000").is_err()); + assert!(parse_port("port").is_err()); + let local = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9878)); + assert_eq!(parse_bridge_target("9878"), Ok(local)); + assert_eq!(parse_bridge_target("127.0.0.1:9878"), Ok(local)); + assert_eq!(parse_bridge_target("localhost:9878"), Ok(local)); + assert!(parse_bridge_target("192.168.1.5:9878").is_err(), "this computer only"); + assert!(parse_bridge_target("example.com:9878").is_err()); +} + +#[test] +fn the_control_file_round_trips() { + let c = ControlFile { port: 9878, token: TOKEN.into(), pid: 42, version: "0.2.1".into() }; + assert_eq!(ControlFile::parse(&c.to_json().to_string()), Ok(c)); + assert!(ControlFile::parse("{}").is_err()); + assert!(ControlFile::parse("nonsense").is_err()); +} + +#[test] +fn the_token_comes_from_the_environment_then_the_control_file() { + let dir = std::env::temp_dir().join(format!("anicraft-control-token-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join(CONTROL_FILE); + std::fs::write(&file, ControlFile { port: 9878, token: "from-file".into(), pid: 1, version: String::new() }.to_json().to_string()).unwrap(); + assert_eq!(find_token(Some("from-env".into()), Some(&file)), Ok("from-env".into()), "the environment wins"); + assert_eq!(find_token(None, Some(&file)), Ok("from-file".into())); + let missing = find_token(None, Some(&dir.join("gone.json"))).unwrap_err(); + assert!(missing.contains("anicraft --control"), "{missing}"); + assert!(find_token(None, None).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_missing_or_wrong_token_is_refused_and_the_connection_closed() { + let app = App::start(Session::default()); + let mut c = app.connect(); + let r = send(&mut c, r#"{"id":1,"method":"tools.call","params":{"name":"anicraft_run","arguments":{"command":"draw.rect","params":{"x":0,"y":0,"w":5,"h":5}}}}"#); + assert_eq!(r["ok"], false); + assert!(r["error"].as_str().unwrap().starts_with("missing token"), "{r}"); + assert!(closed(&mut c)); + let mut c = app.connect(); + let r = send(&mut c, &json!({"id": 2, "token": "nope", "method": "tools.call", "params": {"name": "anicraft_run", "arguments": {"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 5, "h": 5}}}}).to_string()); + assert!(r["error"].as_str().unwrap().starts_with("wrong token"), "{r}"); + assert!(closed(&mut c)); + assert!(app.session().visible_elements().is_empty(), "nothing ran"); +} + +#[test] +fn http_and_oversized_lines_are_refused_and_the_connection_closed() { + let app = App::start(Session::default()); + let mut c = app.connect(); + let r = send(&mut c, "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n"); + assert_eq!((r["ok"].clone(), r["id"].clone()), (json!(false), Value::Null)); + assert!(closed(&mut c)); + let mut c = app.connect(); + let big = format!(r#"{{"id":1,"token":"{TOKEN}","method":"hello","pad":"{}"}}"#, "x".repeat(MAX_LINE)); + // The app stops reading at the limit and answers; the rest of the write may fail. + let _ = c.1.write_all(big.as_bytes()); + let _ = c.1.write_all(b"\n"); + let reply: Value = serde_json::from_str(&read_line(&mut c.0, MAX_LINE).unwrap().unwrap()).unwrap(); + assert!(reply["error"].as_str().unwrap().contains("longer than 4 MiB"), "{reply}"); + assert!(closed(&mut c)); +} + +#[test] +fn a_call_through_the_port_matches_the_headless_server() { + let app = App::start(Session::default()); + let mut c = app.connect(); + let hello = send(&mut c, &json!({"id": 1, "token": TOKEN, "method": "hello"}).to_string()); + assert_eq!(hello, json!({"id": 1, "ok": true, "result": {"app": "AniCraft", "version": env!("CARGO_PKG_VERSION"), "protocol": PROTOCOL}})); + let list = send(&mut c, &json!({"id": 2, "token": TOKEN, "method": "tools.list"}).to_string()); + assert_eq!(list["result"], mcp::tools()); + let args = json!({"command": "draw.rect", "params": {"x": 10, "y": 10, "w": 50, "h": 40, "fill": "#ff0000"}}); + let live = send(&mut c, &json!({"id": 3, "token": TOKEN, "method": "tools.call", "params": {"name": "anicraft_run", "arguments": args}}).to_string()); + assert_eq!(live["ok"], true, "{live}"); + let mut headless = Session::default(); + assert_eq!(live["result"], mcp::call_tool(&mut headless, "anicraft_run", &args).unwrap(), "the same dispatcher, the same answer"); + // A protocol error in headless mode is an error reply here; the connection stays usable. + let bad = send(&mut c, &json!({"id": 4, "token": TOKEN, "method": "tools.call", "params": {"name": "nope"}}).to_string()); + assert_eq!((bad["ok"].clone(), bad["error"].clone()), (json!(false), json!("unknown tool 'nope'"))); + let unknown = send(&mut c, &json!({"id": 5, "token": TOKEN, "method": "frobnicate"}).to_string()); + assert_eq!(unknown["ok"], false); + let doc = send(&mut c, &json!({"id": 6, "token": TOKEN, "method": "tools.call", "params": {"name": "anicraft_document"}}).to_string()); + // `state` numbers saved states across every session in the process, so it differs. + let described = |r: &Value| { + let mut v: Value = serde_json::from_str(r["content"][0]["text"].as_str().unwrap()).unwrap(); + v.as_object_mut().unwrap().remove("state"); + v + }; + assert_eq!(described(&doc["result"]), described(&mcp::call_tool(&mut headless, "anicraft_document", &json!({})).unwrap())); + let s = app.session(); + assert_eq!(s.visible_elements().len(), 1); + assert!(s.doc == headless.doc); +} + +#[test] +fn a_call_that_waited_past_its_deadline_does_not_run() { + let (reply, answer) = channel(); + let r = Request { name: "anicraft_run".into(), arguments: json!({"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 5, "h": 5}}), deadline: Instant::now(), reply }; + assert!(r.expired() && r.changes_document()); + let mut s = Session::default(); + r.run(&mut s); + assert_eq!(answer.recv().unwrap(), Err(BUSY.to_string())); + assert!(s.visible_elements().is_empty()); +} + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +#[test] +fn the_bridge_starts_without_the_app_and_says_how_to_start_it() { + let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, free_port())); + let dir = std::env::temp_dir().join(format!("anicraft-bridge-none-{}", std::process::id())); + let mut b = Bridge::with_token_file(addr, Some(dir.join(CONTROL_FILE))); + // The handshake and the tool list need no app. + let init = mcp::handle(&mut b, r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#).unwrap(); + assert!(init["result"]["instructions"].as_str().unwrap().contains("open")); + let list = mcp::handle(&mut b, r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#).unwrap(); + assert_eq!(list["result"]["tools"], mcp::tools()); + let r = mcp::handle(&mut b, r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"anicraft_document"}}"#).unwrap(); + assert_eq!(r["result"]["isError"], true); + assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("anicraft --control"), "{r}"); + // A token file but no app listening: the same advice. + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(CONTROL_FILE), ControlFile { port: addr.port(), token: TOKEN.into(), pid: 1, version: String::new() }.to_json().to_string()).unwrap(); + assert!(matches!(b.call_tool("anicraft_document", &json!({})), Err(BridgeError::NotRunning(_)))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_bridge_drives_the_app_and_says_when_it_has_gone() { + let dir = std::env::temp_dir().join(format!("anicraft-bridge-live-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join(CONTROL_FILE); + let app = App::start(Session::default()); + std::fs::write(&file, ControlFile { port: app.port, token: TOKEN.into(), pid: 1, version: String::new() }.to_json().to_string()).unwrap(); + let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, app.port)); + let mut b = Bridge::with_token_file(addr, Some(file.clone())); + let r = b.call("anicraft_run", &json!({"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 9, "h": 9}})).unwrap(); + assert_eq!(r["isError"], false, "{r}"); + assert_eq!(b.call("anicraft_document", &json!({})).unwrap()["isError"], false); + assert_eq!(app.session().visible_elements().len(), 1, "the edit landed in the app's session"); + // The app's frame loop is gone: the call fails (as an error the assistant reads), never + // silently. + let r = b.call("anicraft_run", &json!({"command": "draw.rect", "params": {"x": 0, "y": 0, "w": 9, "h": 9}})); + assert!(r.as_ref().map_or(true, |v| v["isError"] == true), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index cb9ef155..7f8c6706 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -2,6 +2,7 @@ //! server (`mcp`). Every operation goes through the engine's command registry. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod control; pub mod mcp; use anicraft_engine::{Session, commands, format}; @@ -33,6 +34,9 @@ USAGE: {\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}} anicraft-cli mcp [file|--sample] Model Context Protocol server on stdin/stdout, for AI assistants (see docs/mcp.md) + anicraft-cli mcp --bridge the same tools, acting live on the AniCraft window + started with `anicraft --control ` + (docs/control-protocol.md) anicraft-cli --version --plugins loads the WebAssembly plug-ins in a folder first (also the @@ -241,6 +245,16 @@ pub fn run(argv: &[String]) -> Result { Ok(String::new()) } "mcp" => { + if let Some(target) = a.flag("bridge") { + if src.is_some() || a.flag("plugins").is_some() { + return Err("mcp --bridge acts on the open AniCraft window: it takes no file or --plugins".into()); + } + let mut b = control::Bridge::new(control::parse_bridge_target(target)?); + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + mcp::serve(&mut b, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?; + return Ok(String::new()); + } let mut s = session(&a, src)?; let stdin = std::io::stdin(); let mut stdout = std::io::stdout(); diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 44e3543e..809922e0 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -6,6 +6,10 @@ //! frame as a picture. Everything still goes through `Session::execute`, so undo, validation //! and the confirmation tiers (ADR 0004: `"confirm": true` before irreversible loss) apply to //! an assistant exactly as to the app. +//! +//! The same tools drive the desktop app live (ADR 0070): the app runs [`call_tool`] on its own +//! session for requests from its control port, and `anicraft-cli mcp --bridge ` is this +//! server with a [`Backend`] that forwards each tool call there (`crate::control`). use anicraft_engine::{Session, commands}; use serde_json::{Value, json}; @@ -20,7 +24,8 @@ const MAX_PICTURE_EDGE: f32 = 2048.0; /// Most steps in one `anicraft_run_script` call. const MAX_STEPS: usize = 10_000; -const INSTRUCTIONS: &str = "AniCraft is a 2D animation studio. Every edit is a command: call \ +/// The headless server's instructions (an in-process document no one sees). +pub const INSTRUCTIONS: &str = "AniCraft is a 2D animation studio. Every edit is a command: call \ anicraft_commands to find one (filter by words such as 'tween' or 'export'), then anicraft_run \ with its id and params, or anicraft_run_script for several in order. Frames in params are \ 0-based. Commands act on the current scene, layer, frame and selection, which anicraft_document \ @@ -28,7 +33,8 @@ reports. Use anicraft_render to see a frame. Edits can be undone with edit.undo. would lose work or replace a file refuse until params include \"confirm\": true; ask the person \ before confirming."; -fn tools() -> Value { +/// The tools, as `tools/list` returns them. The desktop app's control port lists the same. +pub fn tools() -> Value { json!([ { "name": "anicraft_commands", @@ -95,21 +101,46 @@ fn error(id: Value, code: i64, message: impl Into) -> Value { json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) } -fn text_result(v: &Value, is_error: bool) -> Value { +/// A tool result holding `v` as text (pretty JSON unless it is a string). +pub fn text_result(v: &Value, is_error: bool) -> Value { let text = if let Value::String(s) = v { s.clone() } else { serde_json::to_string_pretty(v).unwrap_or_default() }; json!({"content": [{"type": "text", "text": text}], "isError": is_error}) } +/// Where tools run: a session, and how a command runs on it. The headless server uses the +/// [`Session`] itself; the desktop app runs commands through its own follow-up (the status +/// line, the view a new document resets), as for the person's own edits. +pub trait Host { + fn session(&self) -> &Session; + /// Runs one command; the error is the engine's message. + fn execute(&mut self, id: &str, params: &Value) -> Result; +} + +impl Host for Session { + fn session(&self) -> &Session { + self + } + fn execute(&mut self, id: &str, params: &Value) -> Result { + Session::execute(self, id, params).map_err(|e| e.to_string()) + } +} + +/// Whether a tool can change the document (the app holds these back while the person is in +/// the middle of a drag or typing, so the two edits never share an undo step). +pub fn tool_changes_document(name: &str) -> bool { + !matches!(name, "anicraft_commands" | "anicraft_document" | "anicraft_render") +} + /// Runs one tool. Tool failures are results with `isError` (so the assistant can read and /// correct them); only malformed calls are protocol errors. -fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result { - let run = |s: &mut Session, step: &Value| -> Result { +pub fn call_tool(h: &mut H, name: &str, args: &Value) -> Result { + let run = |h: &mut H, step: &Value| -> Result { let id = step.get("command").and_then(Value::as_str).ok_or("missing \"command\"")?; let params = step.get("params").cloned().unwrap_or_else(|| json!({})); if !params.is_object() { return Err(format!("{id}: \"params\" must be an object")); } - s.execute(id, ¶ms).map_err(|e| format!("{id}: {e}")) + h.execute(id, ¶ms).map_err(|e| format!("{id}: {e}")) }; Ok(match name { "anicraft_commands" => { @@ -125,8 +156,11 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result .collect(); text_result(&Value::Array(list), false) } - "anicraft_run" => match run(s, args) { - Ok(v) => text_result(&json!({"result": v, "revision": s.revision, "frame": s.frame, "scene": s.scene}), false), + "anicraft_run" => match run(h, args) { + Ok(v) => { + let s = h.session(); + text_result(&json!({"result": v, "revision": s.revision, "frame": s.frame, "scene": s.scene}), false) + } Err(e) => text_result(&Value::String(e), true), }, "anicraft_run_script" => { @@ -136,15 +170,17 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result } let mut results = Vec::with_capacity(steps.len()); for (i, step) in steps.iter().enumerate() { - match run(s, step) { + match run(h, step) { Ok(v) => results.push(v), Err(e) => return Ok(text_result(&json!({"failed_step": i + 1, "error": e, "done": results}), true)), } } + let s = h.session(); text_result(&json!({"results": results, "revision": s.revision, "frame": s.frame}), false) } - "anicraft_document" => text_result(&s.info(), false), + "anicraft_document" => text_result(&h.session().info(), false), "anicraft_render" => { + let s = h.session(); let frame = match args.get("frame") { None | Some(Value::Null) => s.frame, Some(v) => v.as_u64().and_then(|f| u32::try_from(f).ok()).ok_or("\"frame\" must be a whole number from 0")?, @@ -173,8 +209,26 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result }) } +/// What answers `tools/call`: the in-process session (headless), or the desktop app through +/// its control port (`--bridge`, `crate::control::Bridge`). +pub trait Backend { + /// The `instructions` the server gives the assistant at `initialize`. + fn instructions(&self) -> &'static str; + /// A `tools/call` result, or the message of a protocol error (a malformed call). + fn call(&mut self, name: &str, args: &Value) -> Result; +} + +impl Backend for Session { + fn instructions(&self) -> &'static str { + INSTRUCTIONS + } + fn call(&mut self, name: &str, args: &Value) -> Result { + call_tool(self, name, args) + } +} + /// Answers one JSON-RPC message; `None` for notifications (and responses), which get no reply. -pub fn handle(s: &mut Session, line: &str) -> Option { +pub fn handle(s: &mut B, line: &str) -> Option { let msg: Value = match serde_json::from_str(line.trim_start_matches('\u{feff}')) { Ok(v) => v, Err(e) => return Some(error(Value::Null, -32700, format!("parse error: {e}"))), @@ -198,7 +252,7 @@ pub fn handle(s: &mut Session, line: &str) -> Option { "protocolVersion": version, "capabilities": {"tools": {"listChanged": false}}, "serverInfo": {"name": "anicraft", "title": "AniCraft", "version": env!("CARGO_PKG_VERSION")}, - "instructions": INSTRUCTIONS + "instructions": s.instructions() }) } "ping" => json!({}), @@ -206,7 +260,7 @@ pub fn handle(s: &mut Session, line: &str) -> Option { "tools/call" => { let Some(name) = params.get("name").and_then(Value::as_str) else { return Some(error(id, -32602, "tools/call needs a tool \"name\"")) }; let args = params.get("arguments").cloned().unwrap_or_else(|| json!({})); - match call_tool(s, name, &args) { + match s.call(name, &args) { Ok(v) => v, Err(e) => return Some(error(id, -32602, e)), } @@ -218,7 +272,7 @@ pub fn handle(s: &mut Session, 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 Session, input: R, out: &mut W) -> std::io::Result<()> { +pub fn serve(s: &mut B, input: R, out: &mut W) -> std::io::Result<()> { for line in input.lines() { let line = line?; if line.trim().is_empty() { diff --git a/docs/adr/0070-live-control-port.md b/docs/adr/0070-live-control-port.md new file mode 100644 index 00000000..44637065 --- /dev/null +++ b/docs/adr/0070-live-control-port.md @@ -0,0 +1,99 @@ +# ADR 0070: A live control port, so assistants edit the open window + +* Status: accepted (2026-11-12) +* Relates to: ADR 0004 (destructive actions), ADR 0005 (typography), ADR 0006 (platforms), + ADR 0040 (interface languages), `docs/mcp.md`, `docs/control-protocol.md` + +## Context + +`anicraft-cli mcp` gives AI assistants the engine's commands as five MCP tools, but it edits a +document inside its own process, with no window. To see the result the person saves, then opens +the file in the app. Every edit is invisible until then, and the assistant and the person can +never work on the same document at once. + +The sister apps (VectorCraft, CadCraft, FilmCraft, EffectCraft) already let an assistant drive the +open window through a TCP port on `127.0.0.1`, with a line-per-message JSON protocol and an MCP +"bridge" that forwards to it. AniCraft should behave the same way. + +One lesson from FilmCraft: its token was an environment variable, which a desktop shortcut's +process received and an MCP server started by the assistant's desktop app did not. Authentication +must not depend on an environment variable reaching two unrelated processes. + +## Decision + +1. **`anicraft --control `** (also `ANICRAFT_CONTROL_PORT`; the flag wins) opens a control + port on `127.0.0.1` only. 9878 is the convention (after EffectCraft's 9877). A bad port is an + error before any window opens. If the port can't be opened (in use), the window opens anyway + and the status bar says why. +2. **The protocol is small** (`docs/control-protocol.md`): one JSON object per line each way, + persistent connections, answered in order. Methods: `hello`, `tools.list`, `tools.call`. + Replies are `{"id", "ok": true, "result"}` or `{"id", "ok": false, "error"}`. +3. **One dispatcher for live and headless.** The app depends on the `anicraft-cli` library and + runs its `mcp::call_tool` and `mcp::tools` on the window's session. `call_tool` is generic over + a small `Host` trait (the session, and how a command runs), so the app runs commands through + its own follow-up (`App::announce`: the status line, the view a new document resets, Open + Recent), as for the person's own edits. + + *Considered:* a new crate for the dispatcher, used by both. It would have to be L4 (it needs + the engine and the renderer), and the CLI (L4) may not depend on a crate in its own layer, so + the CLI would have to move up beside the shell. The shell (L5) depending on the CLI library + (L4) fits the layering as it is, adds no crate, and the CLI library has no dependency the shell + doesn't already have (except `getrandom`, below). The CLI's library already was the MCP server; + it now also holds the control port's protocol, its listener threads and the bridge client + (`crates/cli/src/control.rs`), none of which touches the UI toolkit, so they are tested there. +4. **Threads, and the frame.** One listener thread and one thread per connection (at most 16). A + tool call goes to the UI thread through a channel with a reply sender; the connection thread + wakes the window (`request_repaint`). The frame loop runs waiting calls at the start of the + frame, before anything draws, so their edits show in the same frame (AGENTS.md "edits are + live"). The window never takes focus. An edit made behind the start screen (ADR 0059) + closes it, so the person sees the document change. +5. **The person's own gestures.** An edit from a tool must not join the person's undo step. While + the person is dragging (pointer held, a stage drag, or a plug-in dialog previewing), calls that + can change the document wait (calls that only read don't). A call that waited 60 s is refused + without running, and the client is told so. An open gesture that is only typing (a property + field still focused) is committed first, as its own undo step, as clicking elsewhere would do; + waiting for that could block an assistant indefinitely. + + *Considered:* committing the gesture mid-drag. The rest of the drag would then record one undo + step per frame, so we wait instead. +6. **Authentication: a token file, no setup.** Each run with `--control` makes a fresh 32-byte + token from the operating system's random numbers (`getrandom`, MIT OR Apache-2.0, already in + the tree) and writes `control.json` (`port`, `token`, `pid`, `version`) to the AniCraft settings + folder, owner-only on macOS and Linux (`%APPDATA%` is already private on Windows). It is + replaced at start and removed on exit if it still holds this run's token. Every request carries + the token; a missing or wrong token is refused and the connection closed before anything runs. + `ANICRAFT_CONTROL_TOKEN`, when set, is the token on both sides (CI, power users). + + The CLI can't use the shell's `platform::config_dir`, so it has its own copy of the folder rule + (`control::settings_dir`) and a shell test keeps the two equal. + + *Considered:* no authentication (VectorCraft, CadCraft, EffectCraft). Any local process, and a + web page able to reach localhost, could then edit and save files as the person. *Considered:* + an environment-variable token only (FilmCraft): see Context. +7. **Hardening, as in the sister apps.** Every line must be a JSON object with a string `method`; + anything else gets one error line and the connection closes. That also refuses a web page's + `fetch` to localhost, which starts with an HTTP request line. Lines are capped at 4 MiB. Writes + time out after 10 s so a client that stops reading can't hold a thread. +8. **Safety rules unchanged.** Calls run through `Session::execute`, so `"confirm": true` (ADR 0004) + is needed exactly as headless, unsaved-work guards and crash recovery see the edits as the + person's, and every edit undoes with Ctrl+Z. +9. **`anicraft-cli mcp --bridge `** is the MCP server with a backend that + forwards `tools/call` to the app; `initialize` and `tools/list` are answered locally (the same + tool list), so the server starts and lists its tools before AniCraft is open. It connects on + the first call and returns an error that says how to start the app when it can't. It reconnects + after a break (an app that quit is noticed before the next request is sent). An edit whose reply + was lost is never sent again (the app may have made it); a call that only reads is tried once + more. Hosts other than this computer are refused. +10. **Visible.** While the port is open the status bar says "Remote control on (port N)" (through + `tr!` and `theme::Type`), with a tooltip saying what that means. + +## Consequences + +* The shell now builds the CLI library (small; nothing new for the web build, which leaves the + control port out). +* The tool behaviour can't drift between live and headless: one function serves both, and a test + checks that a call through the port answers as `call_tool` does. +* Remote edits arrive at most once per frame batch; a long `anicraft_run_script` blocks the window + while it runs, as a long menu command would. +* Not yet: a screenshot tool that returns the window itself (the app already captures itself for + `--screenshot`). diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..65918325 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0070 | feat/live-control | Live control port | diff --git a/docs/control-protocol.md b/docs/control-protocol.md new file mode 100644 index 00000000..5e0fec7f --- /dev/null +++ b/docs/control-protocol.md @@ -0,0 +1,103 @@ +# The live control port + +`anicraft --control ` opens the AniCraft window as usual and also listens on a port on this +computer, so an assistant (or a script) can edit the open document while you watch. Every edit +appears in the window at once and undoes with Ctrl+Z, like your own. The status bar says +"Remote control on (port N)" while it is open. ADR 0070 records the design. + +Most people never speak this protocol themselves: AI assistants reach it through +`anicraft-cli mcp --bridge ` (see `docs/mcp.md`). + +```sh +anicraft --control 9878 # 9878 by convention +ANICRAFT_CONTROL_PORT=9878 anicraft # the same; --control wins over the variable +``` + +## Transport + +* TCP on `127.0.0.1` only. +* One JSON object per line (UTF-8, `\n`; a `\r` before it is ignored), each way. +* Connections stay open; requests on one connection are answered in order. + +## Authentication + +Each run makes a fresh token: 64 hex digits from the operating system's random numbers. The app +writes it to `control.json` in AniCraft's settings folder: + +| System | File | +|---|---| +| Windows | `%APPDATA%\AniCraft\control.json` | +| macOS | `~/Library/Application Support/AniCraft/control.json` | +| Linux | `$XDG_CONFIG_HOME/anicraft/control.json` (default `~/.config/anicraft/`) | + +```json +{"port": 9878, "token": "3f1c…", "pid": 12345, "version": "0.2.1"} +``` + +On macOS and Linux the file is readable only by you; on Windows the settings folder already is. +It is replaced when AniCraft starts with `--control` and removed when it closes. A program running +as you finds the token there, with nothing to copy into its settings. + +If `ANICRAFT_CONTROL_TOKEN` is set, it is the token instead (set it for both the app and the +client: CI, power users). + +Every request carries `"token"`. A missing or wrong token gets an error and the connection +closes before anything runs. + +## Requests and replies + +```json +{"id": 1, "token": "…", "method": "hello"} +{"id": 1, "ok": true, "result": {"app": "AniCraft", "version": "0.2.1", "protocol": 1}} +``` + +`id` is any JSON value and comes back as it was. A reply is `{"id", "ok": true, "result"}` or +`{"id", "ok": false, "error": "message"}`. + +| Method | Params | Result | +|---|---|---| +| `hello` | | `{app, version, protocol}` | +| `tools.list` | | the tools, exactly as MCP `tools/list` lists them (`docs/mcp.md`) | +| `tools.call` | `{name, arguments}` | exactly what MCP `tools/call` returns: `{content: […], isError}` | + +`tools.call` runs the same code as the headless MCP server. A tool that fails (a command's error) +is a result with `"isError": true`; a malformed call (an unknown tool, a missing `name`) is an +`"ok": false` reply. + +```json +{"id": 2, "token": "…", "method": "tools.call", "params": {"name": "anicraft_run", "arguments": {"command": "draw.rect", "params": {"x": 10, "y": 10, "w": 50, "h": 50}}}} +{"id": 2, "ok": true, "result": {"content": [{"type": "text", "text": "{\"frame\": 0, \"result\": {…}, \"revision\": 3, \"scene\": 0}"}], "isError": false}} +``` + +## When calls run + +The window runs calls at the start of a frame, so an edit shows in that frame. It never takes +keyboard focus and doesn't need to be the front window. An edit made while the start screen is showing closes it, so you see +the document it changed. + +While you are dragging (or a plug-in dialog is previewing), calls that could change the document +wait until you let go, so your drag and the assistant's edit stay separate undo steps. Calls that +only read run at once. If you were typing in a field, your change is kept as its own undo step +first. A call that waited 60 seconds is not run, and its reply says so. + +Commands that would lose work or replace a file still need `"confirm": true` (ADR 0004). + +## Limits + +| | | +|---|---| +| Line length | 4 MiB; a longer line gets an error and the connection closes | +| Connections | 16 at once; another gets an error line and is closed | +| Waiting | 60 s per call | +| First line | must be a JSON object with a string `"method"`, or the connection closes (this also refuses a web page's request to localhost) | + +## Trying it by hand + +With AniCraft open with `--control 9878`, in PowerShell: + +```powershell +$t = (Get-Content "$env:APPDATA\AniCraft\control.json" | ConvertFrom-Json).token +$c = New-Object Net.Sockets.TcpClient 127.0.0.1, 9878 +$w = New-Object IO.StreamWriter $c.GetStream(); $r = New-Object IO.StreamReader $c.GetStream() +$w.WriteLine("{""id"":1,""token"":""$t"",""method"":""hello""}"); $w.Flush(); $r.ReadLine() +``` diff --git a/docs/mcp.md b/docs/mcp.md index ce1a3be1..b3f8a088 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8,8 +8,22 @@ look at frames and export through the same commands the app uses. anicraft-cli mcp # a new, empty document anicraft-cli mcp scene.anicraft # open a document anicraft-cli mcp --sample # the sample animation +anicraft-cli mcp --bridge 9878 # the AniCraft window you have open (below) ``` +## Headless or live + +Without `--bridge` the server edits a document of its own, with no window: good for pipelines and +batch work. Save it (`file.save`) to keep the result. + +With `--bridge ` the same tools act on the AniCraft window you have open, started with +`anicraft --control `: every edit appears there at once, and Ctrl+Z undoes it +(`docs/control-protocol.md`, ADR 0070). The server starts even when AniCraft isn't open (an +assistant starts its servers when it starts) and connects on the first tool call; until AniCraft is +open with remote control, the tools answer with how to start it. Close and reopen AniCraft whenever +you like: the next call reconnects, with no need to restart the assistant. It finds the run's token +in `control.json` in AniCraft's settings folder, so there is nothing to copy. + The server talks MCP's stdio transport: JSON-RPC 2.0, one message per line on stdin and stdout. It speaks protocol revisions 2025-06-18, 2025-03-26 and 2024-11-05. @@ -28,6 +42,19 @@ Most clients take a server entry like this one (use the full path to `anicraft-c } ``` +For live editing, start AniCraft with `--control 9878` (a desktop shortcut is handy) and use: + +```json +{ + "mcpServers": { + "anicraft": { + "command": "C:\\path\\to\\anicraft-cli.exe", + "args": ["mcp", "--bridge", "9878"] + } + } +} +``` + ## Tools | Tool | What it does | @@ -54,3 +81,6 @@ timeline). save, import, export), as with the CLI. Only connect clients you trust with those files. * 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, + since it may have been made; the assistant is told to check with `anicraft_document`. While you + are dragging, the assistant's edits wait until you let go, so the two stay separate undo steps. diff --git a/docs/roadmap.md b/docs/roadmap.md index 6161a6c3..f352c14a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,7 +14,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. Not yet: pen tilt (egui doesn't report it), opacity varying along a stroke, textured or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | -| Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | +| 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 0070, `docs/control-protocol.md`): `anicraft --control ` and `anicraft-cli mcp --bridge ` run the same tools on the open window, 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. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | | Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. **Templates, SVG into the Library and drops on the timeline** (ADR 0065): six built-in templates made in code (banners 728 × 90 and 300 × 250, social square 1080 × 1080 at 30 fps, storyboard 16:9 panels, character turnaround, lip-sync mouth chart) with guides on a locked guide layer, on the start screen and File › New from Template; File › Save as Template keeps the document with a picture in the settings folder by category (replacing and deleting confirm); an SVG dropped on or imported to the Library becomes one graphic symbol named after the file, in the folder under the pointer; a sound dropped on a layer's frame goes onto that keyframe, an image or SVG onto that layer in a keyframe made there if needed, one undo step, with a highlight on the cell. Not yet: exact drop positions on the desktop (eframe 0.36 and 0.37 are on winit 0.30, which gives none during a drag; a drop waits for the first pointer move, else lands mid-view), user template descriptions and renaming, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | diff --git a/src/app.rs b/src/app.rs index 6dccf28e..fb165c7a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -285,6 +285,9 @@ pub use anicraft_engine::doc::LibraryItem; pub struct App { #[cfg(not(target_arch = "wasm32"))] pub(crate) updates: crate::updates::Updates, + /// The live control port, with `--control` (ADR 0070). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) remote: Option, pub s: Session, pub tool: Tool, pub view: StageView, @@ -549,6 +552,8 @@ impl App { let mut app = App { #[cfg(not(target_arch = "wasm32"))] updates: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + remote: None, s: session, tool: Tool::Select, view: StageView { zoom: 1.0, pan: egui::Vec2::ZERO, fit: true, fitted: None }, @@ -2779,6 +2784,8 @@ impl eframe::App for App { self.recovery.finish(&self.s, clean); #[cfg(not(target_arch = "wasm32"))] self.updates.finish(); + #[cfg(not(target_arch = "wasm32"))] + crate::remote::finish(self); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { @@ -2798,6 +2805,9 @@ impl App { } } self.handle_screenshot(&ctx); + // An assistant's edits (ADR 0070), before anything draws: they show in this frame. + #[cfg(not(target_arch = "wasm32"))] + crate::remote::poll(self, &ctx); self.poll_font_scan(&ctx); self.follow_system_contrast(&ctx); if let Some(p) = platform::picked_file() { diff --git a/src/main.rs b/src/main.rs index 594d1051..14dc0b90 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ //! ```text //! anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open ] //! [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] +//! [--control ] //! anicraft --version //! ``` //! `--screenshot` starts normally, draws ~120 frames, saves the window as PNG and exits. @@ -55,6 +56,8 @@ mod platform; mod plugins_ui; mod prefs; mod recent; +#[cfg(not(target_arch = "wasm32"))] +mod remote; mod scale_grid; mod sound; mod shape_hints; @@ -111,7 +114,7 @@ struct Look { } #[cfg(not(target_arch = "wasm32"))] -fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, open: Option, look: Look) -> eframe::Result { +fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, open: Option, look: Look, control: Option) -> eframe::Result { let options = eframe::NativeOptions { viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])), renderer, @@ -143,6 +146,10 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o start::open(&mut a); } a.preview_look(&cc.egui_ctx, look.theme, look.scale); + // `--control`: an assistant can edit this window live (ADR 0070). + if let Some(port) = control { + remote::start(&mut a, &cc.egui_ctx, port); + } a.open_panel(open.as_deref()); // An imported document says what came across, as opening it from the menu does. if let Some(r) = report { @@ -171,6 +178,8 @@ struct Args { open: Option, renderer: Option, look: Look, + /// `--control `: the live control port (ADR 0070). + control: Option, /// `--version` / `--help`: print and leave. print: Option, } @@ -191,6 +200,8 @@ fn parse_args(args: impl IntoIterator) -> Result { match a.as_str() { "--screenshot" => out.shot = Some(PathBuf::from(args.next().ok_or("--screenshot needs a file name")?)), // i18n-exempt: a console message "--open" => out.open = args.next(), + // i18n-exempt: a console message + "--control" => out.control = Some(anicraft_cli::control::parse_port(&args.next().unwrap_or_default()).map_err(|e| format!("--control: {e}"))?), "--renderer" => out.renderer = args.next(), "--shot-width" => match args.next().and_then(|s| s.parse::().ok()) { Some(w) if (64..=8192).contains(&w) => out.look.shot_width = Some(w), @@ -226,7 +237,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--control ] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ @@ -234,6 +245,8 @@ const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--sc --theme the interface palette for this run (not saved)\n\ --scale the interface scale for this run, 75 to 200 (not saved)\n\ --lang the interface language for this run (not saved); pseudo tests the layout\n\ + --control lets an assistant edit this window live through a port on this computer\n\ + (also ANICRAFT_CONTROL_PORT; 9878 by convention; see docs/control-protocol.md)\n\ Headless use: anicraft-cli --help"; #[cfg(not(target_arch = "wasm32"))] @@ -263,7 +276,21 @@ fn main() -> eframe::Result { } None => {} } - let Args { shot, file, open, renderer, look, .. } = args; + let Args { shot, file, open, renderer, look, control, .. } = args; + // ANICRAFT_CONTROL_PORT when there is no --control; a bad port stops here, before a window. + let control = match control { + Some(p) => Some(p), + None => match std::env::var(anicraft_cli::control::PORT_ENV).ok().filter(|v| !v.trim().is_empty()) { + Some(v) => match anicraft_cli::control::parse_port(&v) { + Ok(p) => Some(p), + Err(e) => { + eprintln!("{}: {e}", anicraft_cli::control::PORT_ENV); + std::process::exit(2); + } + }, + None => None, + }, + }; // macOS hands documents over as Apple Events, the one that launched the app included: listen // from before the event loop starts until it ends (ADR 0062). let _documents = platform::listen_for_documents(); @@ -272,10 +299,10 @@ fn main() -> eframe::Result { // on some Linux setups) retry once with OpenGL, unless the user forced a backend. let forced = platform::forced_renderer(renderer.as_deref()); let first = forced.unwrap_or(eframe::Renderer::Wgpu); - match run(first, file.as_deref(), shot.clone(), open.clone(), look.clone()) { + match run(first, file.as_deref(), shot.clone(), open.clone(), look.clone(), control) { Err(e) if forced.is_none() && first == eframe::Renderer::Wgpu => { eprintln!("GPU backend (wgpu) failed to start: {e}. Retrying with OpenGL."); - run(eframe::Renderer::Glow, file.as_deref(), shot, open, look) + run(eframe::Renderer::Glow, file.as_deref(), shot, open, look, control) } other => other, } @@ -305,6 +332,11 @@ mod args_tests { assert_eq!(parse(&["--screenshot", "a.png", "--shot-width", "1200"]).look.shot_width, Some(1200)); assert!(parse_args(["--shot-width".to_string(), "9".to_string()]).is_err()); assert_eq!(parse(&["--version"]).print, Some(Print::Version)); + // `--control ` (ADR 0070): a port from 1 to 65535, or an error before any window. + assert_eq!(parse(&["--control", "9878"]).control, Some(9878)); + for bad in [&["--control"][..], &["--control", "0"], &["--control", "99999"], &["--control", "port"]] { + assert!(parse_args(bad.iter().map(|a| a.to_string())).is_err(), "{bad:?}"); + } // And the file opens: the session starts with it, not the sample. let dir = std::env::temp_dir().join(format!("anicraft-shell-args-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); diff --git a/src/panels.rs b/src/panels.rs index c7a79b2d..eef49bf0 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -208,6 +208,13 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) { let small = |t: String| text(Type::Data, t).color(T.text_faint); ui.label(small(tr!("undo {steps} · {size} MB", steps = app.s.history().undo_len(), size = format!("{:.1}", app.s.history().bytes() as f32 / (1024.0 * 1024.0))))); ui.add_space(12.0); + // An assistant can edit this window (ADR 0070): always in view while that is so. + #[cfg(not(target_arch = "wasm32"))] + if let Some(port) = crate::remote::port(app) { + ui.label(text(Type::Label, tr!("Remote control on (port {port})", port = port)).color(T.text_faint)) + .on_hover_text(tr!("An assistant can edit this document through a control port on this computer. Its edits appear here at once and undo like your own. Started with --control; close AniCraft to turn it off.")); + ui.add_space(12.0); + } if let Some(a) = crate::autosave::status(app, now) { ui.label(small(a)).on_hover_text(tr!("A recovery copy of your unsaved work. If AniCraft closes unexpectedly, the next start offers it back.")); ui.add_space(12.0); diff --git a/src/platform.rs b/src/platform.rs index d1ca41c5..ab45f471 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -201,6 +201,31 @@ pub fn recovery_dir() -> Option { } } +/// Writes a file only this user may read (the control port's token, ADR 0070), making its folder +/// first. On Windows the settings folder (%APPDATA%) is already private to the user; elsewhere +/// the file is made owner-only (0600). +#[cfg(not(target_arch = "wasm32"))] +pub fn write_private_file(path: &std::path::Path, contents: &[u8]) -> std::io::Result<()> { + use std::io::Write; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + options.mode(0o600); + // An older file keeps its mode when opened: tighten it first. + if path.exists() { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + } + } + let mut f = options.open(path)?; + f.write_all(contents)?; + f.sync_all() +} + /// Whether the recovery folder was chosen explicitly (screenshot runs only touch it then). pub fn recovery_dir_overridden() -> bool { std::env::var_os("ANICRAFT_RECOVERY_DIR").is_some_and(|v| !v.is_empty()) diff --git a/src/remote.rs b/src/remote.rs new file mode 100644 index 00000000..17cc94de --- /dev/null +++ b/src/remote.rs @@ -0,0 +1,143 @@ +//! Remote control (ADR 0070, `docs/control-protocol.md`): `anicraft --control ` opens a +//! control port on this computer, and an assistant (through `anicraft-cli mcp --bridge`) edits +//! the open document live. The port, its threads and the tools are `anicraft_cli::control`'s; +//! this module runs each call on the window's session at the start of a frame, writes the +//! run's token to `control.json` in the settings folder, and removes it on exit. +//! +//! A call that edits waits while the person is dragging (or a plug-in dialog has its preview +//! open), so the two never share an undo step. Typing in a field doesn't hold it back: the +//! person's typed change is committed as its own step first, as clicking elsewhere would. + +use crate::app::{App, Drag}; +use crate::platform; +use anicraft_cli::{control, mcp}; +use anicraft_engine::Session; +use serde_json::Value; +use std::collections::VecDeque; +use std::path::PathBuf; +use std::sync::Arc; + +/// An open control port. +pub struct Remote { + server: control::Server, + /// Calls in arrival order; the first one that edits holds the rest back during a drag. + waiting: VecDeque, + token: String, + /// `control.json`, when it could be written. + file: Option, +} + +/// Opens the control port; failures go to the status bar (the window still opens). +pub fn start(app: &mut App, ctx: &egui::Context, port: u16) { + let token = match control::token_from_env().map_or_else(control::new_token, Ok) { + Ok(t) => t, + Err(e) => { + app.status_err(tr!("Remote control is off: {reason}", reason = e)); + return; + } + }; + let wake_ctx = ctx.clone(); + let server = match control::listen(port, token.clone(), Arc::new(move || wake_ctx.request_repaint())) { + Ok(s) => s, + Err(e) => { + app.status_err(tr!("Remote control is off: port {port} is in use or not allowed ({reason}). Is another AniCraft already open with remote control?", port = port, reason = e)); + return; + } + }; + let file = control::control_file(); + let written = file.as_ref().map(|path| { + let contents = control::ControlFile { port: server.port, token: token.clone(), pid: std::process::id(), version: env!("CARGO_PKG_VERSION").to_string() }; + platform::write_private_file(path, contents.to_json().to_string().as_bytes()) + }); + if let Some(Err(e)) = &written { + // The port works with ANICRAFT_CONTROL_TOKEN; without the file a bridge can't find it. + app.status_err(tr!("Remote control is on, but its token could not be saved ({reason}); set ANICRAFT_CONTROL_TOKEN for the assistant.", reason = e)); + } + let file = if matches!(written, Some(Ok(()))) { file } else { None }; + app.remote = Some(Remote { server, waiting: VecDeque::new(), token, file }); +} + +/// The port, while remote control is on (the status bar shows it). +pub fn port(app: &App) -> Option { + app.remote.as_ref().map(|r| r.server.port) +} + +/// Whether the person is in the middle of an edit a remote one must not join. +fn person_is_dragging(app: &App, ctx: &egui::Context) -> bool { + app.drag != Drag::None || app.plugin_dialog.is_some() || (app.s.in_gesture() && ctx.egui_is_using_pointer()) +} + +/// Runs the waiting calls: at the start of a frame, so their edits draw in this one. +pub fn poll(app: &mut App, ctx: &egui::Context) { + let Some(r) = app.remote.as_mut() else { return }; + while let Some(req) = r.server.try_recv() { + r.waiting.push_back(req); + } + loop { + let dragging = person_is_dragging(app, ctx); + let Some(r) = app.remote.as_mut() else { return }; + let Some(next) = r.waiting.front() else { return }; + if next.changes_document() && dragging && !next.expired() { + // Look again shortly: the drag ends without a remote wake-up. + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + return; + } + let Some(req) = r.waiting.pop_front() else { return }; + // (An expired call is refused without running: it leaves the person's gesture alone.) + if req.changes_document() && !req.expired() && !dragging && app.s.in_gesture() { + // A typed property change still open: it becomes its own undo step first. + app.s.end_gesture(); + } + req.run(&mut Live(app)); + } +} + +/// On exit: calls still waiting are told so, and `control.json` goes (if it is still ours). +pub fn finish(app: &mut App) { + let Some(mut r) = app.remote.take() else { return }; + for req in r.waiting.drain(..) { + // i18n-exempt: the protocol's English, read by the assistant (as MCP) + req.refuse("AniCraft is closing"); + } + if let Some(path) = &r.file { + let ours = std::fs::read_to_string(path).ok().and_then(|t| control::ControlFile::parse(&t).ok()).is_some_and(|c| c.token == r.token); + if ours { + let _ = std::fs::remove_file(path); + } + } +} + +/// The window as the tools' host: commands run with the follow-up the person's own get (the +/// status line, the view a new document resets, Open Recent). +struct Live<'a>(&'a mut App); + +impl mcp::Host for Live<'_> { + fn session(&self) -> &Session { + &self.0.s + } + fn execute(&mut self, id: &str, params: &Value) -> Result { + let selected = self.0.s.selection.len(); + let revision = self.0.s.revision; + let v = self.0.s.execute(id, params).map_err(|e| e.to_string())?; + // An edit to the document behind the start screen: show the document, so the person + // sees it land (ADR 0059's start screen otherwise covers the workspace). + if self.0.s.revision != revision { + self.0.start = None; + } + self.0.announce(id, &v, selected); + Ok(v) + } +} + +#[cfg(test)] +mod tests { + use crate::platform; + + /// The CLI finds `control.json` with its own copy of the settings-folder rule (it can't use + /// the shell); they must agree, or the bridge looks in the wrong place. + #[test] + fn the_bridge_looks_for_the_token_in_the_settings_folder() { + assert_eq!(anicraft_cli::control::settings_dir(), platform::config_dir()); + assert_eq!(anicraft_cli::control::control_file(), platform::config_dir().map(|d| d.join("control.json"))); + } +} From 5967b274b2953ad3050a930a407855e812bef7e9 Mon Sep 17 00:00:00 2001 From: lienatanael1-beep Date: Thu, 12 Nov 2026 15:32:09 +0700 Subject: [PATCH 029/570] docs: ADR 0070 is reserved for #216 Co-Authored-By: Claude Opus 5.5 --- docs/adr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/README.md b/docs/adr/README.md index 65918325..4f01eaae 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0070 | feat/live-control | Live control port | +| 0070 | #216 | Live control port | From a3c1a7d8ec53f609fc514549e2c45a689a7813b3 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 09:12:27 +0000 Subject: [PATCH 030/570] fix(cli): subcommand --help prints that subcommand's usage (#153) `anicraft-cli --help` (and `-h`) was parsed as a flag missing its value and failed with "flag --help needs a value". It now prints the usage lines of that subcommand, as does `anicraft-cli help `. An unknown subcommand still reports an error with the full usage. --- crates/cli/src/lib.rs | 78 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index cb9ef155..c6b0ccec 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -111,13 +111,51 @@ fn one_based(a: &Args, k: &str) -> Result, String> { } } +/// Returns the usage line(s) for a given subcommand, formatted under `USAGE:`. +pub fn subcommand_usage(cmd: &str) -> Option { + let body = match cmd { + "info" => " anicraft-cli info ", + "render" => " anicraft-cli render --out [--frame N] [--scale S]", + "render-seq" => " anicraft-cli render-seq --out-dir [--from A] [--to B] [--scale S]", + "gif" => " anicraft-cli gif --out [--from A] [--to B] [--scale S] [--overwrite yes]", + "apng" | "webp" => { + " anicraft-cli apng|webp --out [--from A] [--to B] [--scale S]\n [--loop forever|N] [--background yes] [--overwrite yes]\n full colour with real transparency (WebP: lossless)" + } + "commands" => " anicraft-cli commands", + "run" => " anicraft-cli run [--save ]", + "exec" => " anicraft-cli exec [] [--save ]", + "new" => " anicraft-cli new --out [--width W] [--height H] [--fps F]", + "guide" => " anicraft-cli guide --out writes the user guide as HTML pages (open index.html)", + "bench" => { + " anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release)\n anicraft-cli bench --check yes the default scenario against the budgets in\n docs/performance.md; fails when one is missed" + } + "serve" => { + " anicraft-cli serve [file|--sample] JSON-lines on stdin/stdout:\n {\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}}" + } + "mcp" => { + " anicraft-cli mcp [file|--sample] Model Context Protocol server on stdin/stdout,\n for AI assistants (see docs/mcp.md)" + } + "version" => " anicraft-cli --version", + _ => return None, + }; + Some(format!("USAGE:\n{body}")) +} + /// Runs the CLI; returns the text to print on success. pub fn run(argv: &[String]) -> Result { let Some((cmd, rest)) = argv.split_first() else { return Ok(USAGE.to_string()) }; + if cmd == "help" || cmd == "--help" || cmd == "-h" { + if let Some(sub) = rest.first().filter(|s| *s != "--help" && *s != "-h") { + return subcommand_usage(sub).ok_or_else(|| format!("unknown subcommand '{sub}'\n\n{USAGE}")); + } + return Ok(USAGE.to_string()); + } + if rest.iter().any(|a| a == "--help" || a == "-h") { + return subcommand_usage(cmd).ok_or_else(|| format!("unknown subcommand '{cmd}'\n\n{USAGE}")); + } let a = Args::parse(rest)?; let src = a.positional.first().map(String::as_str); match cmd.as_str() { - "help" | "--help" | "-h" => Ok(USAGE.to_string()), // The release packaging smoke-tests every build with this (packaging/, ADR 0026). "version" | "--version" | "-V" => Ok(format!("anicraft-cli {}", env!("CARGO_PKG_VERSION"))), "commands" => { @@ -589,4 +627,42 @@ mod tests { assert!(run(&["commands".into()]).unwrap().contains("timeline.insert_keyframe")); assert!(run(&["guide".into()]).is_err()); } + + #[test] + fn subcommand_help_prints_usage() { + let subcommands = ["info", "render", "render-seq", "gif", "apng", "webp", "commands", "run", "exec", "new", "guide", "bench", "serve", "mcp"]; + for sub in subcommands { + let out_long = run(&[sub.to_string(), "--help".to_string()]).unwrap(); + assert!(out_long.contains("USAGE:"), "help for {sub} should contain USAGE:"); + assert!(out_long.contains(sub), "help for {sub} should mention {sub}"); + + let out_short = run(&[sub.to_string(), "-h".to_string()]).unwrap(); + assert_eq!(out_long, out_short); + + let out_help = run(&["help".to_string(), sub.to_string()]).unwrap(); + assert_eq!(out_long, out_help); + } + + // Subcommand help with other arguments present + assert_eq!( + run(&["render".into(), "--scale".into(), "2".into(), "--help".into()]).unwrap(), + run(&["render".into(), "--help".into()]).unwrap() + ); + + // Unknown subcommand with --help or help still reports unknown + assert!(run(&["bogus".into(), "--help".into()]).is_err()); + assert!(run(&["help".into(), "bogus".into()]).is_err()); + } + + #[test] + fn subcommand_usage_matches_usage_text() { + let subcommands = + ["info", "render", "render-seq", "gif", "apng", "webp", "commands", "run", "exec", "new", "guide", "bench", "serve", "mcp", "version"]; + for sub in subcommands { + let u = subcommand_usage(sub).expect("subcommand_usage should exist"); + let body = u.strip_prefix("USAGE:\n").expect("should start with USAGE:\n"); + assert!(USAGE.contains(body), "USAGE should contain body for {sub}"); + } + assert_eq!(subcommand_usage("bogus"), None); + } } From de3a88f2f88550b9b7baf968c7a343b6adc30a8c Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 09:40:27 +0000 Subject: [PATCH 031/570] fix(shell): Ctrl+C, Ctrl+X and Ctrl+V copy, cut and paste on the stage On the desktop egui-winit turns Ctrl/Cmd+X, C and V into Cut, Copy and Paste events and drops the key press, so the keymap never matched them. Outside text fields those events become their key presses again (with the modifiers held, so Ctrl+Shift+V is still Paste in Place). Paste only arrives when the system clipboard holds text, so a copy or cut now puts a short note there. The browser build already sends key presses and is unchanged. Fixes #197 --- src/app.rs | 134 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 133 insertions(+), 1 deletion(-) diff --git a/src/app.rs b/src/app.rs index 6dccf28e..47adf8dd 100644 --- a/src/app.rs +++ b/src/app.rs @@ -434,6 +434,9 @@ pub struct App { fonts_rx: Option>, /// Re-check which glyphs the active fonts have (after fonts change). glyph_check: bool, + /// A copy or cut ran: the system clipboard gets a note at the end of the frame, so the next + /// Ctrl/⌘+V reaches the app (egui-winit sends a paste only when the clipboard holds text). + copied: bool, /// Document revision at the end of the last frame (edits schedule a repaint). last_revision: u64, title: String, @@ -640,6 +643,7 @@ impl App { system_fonts: None, fonts_rx: None, glyph_check: true, + copied: false, last_revision: 0, title: String::new(), keymap, @@ -713,7 +717,12 @@ impl App { platform::deliver(anicraft_engine::vfs::take_written()); } match result { - Ok(v) => Some(v), + Ok(v) => { + if matches!(id, "edit.copy" | "edit.cut" | "timeline.copy_frames" | "timeline.cut_frames" | "frames.copy" | "frames.cut") { + self.copied = true; + } + Some(v) + } Err(e) => { // The engine's English, translated when a catalog has that exact message. self.status_err(crate::i18n::t_dyn(&e.to_string()).into_owned()); @@ -2407,6 +2416,10 @@ impl App { } return; } + // (A browser sends these keys as presses already, with its clipboard events after.) + if !platform::WEB { + ctx.input_mut(clipboard_keys_as_presses); + } let control = keys == crate::a11y::Keyboard::Control; if !control { crate::motion_path::consume_keys(self, ctx); @@ -2918,6 +2931,12 @@ impl App { crate::brush_panel::sync(self); // A browser asks before leaving a page with unsaved work (its close guard). platform::set_unsaved(self.s.is_dirty()); + // Copied artwork or frames: the system clipboard says so, as any copy replaces what it + // held, and so the next Ctrl/⌘+V comes through (issue #197). A browser sends that key + // press whatever its clipboard holds. + if std::mem::take(&mut self.copied) && !platform::WEB { + ctx.copy_text(tr!("Copied from AniCraft").to_string()); + } // An edit late in this frame (after the stage drew) must be shown without waiting for // the next input event: egui only repaints on demand. This was the "drag commits after a @@ -2929,6 +2948,119 @@ impl App { } } +/// On the desktop egui-winit turns Ctrl/⌘+X, C and V (and Shift+Delete, Ctrl+Insert and +/// Shift+Insert on Windows) into `Event::Cut`, `Event::Copy` and `Event::Paste` instead of key +/// presses, so the keymap never saw them (issue #197). Outside a text field they are shortcuts +/// like any other: each becomes its key press again, with the modifiers held (Ctrl+Shift+V is +/// Paste in Place), and the keymap decides what it runs. The events stay for egui. +fn clipboard_keys_as_presses(i: &mut egui::InputState) { + // Without Ctrl/⌘ it was Shift+Delete, Ctrl+Insert, Shift+Insert or a Cut/Copy/Paste key. + let modifiers = if i.modifiers.command { i.modifiers } else { Modifiers::COMMAND }; + let keys: Vec = i + .events + .iter() + .filter_map(|e| match e { + egui::Event::Cut => Some(Key::X), + egui::Event::Copy => Some(Key::C), + egui::Event::Paste(_) => Some(Key::V), + _ => None, + }) + .collect(); + i.events.extend(keys.into_iter().map(|key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers })); +} + +/// Ctrl/⌘+X, C and V on the stage (issue #197). On the desktop egui-winit hands them over as +/// `Event::Cut`, `Event::Copy` and `Event::Paste`, never as key presses, so these tests send +/// exactly that. +#[cfg(test)] +mod clipboard_key_tests { + use super::App; + use egui::{Event, Modifiers, RawInput, Rect, pos2, vec2}; + + fn app() -> (egui::Context, App) { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + (ctx, app) + } + + /// The keys held (as egui-winit reports them, first) and the events of one frame. + fn input(modifiers: Modifiers, events: Vec) -> RawInput { + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1600.0, 940.0))), events, ..Default::default() } + } + + /// One frame; what it asked the system clipboard to hold. + fn frame(ctx: &egui::Context, app: &mut App, input: RawInput) -> Vec { + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + out.platform_output.commands.into_iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t) } else { None }).collect() + } + + /// Elements on the playhead's frame, every layer. + fn elements(app: &App) -> usize { + app.s.timeline().layers.iter().filter_map(|l| l.keyframe_at(app.s.frame)).map(|k| k.elements.len()).sum() + } + + fn ctrl() -> Modifiers { + Modifiers::CTRL | Modifiers::COMMAND + } + + #[test] + fn ctrl_c_x_and_v_copy_cut_and_paste_the_selected_artwork() { + let (ctx, mut app) = app(); + for _ in 0..3 { + frame(&ctx, &mut app, input(Modifiers::NONE, vec![])); + } + app.run("edit.select_all", serde_json::json!({})); + assert!(!app.s.selection.is_empty(), "the sample has artwork to select"); + let before = elements(&app); + // Ctrl+C copies, and puts something on the system clipboard, so the next Ctrl+V + // reaches the app even when the clipboard held no text before. + let copied = frame(&ctx, &mut app, input(ctrl(), vec![Event::Copy])); + assert!(!app.s.clipboard.is_empty(), "Ctrl+C copied the selection"); + assert!(copied.iter().any(|t| !t.is_empty()), "the system clipboard holds text: {copied:?}"); + assert_eq!(elements(&app), before, "copying changes nothing"); + // Ctrl+V pastes a copy (whatever text the system clipboard holds). + let steps = app.s.history().undo_len(); + frame(&ctx, &mut app, input(ctrl(), vec![Event::Paste("AniCraft artwork".into())])); + assert!(elements(&app) > before, "Ctrl+V pasted the artwork"); + assert_eq!(app.s.history().undo_len(), steps + 1, "one undo step"); + // Ctrl+Shift+V is Paste in Place. + let pasted = elements(&app); + frame(&ctx, &mut app, input(ctrl() | Modifiers::SHIFT, vec![Event::Paste("AniCraft artwork".into())])); + assert!(elements(&app) > pasted, "Ctrl+Shift+V pasted in place"); + // Ctrl+X cuts what is selected (the pasted copy). + let now = elements(&app); + frame(&ctx, &mut app, input(ctrl(), vec![Event::Cut])); + assert!(elements(&app) < now, "Ctrl+X cut the selection"); + } + + #[test] + fn a_text_field_keeps_its_own_copy_and_paste() { + let (ctx, mut app) = app(); + let mut text = String::new(); + let run = |app: &mut App, text: &mut String, input: RawInput| { + let mut out = ctx.run_ui(input, |ui| { + ui.text_edit_singleline(text).request_focus(); + app.frame(ui); + }); + out.textures_delta.clear(); + }; + for _ in 0..3 { + run(&mut app, &mut text, input(Modifiers::NONE, vec![])); + } + assert!(ctx.text_edit_focused(), "the field has the keyboard"); + app.run("edit.select_all", serde_json::json!({})); + let before = elements(&app); + run(&mut app, &mut text, input(ctrl(), vec![Event::Copy])); + assert!(app.s.clipboard.is_empty(), "Ctrl+C in a text field does not copy artwork"); + run(&mut app, &mut text, input(ctrl(), vec![Event::Paste("hello".into())])); + assert_eq!(text, "hello", "the field took the paste"); + assert_eq!(elements(&app), before, "and the stage did not"); + } +} + #[cfg(test)] mod shrink_tests { use super::shrink; From a55ca843e8fe2215112b60426f194f5f5fb49213 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 10:31:10 +0000 Subject: [PATCH 032/570] fix(timeline): a click on the playhead selects its frame on every layer, so F5 and the other frame keys act on all layers Clicking or dragging the frame ruler only moved the playhead and left the frame selection on one layer, so Insert Frame (F5), Remove Frames, the keyframe keys and Copy/Cut Frames went to the active layer only. The ruler now selects the playhead's frame from the first to the last layer; clicking a frame of one layer narrows it to that layer again. Each command stays one undo step. Fixes #195 --- docs/guide/timeline.md | 2 ++ src/timeline.rs | 67 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/docs/guide/timeline.md b/docs/guide/timeline.md index 2667634f..a06a9ed8 100644 --- a/docs/guide/timeline.md +++ b/docs/guide/timeline.md @@ -120,6 +120,8 @@ An empty frame shows a hint in **Properties › Frame**: press **F7** to start d * Click a frame to select it and move the playhead there. * **Shift**-click, or drag across frames, to select a range. A selection can span several layers. +* Click the playhead (the frame ruler) to select that frame on every layer. **F5**, **F6** + and the other frame keys then act on all layers, until you click a frame of one layer. * **Ctrl+Alt+A** selects every frame. The frame keys, the header buttons and the right-click menu all act on the whole selection. diff --git a/src/timeline.rs b/src/timeline.rs index adf0b28d..625989a9 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -403,6 +403,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { && let Some(p) = ruler_resp.interact_pointer_pos() { app.playing = false; app.run("timeline.goto", json!({"frame": frame_at(p.x)})); + // The playhead's frame on every layer, as in Animate: F5, F6, Shift+F5 and the + // other frame commands then act on all layers until a frame of one layer is clicked. + let layers = &app.s.timeline().layers; + if let (Some(a), Some(b)) = (layers.first(), layers.last()) { + app.frame_sel = Some(FrameSel { anchor: (a.id, app.s.frame), head: (b.id, app.s.frame) }); + } } // The onion menu on a right-click, as the markers live here (ADR 0047). ruler_resp.context_menu(|ui| crate::onion::menu(app, ui)); @@ -1659,4 +1665,65 @@ mod tests { // A deleted layer invalidates the selection. assert!(FrameSel { anchor: (LayerId(9), 0), head: (LayerId(1), 0) }.layers(&ls).is_empty()); } + + /// Each layer's length, in frames. + fn ends(app: &App) -> Vec<(LayerId, u32)> { + app.s.timeline().layers.iter().map(|l| (l.id, l.end_frame())).collect() + } + + /// Issue 195: a click on the playhead (the frame ruler) picks that frame on every layer, so + /// F5 adds a frame to all of them; a click on one layer's frame goes back to that layer. + #[test] + fn a_click_on_the_playhead_makes_frame_keys_act_on_every_layer() { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 940.0) / app.prefs.ui_scale); + let frame = |app: &mut App, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| app.frame(ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update + }; + let mut tree = None; + for _ in 0..3 { + tree = frame(&mut app, Vec::new()).or(tree); + } + let layers: Vec = app.s.timeline().layers.iter().filter(|l| l.kind != LayerKind::Folder).map(|l| l.id).collect(); + assert!(layers.len() >= 2, "the sample has several layers: {layers:?}"); + // The second layer is the active one, as after a click on its name. + app.s.layer = layers[1]; + // The frame ruler, found by its name for screen readers. + let ppp = ctx.pixels_per_point(); + let ruler = tree + .and_then(|t| t.nodes.into_iter().find(|(_, n)| n.label() == Some("Playhead (frame ruler)"))) + .and_then(|(_, n)| n.bounds()) + .map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32) / ppp, pos2(b.x1 as f32, b.y1 as f32) / ppp)) + .unwrap_or_else(|| panic!("no frame ruler on screen")); + // Click the ruler a little way in (frame 3 or so). + let at = pos2(ruler.left() + 40.0, ruler.center().y); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, vec![press(true)]); + frame(&mut app, vec![press(false)]); + frame(&mut app, Vec::new()); + let f = app.s.frame; + assert!(f > 0, "the click moved the playhead"); + let before = ends(&app); + let steps = app.s.history_len(); + app.invoke("timeline.insert_frame"); + assert_eq!(app.s.history_len(), steps + 1, "one undo step"); + // The same as F5 on every layer at the playhead. + let all = ends(&app); + app.s.undo().expect("undo"); + assert_eq!(ends(&app), before, "one undo takes it all back"); + app.run("timeline.insert_frame", json!({"layers": layers.iter().map(|l| l.0).collect::>(), "frame": f})); + assert_eq!(all, ends(&app), "F5 after a click on the playhead adds a frame on every layer"); + app.s.undo().expect("undo"); + assert!(before.iter().zip(&all).filter(|(b, a)| b != a).count() >= 2, "more than one layer grew: {before:?} → {all:?}"); + // A click on one layer's frame (what the grid does) acts on that layer only again. + app.frame_sel = Some(FrameSel::cell(layers[1], f)); + app.invoke("timeline.insert_frame"); + let one = ends(&app); + assert_eq!(before.iter().zip(&one).filter(|(b, a)| b != a).map(|(b, _)| b.0).collect::>(), vec![layers[1]]); + } } From 2cc96ba8f0989912711dee043032f88a23c31880 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 10:39:11 +0000 Subject: [PATCH 033/570] docs(cli): say which frame numbers are 1-based and which are 0-based (#152) The usage text said only that frames on the command line are 1-based. It now also says that frame numbers inside JSON params, scripts and command results are 0-based, as docs/mcp.md already does. --- crates/cli/src/lib.rs | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index cb9ef155..1a9cb983 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -39,7 +39,9 @@ USAGE: ANICRAFT_PLUGINS environment variable); see docs/plugins.md. Without it, headless runs use no plug-ins, so they are repeatable. -Frames on the command line are 1-based, as in the timeline."; +Frame flags on the command line (--frame, --from, --to) are 1-based, as in the +timeline. Frame numbers inside JSON params, scripts and command results are +0-based, as everywhere in the engine."; /// Parsed flags: positional args plus `--key value` pairs. pub struct Args { @@ -589,4 +591,37 @@ mod tests { assert!(run(&["commands".into()]).unwrap().contains("timeline.insert_keyframe")); assert!(run(&["guide".into()]).is_err()); } + + #[test] + fn usage_clarifies_frame_numbering_split() { + let help = run(&["help".into()]).unwrap(); + assert!(help.contains("0-based"), "CLI usage should clarify that JSON command frame numbers are 0-based"); + assert!(help.contains("1-based"), "CLI usage should clarify that command-line frame flags are 1-based"); + + let dir = std::env::temp_dir().join(format!("anicraft-cli-frame-split-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let out_cli = dir.join("cli.png"); + let out_exec = dir.join("exec.png"); + + let res_cli: serde_json::Value = serde_json::from_str( + &run(&["render".into(), "--sample".into(), "--frame".into(), "1".into(), "--out".into(), out_cli.to_str().unwrap().into()]).unwrap(), + ) + .unwrap(); + + let res_exec: serde_json::Value = serde_json::from_str( + &run(&[ + "exec".into(), + "--sample".into(), + "file.export_png".into(), + format!(r#"{{"path": "{}", "frame": 0}}"#, out_exec.to_str().unwrap().replace('\\', "/")), + ]) + .unwrap(), + ) + .unwrap(); + + assert_eq!(res_cli["frame"], 0); + assert_eq!(res_exec["frame"], 0); + assert_eq!(std::fs::read(&out_cli).unwrap(), std::fs::read(&out_exec).unwrap()); + let _ = std::fs::remove_dir_all(&dir); + } } From 90d894aa68068b311baa2ccca1e3a668cc026cc8 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:22:41 +0100 Subject: [PATCH 034/570] Sanitize dotted spacing in Dash::lerp for overshooting eases Found while testing crates/doc/src/stroke_style.rs:~233 (Dash::lerp, the Dotted/Dotted arm) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/stroke_style.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/stroke_style.rs b/crates/doc/src/stroke_style.rs index 58fdf354..ad902014 100644 --- a/crates/doc/src/stroke_style.rs +++ b/crates/doc/src/stroke_style.rs @@ -230,7 +230,7 @@ impl Dash { (Some(Dash::Dashed { lengths: la, offset: oa }), Some(Dash::Dashed { lengths: lb, offset: ob })) if la.len() == lb.len() => { Dash::Dashed { lengths: la.iter().zip(lb.iter()).map(|(&x, &y)| mix(x, y)).collect(), offset: mix(*oa, *ob) }.sanitized() } - (Some(Dash::Dotted { spacing: sa }), Some(Dash::Dotted { spacing: sb })) => Some(Dash::Dotted { spacing: mix(*sa, *sb) }), + (Some(Dash::Dotted { spacing: sa }), Some(Dash::Dotted { spacing: sb })) => Dash::Dotted { spacing: mix(*sa, *sb) }.sanitized(), _ => if t >= 1.0 { b.cloned() } else { a.cloned() }, } } @@ -319,6 +319,16 @@ mod tests { assert_eq!(Dash::dotted(f32::NAN), Some(Dash::Dotted { spacing: 0.0 })); } + #[test] + fn dotted_lerp_clamps_overshooting_spacing() { + let a = Dash::Dotted { spacing: 0.0 }; + let b = Dash::Dotted { spacing: 10.0 }; + assert_eq!(Dash::lerp(Some(&a), Some(&b), -0.5), Some(Dash::Dotted { spacing: 0.0 })); + let c = Dash::Dotted { spacing: MAX_DASH_LENGTH }; + let d = Dash::Dotted { spacing: MAX_DASH_LENGTH * 2.0 }; + assert_eq!(Dash::lerp(Some(&c), Some(&d), 1.5), Some(Dash::Dotted { spacing: MAX_DASH_LENGTH })); + } + #[test] fn dots_are_round_zero_length_dashes() { let st = StrokeStyle { cap: Cap::Butt, dash: Dash::dotted(3.0), ..StrokeStyle::default() }; From 4c73d1ce82a762e434f422470fd3e80a7855325c Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:30:22 +0100 Subject: [PATCH 035/570] Keep odd dash patterns whole when Dash::sanitized repeats them Found while testing crates/doc/src/stroke_style.rs:183-187 (Dash::sanitized) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/stroke_style.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/stroke_style.rs b/crates/doc/src/stroke_style.rs index 58fdf354..a5909fcf 100644 --- a/crates/doc/src/stroke_style.rs +++ b/crates/doc/src/stroke_style.rs @@ -174,7 +174,8 @@ impl Dash { } /// The pattern as stored, cleaned up (a file, a command): lengths finite and in range, an - /// odd count repeated, at most [`MAX_DASH_ENTRIES`], the offset within one period. + /// odd count repeated whole (so the dash/gap alternation holds where the pattern wraps), at + /// most [`MAX_DASH_ENTRIES`] read, the offset within one period. /// `None` when it draws solid (no gaps, or nothing at all to repeat). pub fn sanitized(self) -> Option { match self { @@ -183,7 +184,6 @@ impl Dash { if v.len() % 2 == 1 { let again = v.clone(); v.extend(again); - v.truncate(MAX_DASH_ENTRIES); } let period: f32 = v.iter().sum(); let gaps: f32 = v.iter().skip(1).step_by(2).sum(); @@ -319,6 +319,16 @@ mod tests { assert_eq!(Dash::dotted(f32::NAN), Some(Dash::Dotted { spacing: 0.0 })); } + #[test] + fn odd_dash_patterns_repeat_whole() { + for n in (9..=15).step_by(2) { + let base: Vec = (1..=n).map(|i| i as f32).collect(); + let d = Dash::Dashed { lengths: base.clone().into(), offset: 0.0 }.sanitized().unwrap(); + let want: Vec = base.iter().chain(base.iter()).copied().collect(); + assert_eq!(d, Dash::Dashed { lengths: want.into(), offset: 0.0 }, "n = {n}"); + } + } + #[test] fn dots_are_round_zero_length_dashes() { let st = StrokeStyle { cap: Cap::Butt, dash: Dash::dotted(3.0), ..StrokeStyle::default() }; From fe560d9bc3e1d8604bf7c1b61de5ff9f278618e7 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:58:07 +0100 Subject: [PATCH 036/570] Normalise negative sizes in Path::rounded_rect Found while testing crates/geom/src/path.rs:243-262 (Path::rounded_rect) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/path.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5c29dd2f..6468d674 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -246,7 +246,9 @@ impl Path { return Path::rect(x, y, w, h); } let k = r * (1.0 - KAPPA); - let (x1, y1) = (x + w, y + h); + // Normalise negative sizes by swapping the corners. + let (x, x1) = if w < 0.0 { (x + w, x) } else { (x, x + w) }; + let (y, y1) = if h < 0.0 { (y + h, y) } else { (y, y + h) }; let mut p = Path::new(); p.move_to(Vec2::new(x + r, y)) .line_to(Vec2::new(x1 - r, y)) @@ -499,6 +501,15 @@ pub fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 { mod tests { use super::*; + #[test] + fn rounded_rect_negative_size_matches_rect_bounds() { + for (w, h) in [(-10.0, 10.0), (10.0, -10.0), (-10.0, -10.0)] { + let b = Path::rounded_rect(0.0, 0.0, w, h, 2.0).bounds(); + let e = Path::rect(0.0, 0.0, w, h).bounds(); + assert_eq!((b.min, b.max), (e.min, e.max), "w={w} h={h}"); + } + } + #[test] fn flatten_rect_is_closed_polygon() { let pls = Path::rect(0.0, 0.0, 10.0, 5.0).flatten(&Affine::IDENTITY, 0.1); From 8cc35a3fb40dd4bc26316e5b7b531fbd1097f607 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 14:19:12 +0000 Subject: [PATCH 037/570] fix(panels): keep a flipped scale instead of clamping it to 1 % The Properties panel's Scale fields had a 1-10000 % range, and egui clamps a value that is only shown to its range and reports a change. A flipped shape (scale -100 %) was rewritten to 1 % on the next frame, so Flip Horizontal or Vertical, and dragging a transform handle past the opposite edge, squashed the shape flat instead of mirroring it. The fields now allow -10000 to 10000 % and no longer clamp a shown value. A zero scale is still refused by the engine. Fixes #116 --- src/panels.rs | 87 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 85 insertions(+), 2 deletions(-) diff --git a/src/panels.rs b/src/panels.rs index c7a79b2d..c254b2c9 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -645,8 +645,14 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E }); } row(ui, tr!("Scale"), |ui| { - let a = ui.add(egui::DragValue::new(&mut sx).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale width")); - let b = ui.add(egui::DragValue::new(&mut sy).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale height")); + // Negative is a mirror (Flip). Only edits are clamped: a scale merely shown is never + // rewritten (#116). The engine refuses a scale too near zero. + let a = ui + .add(egui::DragValue::new(&mut sx).suffix(" %").speed(0.5).range(-10000.0..=10000.0).clamp_existing_to_range(false).max_decimals(1)) + .named(tr!("Scale width")); + let b = ui + .add(egui::DragValue::new(&mut sy).suffix(" %").speed(0.5).range(-10000.0..=10000.0).clamp_existing_to_range(false).max_decimals(1)) + .named(tr!("Scale height")); if a.changed() || b.changed() { live(app, tr_noop!("Scale"), "element.set_transform", json!({"sx": sx / 100.0, "sy": sy / 100.0})); } @@ -2230,3 +2236,80 @@ fn library(app: &mut App, ui: &mut egui::Ui) { let r = ui.scope(|ui| crate::library::panel(app, ui)).response.rect; app.library.drop_zone.panel = Some(r); } + +#[cfg(test)] +mod tests { + use crate::app::App; + use anicraft_engine::Session; + use anicraft_engine::geom::Affine; + use serde_json::json; + + /// A few headless frames of the whole window, Properties panel included. + fn frames(ctx: &egui::Context, app: &mut App) { + let input = + || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), ..Default::default() }; + for _ in 0..3 { + let mut out = ctx.run_ui(input(), |ui| app.frame(ui)); + out.textures_delta.clear(); + } + } + + fn transform(app: &App) -> Affine { + app.s.visible_elements().first().map(|e| e.transform).unwrap_or_default() + } + + /// #116: the Scale fields show a flipped (negative) or very large scale as it is. Showing + /// it never writes a clamped value back (that squashed a flipped shape to 1 %). + #[test] + fn showing_a_flipped_or_huge_scale_leaves_it_alone() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, Session::default(), Some(std::path::PathBuf::from("unused.png"))); + app.run("draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 80})); + frames(&ctx, &mut app); + let b0 = app.s.selection_bounds(); + app.run("modify.flip_v", json!({})); + frames(&ctx, &mut app); + let t = transform(&app); + assert!((t.m[0] - 1.0).abs() < 1e-4 && (t.m[3] + 1.0).abs() < 1e-4, "flipped vertically, not squashed: {t:?}"); + app.run("modify.flip_h", json!({})); + frames(&ctx, &mut app); + let t = transform(&app); + assert!((t.m[0] + 1.0).abs() < 1e-4 && (t.m[3] + 1.0).abs() < 1e-4, "flipped both ways: {t:?}"); + let b1 = app.s.selection_bounds(); + assert!((b1.width() - b0.width()).abs() < 0.5 && (b1.height() - b0.height()).abs() < 0.5, "same size: {b0:?} vs {b1:?}"); + // Bigger than the fields' range (10000 %): kept too. + app.run("modify.transform", json!({"a": 150, "b": 0, "c": 0, "d": 150, "e": 0, "f": 0})); + frames(&ctx, &mut app); + let t = transform(&app); + assert!((t.m[0] + 150.0).abs() < 1e-2 && (t.m[3] + 150.0).abs() < 1e-2, "{t:?}"); + // A scale of zero is still refused, and leaves the shape as it was. + assert!(app.s.execute("element.set_transform", &json!({"sy": 0})).is_err()); + assert!(app.s.execute("modify.transform", &json!({"a": 1, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0})).is_err()); + assert_eq!(transform(&app), t); + } + + /// #116: dragging the bottom edge of the transform box up past the top edge mirrors the + /// shape; the Properties panel doesn't squash it back to 1 %. + #[test] + fn dragging_an_edge_past_the_opposite_one_mirrors() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, Session::default(), Some(std::path::PathBuf::from("unused.png"))); + app.run("draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 50})); + frames(&ctx, &mut app); + // The bottom edge goes from y 50 to y -50, past the top edge. + let m = crate::stage::xf_total( + crate::app::XfKind::Scale { hx: 0, hy: 1 }, + [0.0, 0.0, 100.0, 50.0], + egui::pos2(50.0, 50.0), + egui::pos2(50.0, -50.0), + false, + false, + ); + assert!(m.m[3] < -0.5, "the drag itself mirrors: {m:?}"); + let [a, b, c, d, e, f] = m.m; + assert!(app.s.execute("modify.transform", &json!({"a": a, "b": b, "c": c, "d": d, "e": e, "f": f})).is_ok()); + frames(&ctx, &mut app); + let t = transform(&app); + assert!((t.m[0] - 1.0).abs() < 1e-4 && (t.m[3] - m.m[3]).abs() < 1e-3, "still mirrored as dragged: {t:?}"); + } +} From 22aef692a35f6ea1d994b1d25e28531f4b3e9ecf Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 14:41:08 +0000 Subject: [PATCH 038/570] fix(tween): morph a shape's stroke with its fill when the side counts differ Merge Drawing stores a shape's line as one element per piece, cut at every corner, and a shape tween paired elements one to one by position. A triangle (3 pieces) into a hexagon (6) left sides bare or pieces standing in between. A shape tween now joins each stroke style's pieces end to end into the outlines they make, on both keyframes, and morphs those as it morphs the fill. Fixes #119 --- crates/doc/src/eval.rs | 71 ++++++++++++++++++++++++++++++++++++-- crates/engine/src/tests.rs | 62 +++++++++++++++++++++++++++++++++ crates/geom/src/morph.rs | 70 +++++++++++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index a17dcd6f..e17783dc 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -242,18 +242,85 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) let morph = tween.kind == TweenKind::Shape; let path = guide.map(|g| (g, tween.orient)); let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() }; + let lines = if morph { tween_lines(kf, next, t) } else { Vec::new() }; let els = kf .elements .iter() .enumerate() - .map(|(i, a)| { + .filter_map(|(i, a)| { + // A line tweened whole stands in for its first piece; its other pieces go. + if let Some((pieces, line)) = lines.iter().find(|l| l.0.contains(&i)) { + return (pieces.first() == Some(&i)).then(|| line.clone()); + } let hints: Vec<_> = pairs.iter().filter(|h| h.0 == i).map(|h| (h.1, h.2)).collect(); - next.elements.get(i).and_then(|b| interpolate(a, b, t, morph, &hints, path)).map_or_else(|| a.clone(), Arc::new) + Some(next.elements.get(i).and_then(|b| interpolate(a, b, t, morph, &hints, path)).map_or_else(|| a.clone(), Arc::new)) }) .collect(); Some((kf.start, Cow::Owned(els))) } +/// The stroke of a raw line piece: what Merge Drawing makes of a drawing's lines, cut at every +/// corner, one element per piece (placed with a plain translation). +fn raw_line(e: &Element) -> Option<&Stroke> { + let [a, b, c, d, ..] = e.transform.m; + match &e.kind { + ElementKind::Shape(s) if s.merge && s.fill.is_none() && [a - 1.0, b, c, d - 1.0].iter().all(|v| v.abs() <= 1e-6) => s.stroke.as_ref(), + _ => None, + } +} + +/// The raw line pieces of `els`, by stroke style (and colour effect) in the order the styles +/// first appear: each style's element indices. +fn line_styles(els: &[Arc]) -> Vec> { + let mut styles: Vec<(&Stroke, crate::ColorEffect, Vec)> = Vec::new(); + for (i, e) in els.iter().enumerate() { + let Some(st) = raw_line(e) else { continue }; + match styles.iter_mut().find(|s| s.0 == st && s.1 == e.color) { + Some(s) => s.2.push(i), + None => styles.push((st, e.color, vec![i])), + } + } + styles.into_iter().map(|s| s.2).collect() +} + +/// A shape tween's raw lines (issue #119): on each keyframe the pieces of one style are joined +/// end to end into the outlines they make, and those morph as the fill does, so the line +/// follows the fill whatever its number of sides (paired piece by piece, sides went bare or +/// pieces were left standing). Styles pair in the order they first appear; each comes out as +/// one element, with the indices of the start keyframe's pieces it replaces. +fn tween_lines(kf: &crate::Keyframe, next: &crate::Keyframe, t: f32) -> Vec<(Vec, Arc)> { + let (sa, sb) = (line_styles(&kf.elements), line_styles(&next.elements)); + sa.into_iter().zip(sb).filter_map(|(ia, ib)| Some((ia.clone(), Arc::new(tween_line(&kf.elements, &ia, &next.elements, &ib, &kf.hints, t)?)))).collect() +} + +/// The pieces `ia` of `a` morphed `t` of the way to the pieces `ib` of `b`, as one line. +fn tween_line(a: &[Arc], ia: &[usize], b: &[Arc], ib: &[usize], hints: &[crate::ShapeHint], t: f32) -> Option { + use anicraft_geom::morph; + let outline = |els: &[Arc], idx: &[usize]| { + let pieces: Vec = idx + .iter() + .filter_map(|&i| match &els.get(i)?.kind { + ElementKind::Shape(s) => Some(s.path.transformed(&els.get(i)?.transform)), + _ => None, + }) + .collect(); + morph::chain(&pieces, anicraft_geom::planar::SNAP) + }; + let (first, other) = (a.get(*ia.first()?)?, b.get(*ib.first()?)?); + let (sa, sb) = (raw_line(first)?, raw_line(other)?); + let (pa, pb) = (outline(a, ia), outline(b, ib)); + // Hints placed on these lines on both keyframes steer them as they steer the fill they edge. + let on = |p: &Path, q| morph::nearest_point(p, q).is_some_and(|(_, d)| d <= crate::hints::HINT_TOLERANCE); + let hints: Vec<_> = hints.iter().take(crate::hints::MAX_SHAPE_HINTS).filter(|h| on(&pa, h.start) && on(&pb, h.end)).map(|h| (h.start, h.end)).collect(); + let path = morph::morph_hinted(&pa, &pb, &hints, t)?; + let c = path.bounds().center(); + if !c.is_finite() { + return None; + } + let shape = Shape { path: Arc::new(path.transformed(&Affine::translate(-c.x, -c.y))), fill: None, stroke: Some(sa.lerp(sb, t)), fill_rule: FillRule::default(), merge: true }; + Some(Element { id: first.id, name: first.name.clone(), transform: Affine::translate(c.x, c.y), color: first.color.lerp(&other.color, t), kind: ElementKind::Shape(shape) }) +} + /// Interpolates two elements; `None` when they cannot tween. With `morph` (a shape tween), /// shapes of different structure blend through [`anicraft_geom::morph`], steered by `hints` /// (shape hints in each element's own space, ADR 0023); otherwise a shape changes only when diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 96a3bf36..ad6fc34d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1598,6 +1598,68 @@ fn create_shape_tween_morphs_and_keeps_the_easing() { assert_eq!(s.active_layer().unwrap().keyframes[0].tween.unwrap().kind, anicraft_doc::TweenKind::Classic); } +/// The flattened outlines of `items` (stage space), as line segments. +fn outline_segments<'a>(items: impl Iterator) -> Vec<(Vec2, Vec2)> { + let mut segs = Vec::new(); + for it in items { + for pl in it.path.flatten(&it.transform, 0.05) { + segs.extend(pl.points.windows(2).map(|w| (w[0], w[1]))); + if let (true, Some(&a), Some(&b)) = (pl.closed, pl.points.last(), pl.points.first()) { + segs.push((a, b)); + } + } + } + segs +} + +/// How far `p` is from the nearest of `segs`. +fn distance_to(segs: &[(Vec2, Vec2)], p: Vec2) -> f32 { + segs.iter() + .map(|&(a, b)| { + let ab = b - a; + let t = if ab.dot(ab) > 0.0 { ((p - a).dot(ab) / ab.dot(ab)).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(a + ab * t) + }) + .fold(f32::INFINITY, f32::min) +} + +#[test] +fn shape_tweens_carry_the_stroke_round_shapes_with_more_or_fewer_sides() { + // Issue #119. A stroked triangle into a stroked hexagon and back (raw shapes: Merge Drawing + // makes one stroke piece per side, 3 and 6 of them). In between, the stroke must follow the + // whole morphing fill outline: no side left bare, no line left standing off it. + let mut s = Session::default(); + let polygon = |s: &mut Session, sides: u32| { + let inner = 60.0 * (std::f32::consts::PI / sides as f32).cos(); // on the edges: a polygon + run(s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 60, "inner": inner, "points": sides, "fill": "#ff0000", "stroke": "#000000", "stroke_width": 2, "object": false})); + }; + polygon(&mut s, 3); + let strokes = |s: &Session| s.active_layer().unwrap().keyframes.last().unwrap().elements.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_none())).count(); + assert_eq!(strokes(&s), 3, "one stroke piece per side"); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_blank_keyframe", json!({})); + polygon(&mut s, 6); + assert_eq!(strokes(&s), 6); + run(&mut s, "timeline.goto", json!({"frame": 20})); + run(&mut s, "timeline.insert_blank_keyframe", json!({})); + polygon(&mut s, 3); + for frame in [0, 10] { + run(&mut s, "timeline.create_shape_tween", json!({"frame": frame})); + } + for frame in [3, 5, 8, 13, 15, 18] { + let list = anicraft_doc::evaluate(&s.doc, frame); + let fill = outline_segments(list.items.iter().filter(|i| i.fill.is_some())); + let stroke = outline_segments(list.items.iter().filter(|i| i.stroke.is_some())); + assert!(!fill.is_empty() && !stroke.is_empty(), "frame {frame}"); + // Every point of the fill's outline has the stroke on it, and every point of the stroke + // lies on the outline. + let bare = fill.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&stroke, p)).fold(0.0, f32::max); + let stray = stroke.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&fill, p)).fold(0.0, f32::max); + assert!(bare < 0.5, "frame {frame}: part of the outline is {bare} from the stroke"); + assert!(stray < 0.5, "frame {frame}: a stroke is {stray} off the outline"); + } +} + #[test] fn scenes_play_in_order_edit_separately_and_survive_save_and_undo() { let mut s = Session::default(); diff --git a/crates/geom/src/morph.rs b/crates/geom/src/morph.rs index 1f95e61c..0b875d61 100644 --- a/crates/geom/src/morph.rs +++ b/crates/geom/src/morph.rs @@ -540,6 +540,49 @@ fn to_path(subs: &[Sub]) -> Path { p } +/// Most open subpaths [`chain`] joins (the search is quadratic); past it they stay as they are. +const MAX_CHAIN: usize = 1024; + +/// Joins the open subpaths of `paths` that meet end to end (within `tol`, turning one round +/// where needed) into longer ones, closing a chain that comes back to its start. Merge +/// Drawing cuts a shape's line at every corner; chained, the pieces are its outline again, so +/// a shape tween morphs them as it morphs the fill. Closed subpaths pass through as they are. +pub fn chain(paths: &[Path], tol: f32) -> Path { + let (mut out, mut open): (Vec, Vec) = paths.iter().flat_map(subpaths).partition(|s| s.closed); + if open.len() > MAX_CHAIN { + out.append(&mut open); + return to_path(&out); + } + let end = |s: &Sub| s.segs.last().map_or(s.start, |g| g[2]); + let near = |a: Vec2, b: Vec2| a.distance(b) <= tol; + open.reverse(); // taken from the back, so in drawing order + while let Some(mut cur) = open.pop() { + // A chain that has come back to its start is done (other pieces may meet it there). + while !near(end(&cur), cur.start) { + let e = end(&cur); + if let Some(i) = open.iter().rposition(|s| near(s.start, e) || near(end(s), e)) { + let s = open.remove(i); + cur.segs.extend(if near(s.start, e) { s.segs } else { reverse(&s).segs }); + } else if let Some(i) = open.iter().rposition(|s| near(end(s), cur.start) || near(s.start, cur.start)) { + let s = open.remove(i); + let mut s = if near(end(&s), cur.start) { s } else { reverse(&s) }; + s.segs.append(&mut cur.segs); + cur = s; + } else { + break; + } + } + if near(end(&cur), cur.start) { + if let Some(g) = cur.segs.last_mut() { + g[2] = cur.start; + } + cur.closed = true; + } + out.push(cur); + } + to_path(&out) +} + /// Most shape hints a morph honours (Animate's a to z). pub const MAX_HINTS: usize = 26; @@ -841,6 +884,33 @@ mod tests { assert!(close(anchors_of(&y)[k], Vec2::new(50.0, 80.0))); } + #[test] + fn chain_joins_pieces_that_meet_into_outlines() { + // A triangle's sides, out of order, one drawn backwards and one a hair off its corner, + // plus a stray line and a closed square: the sides become one closed outline. + let (p, q, r) = (Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(5.0, 8.0)); + let sides = [Path::line(q, r), Path::line(Vec2::new(0.05, 0.0), q), Path::line(p, r)]; + let stray = Path::line(Vec2::new(50.0, 50.0), Vec2::new(60.0, 50.0)); + let square = Path::rect(100.0, 0.0, 5.0, 5.0); + let mut all = sides.to_vec(); + all.extend([stray.clone(), square.clone()]); + let joined = chain(&all, 0.2); + let subs = subpaths(&joined); + assert_eq!(subs.len(), 3, "{subs:?}"); + let tri = subs.iter().find(|s| s.segs.len() == 3).unwrap(); + assert!(tri.closed); + let corners: Vec = anchors(tri).collect(); + for c in [q, r] { + assert!(corners.iter().any(|a| close(*a, c)), "{c:?} in {corners:?}"); + } + assert!(corners.iter().any(|a| a.distance(p) < 0.1)); + assert!(subs.iter().any(|s| !s.closed && s.segs.len() == 1), "the stray line stays open"); + assert!(subs.iter().any(|s| s.closed && s.segs.len() == 4), "the square passes through"); + // The joined triangle morphs like the filled one. + assert!(morph(&joined, &Path::ellipse(0.0, 0.0, 5.0, 5.0), 0.5).is_some()); + assert!(chain(&[], 0.2).cmds.is_empty()); + } + #[test] fn nearest_point_snaps_to_the_outline() { let sq = Path::rect(0.0, 0.0, 100.0, 100.0); From 6f701f5c775518a0d61de746daac773aac18bd92 Mon Sep 17 00:00:00 2001 From: Untoldent Date: Thu, 12 Nov 2026 15:26:09 -0500 Subject: [PATCH 039/570] fix(ui): Select default symbol name when converting to symbol --- src/convert_symbol.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/convert_symbol.rs b/src/convert_symbol.rs index 875826fa..41455569 100644 --- a/src/convert_symbol.rs +++ b/src/convert_symbol.rs @@ -7,6 +7,7 @@ use crate::app::App; use crate::theme::{FORM_LABEL_DOCK, Type, form_row, text}; use anicraft_engine::doc::{Document, FolderId, LibraryEntry, SymbolKind}; use egui::Key; +use egui::text::{CCursor, CCursorRange}; use serde_json::json; /// The dialog while it is open. @@ -75,6 +76,12 @@ pub fn window(app: &mut App, ctx: &egui::Context) { let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Symbol name")); if d.focus { r.request_focus(); + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { + let start = CCursor::new(0); + let end = CCursor::new(d.name.chars().count()); + state.cursor.set_char_range(Some(CCursorRange::two(start, end))); + state.store(ui.ctx(), r.id); + } d.focus = false; } if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { From 6927b9df81e0aad06467ab9103b92c6a7e829154 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:30:25 +0100 Subject: [PATCH 040/570] Combine ActionScript \u surrogate-pair escapes into one char Found while testing crates/actions/src/as3/lex.rs:181-204 (Lexer::string and Lexer::hex) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/actions/src/as3/lex.rs | 28 ++++++++++++++++++++++++++-- crates/actions/src/as3/tests.rs | 7 +++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/actions/src/as3/lex.rs b/crates/actions/src/as3/lex.rs index 2fc83245..bc3bf0ba 100644 --- a/crates/actions/src/as3/lex.rs +++ b/crates/actions/src/as3/lex.rs @@ -179,7 +179,10 @@ impl Lexer<'_> { Some('v') => s.push('\u{b}'), Some('0') if !self.peek().is_some_and(|c| c.is_ascii_digit()) => s.push('\0'), Some('x') => s.push(self.hex(2, here)?), - Some('u') => s.push(self.hex(4, here)?), + Some('u') => { + let unit = self.hex_value(4, here)?; + s.push(self.utf16(unit)); + } // A backslash before a line break continues the string on the next line. Some('\n' | '\u{2028}' | '\u{2029}') => {} Some('\r') => { @@ -195,13 +198,34 @@ impl Lexer<'_> { } fn hex(&mut self, n: usize, at: Pos) -> Result { + let v = self.hex_value(n, at)?; + char::from_u32(v).ok_or_else(|| Problem::at(at, "this escape isn't a character")) + } + + /// The char for a `\u` code unit; a high surrogate joins a following `\uDC00-DFFF` + /// escape, and a lone surrogate becomes U+FFFD. + fn utf16(&mut self, unit: u32) -> char { + if (0xD800..0xDC00).contains(&unit) { + let rest = &self.src.as_bytes()[self.at..]; + let low = rest.strip_prefix(b"\\u").and_then(|r| r.get(..4)).and_then(|h| h.iter().try_fold(0u32, |v, &b| Some(v * 16 + char::from(b).to_digit(16)?))); + if let Some(low) = low.filter(|l| (0xDC00..0xE000).contains(l)) { + for _ in 0..6 { + self.bump(); + } + return char::from_u32(0x10000 + ((unit - 0xD800) << 10) + (low - 0xDC00)).unwrap_or('\u{FFFD}'); + } + } + char::from_u32(unit).unwrap_or('\u{FFFD}') + } + + fn hex_value(&mut self, n: usize, at: Pos) -> Result { let mut v = 0u32; for _ in 0..n { let d = self.peek().and_then(|c| c.to_digit(16)).ok_or_else(|| Problem::at(at, "this escape needs hexadecimal digits"))?; v = v * 16 + d; self.bump(); } - char::from_u32(v).ok_or_else(|| Problem::at(at, "this escape isn't a character")) + Ok(v) } } diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index 2cc2e506..74201319 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -551,3 +551,10 @@ fn scripts_set_append_and_read_text_fields() { assert!(err("a_txt.appendText();").2.contains("one argument")); assert!(err("a_txt.length = 3;").2.contains("can only be read")); } + +#[test] +fn surrogate_pair_escapes() { + assert_eq!(lines(r#"trace("\uD83D\uDE00");"#), vec!["😀".to_string()]); + assert_eq!(lines(r#"trace("é\uD83D\uDE00");"#), vec!["é😀".to_string()]); + assert_eq!(lines(r#"trace("\uD83Dx\uDE00");"#), vec!["\u{FFFD}x\u{FFFD}".to_string()]); +} From 1f58af08e7a3261ef988ae2118de04f967a2d15f Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:51:19 +0100 Subject: [PATCH 041/570] Keep alpha in Rgba::to_hex so the hex round trip is lossless Found while testing crates/doc/src/lib.rs:77-81 (Rgba::to_hex) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/lib.rs | 13 ++++++++++++- crates/render/src/html.rs | 4 ++-- crates/render/src/lottie.rs | 2 +- crates/render/src/svg.rs | 3 ++- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b6cde82e..a74fd096 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -85,7 +85,11 @@ impl Rgba { pub fn to_hex(self) -> String { let s = self.sanitized(); let b = |v: f32| (v * 255.0).round() as u8; - format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b)) + if s.a < 1.0 { + format!("#{:02x}{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b), b(s.a)) + } else { + format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b)) + } } /// Parses `#rrggbb`, `rrggbb` or `#rrggbbaa`. pub fn parse_hex(s: &str) -> Option { @@ -1687,6 +1691,13 @@ mod tests { assert_eq!(LoopMode::Loop.local_frame(u32::MAX, u32::MAX, 0), 0); } + #[test] + fn hex_roundtrip_keeps_alpha() { + let c = Rgba::parse_hex("#ff000080").unwrap(); + assert_eq!(c.to_hex(), "#ff000080"); + assert_eq!(Rgba::parse_hex(&c.to_hex()).unwrap(), c); + } + #[test] fn hex_roundtrip() { let c = Rgba::parse_hex("#ff8000").unwrap(); diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 3b070ec9..01446842 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -863,7 +863,7 @@ pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie { let json = json!({ "v": FORMAT_VERSION, "generator": format!("AniCraft {}", env!("CARGO_PKG_VERSION")), - "stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.to_hex()}, + "stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.with_alpha(1.0).to_hex()}, "fit": opts.fit, "scenes": doc.scenes.iter().enumerate().map(|(i, s)| json!({"name": s.name, "tl": i})).collect::>(), "symbols": symbols, @@ -913,7 +913,7 @@ pub fn to_html(doc: &Document, opts: &HtmlOptions) -> Result // the JSON is inside a string, where `<` reads the same. let data = m.json.to_string().replace('<', "\\u003c"); let title = escape_html(&opts.title); - let bg = doc.stage.background.to_hex(); + let bg = doc.stage.background.with_alpha(1.0).to_hex(); let (w, h) = (doc.stage.width.max(1), doc.stage.height.max(1)); let mut html = String::with_capacity(data.len() + PLAYER_JS.len() + FILTERS_JS.len() + CANVAS_JS.len() + 1024); html.push_str("\n\n\n\n\n"); diff --git a/crates/render/src/lottie.rs b/crates/render/src/lottie.rs index 5f04704a..5b1b216d 100644 --- a/crates/render/src/lottie.rs +++ b/crates/render/src/lottie.rs @@ -531,7 +531,7 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo if background { let bg = doc.stage.background.sanitized(); layers.push(json!({"ddd": 0, "ind": shape_layers + mattes + 1, "ty": 1, "nm": "Stage", "sr": 1, "ks": static_ks(), "ao": 0, "ip": 0, "op": frames, "st": 0, "bm": 0, - "sc": bg.to_hex(), "sw": doc.stage.width, "sh": doc.stage.height})); + "sc": bg.with_alpha(1.0).to_hex(), "sw": doc.stage.width, "sh": doc.stage.height})); } let root = json!({ "v": "5.7.0", diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index f0f55234..02bb7b87 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -210,8 +210,9 @@ fn style_attrs(st: &anicraft_doc::Stroke, k: f32) -> String { out } +/// Opaque `#rrggbb`: SVG carries alpha in separate opacity attributes. fn hex(c: Rgba) -> String { - c.sanitized().to_hex() + c.sanitized().with_alpha(1.0).to_hex() } /// `fill="#rrggbb"` (or `stroke=…`), plus the opacity when not opaque. From 56d767f4d172ba77a00995f6b8997cbee9ef87d1 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 13 Nov 2026 04:49:59 +0000 Subject: [PATCH 042/570] fix: keep sanitized dash patterns idempotent and lerp stable Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/stroke_style.rs | 39 +++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/stroke_style.rs b/crates/doc/src/stroke_style.rs index a5909fcf..d76d7c6d 100644 --- a/crates/doc/src/stroke_style.rs +++ b/crates/doc/src/stroke_style.rs @@ -175,15 +175,22 @@ impl Dash { /// The pattern as stored, cleaned up (a file, a command): lengths finite and in range, an /// odd count repeated whole (so the dash/gap alternation holds where the pattern wraps), at - /// most [`MAX_DASH_ENTRIES`] read, the offset within one period. + /// most twice [`MAX_DASH_ENTRIES`] kept, the offset within one period. /// `None` when it draws solid (no gaps, or nothing at all to repeat). pub fn sanitized(self) -> Option { match self { Dash::Dashed { lengths, offset } => { - let mut v: Vec = lengths.iter().take(MAX_DASH_ENTRIES).map(|&x| length(x)).collect(); + // Up to twice the limit is read, so a whole repeated odd pattern (the stored form) + // survives sanitizing again (so lists of up to twice the limit are kept whole, + // even ones too); an odd list longer than the limit is cut to it. + let mut v: Vec = lengths.iter().take(2 * MAX_DASH_ENTRIES).map(|&x| length(x)).collect(); if v.len() % 2 == 1 { - let again = v.clone(); - v.extend(again); + if v.len() > MAX_DASH_ENTRIES { + v.truncate(MAX_DASH_ENTRIES); + } else { + let again = v.clone(); + v.extend(again); + } } let period: f32 = v.iter().sum(); let gaps: f32 = v.iter().skip(1).step_by(2).sum(); @@ -315,7 +322,7 @@ mod tests { let d = Dash::Dashed { lengths: vec![f32::NAN, -3.0, 1e30, 2.0].into(), offset: f32::INFINITY }.sanitized().unwrap(); assert_eq!(d, Dash::Dashed { lengths: vec![0.0, 0.0, MAX_DASH_LENGTH, 2.0].into(), offset: 0.0 }); let long = Dash::Dashed { lengths: vec![1.0; 99].into(), offset: 0.0 }.sanitized().unwrap(); - assert!(matches!(long, Dash::Dashed { lengths, .. } if lengths.len() == MAX_DASH_ENTRIES)); + assert!(matches!(long, Dash::Dashed { lengths, .. } if lengths.len() == 2 * MAX_DASH_ENTRIES)); assert_eq!(Dash::dotted(f32::NAN), Some(Dash::Dotted { spacing: 0.0 })); } @@ -329,6 +336,28 @@ mod tests { } } + #[test] + fn odd_dash_patterns_are_stable() { + for n in (9..=15).step_by(2) { + let base: Vec = (1..=n).map(|i| i as f32).collect(); + let d = Dash::Dashed { lengths: base.into(), offset: 3.0 }.sanitized().unwrap(); + assert_eq!(d.clone().sanitized().as_ref(), Some(&d), "n = {n}"); + for t in [0.0, 0.5, 1.0] { + assert_eq!(Dash::lerp(Some(&d), Some(&d), t).as_ref(), Some(&d), "n = {n}, t = {t}"); + } + } + } + + #[test] + fn lerp_of_identical_unsanitized_endpoints_is_sanitized() { + let raw = Dash::Dashed { lengths: vec![1.0, 1e30, 3.0].into(), offset: 0.0 }; + let want = raw.clone().sanitized(); + assert_eq!(want, Some(Dash::Dashed { lengths: vec![1.0, MAX_DASH_LENGTH, 3.0, 1.0, MAX_DASH_LENGTH, 3.0].into(), offset: 0.0 })); + for t in [0.0, 0.5, 1.0] { + assert_eq!(Dash::lerp(Some(&raw), Some(&raw), t), want, "t = {t}"); + } + } + #[test] fn dots_are_round_zero_length_dashes() { let st = StrokeStyle { cap: Cap::Butt, dash: Dash::dotted(3.0), ..StrokeStyle::default() }; From da342a3d11b8c4f9a002f28970865c9713d38d0e Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Fri, 13 Nov 2026 10:55:15 +0300 Subject: [PATCH 043/570] fix(text): wrap narrow lines between shaped clusters, never inside one break_lines walked every scalar, but advances sit only on a cluster's first byte, so a cluster wider than the line was split after its first scalar: a combining mark landed on the next line, away from its letter, and a ligature was reshaped in pieces. Advances are now None inside a cluster and lines break only where one starts; an overwide cluster stays whole on its own line. Regressions for a combining mark and a ligature at a narrow width. --- crates/text/src/lib.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6afcd84f..8adcb4a8 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -510,16 +510,17 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style, want_glyphs: bool run }) }; - // Each byte's share of the width (a cluster's advance on its first byte), run by run. Only wrapping - // reads it, so a block without a width skips this pass (it would shape every paragraph twice). - let mut advance = vec![0.0f32; para.len()]; + // Each cluster's advance on its first byte, run by run (`None` inside a cluster, where a + // line can't break). Only wrapping reads it, so a block without a width skips this pass + // (it would shape every paragraph twice). + let mut advance: Vec> = vec![None; para.len()]; let mut start = if style.width.is_some() { 0 } else { para.len() }; while start < para.len() { let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { if let Some(a) = advance.get_mut(g.cluster) { - *a += g.advance; + *a.get_or_insert(0.0) += g.advance; } } start = end; @@ -654,15 +655,16 @@ fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, lette .collect() } -/// A paragraph's lines as byte ranges in reading order, given each byte's share of the width: -/// wrapped after the last space before `width` is passed (or within a word wider than the line), -/// with the spaces at a line's end left out. -fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec> { +/// A paragraph's lines as byte ranges in reading order, given each cluster's advance on its first +/// byte (`None` inside a cluster): wrapped after the last space before `width` is passed (or +/// between the clusters of a word wider than the line, never inside one), with the spaces at a +/// line's end left out. +fn break_lines(para: &str, advance: &[Option], width: Option) -> Vec> { let trimmed = |start: usize, end: usize| start..para.get(start..end).map_or(start, |s| start + s.trim_end().len()); let mut lines = Vec::new(); let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::); for (i, c) in para.char_indices() { - let a = advance.get(i).copied().unwrap_or(0.0); + let Some(a) = advance.get(i).copied().flatten() else { continue }; let space = c.is_whitespace(); if let Some(w) = width && !space @@ -672,7 +674,7 @@ fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec Date: Fri, 13 Nov 2026 11:11:13 +0300 Subject: [PATCH 044/570] fix(text): a mark its letter's face lacks moves the whole cluster to a face with all of it (M5) Fallback looked only at the letter and the new mark, then moved the letter and every earlier mark to that face, so a mark the original face had could land in a face without it and draw as notdef while the missing count stayed zero. The face is now chosen for the whole cluster; when no face has all of it, the new mark comes from a face that has it and the rest stay where they were. Invisible joiners the face doesn't map no longer move the run to another face, which would break joining across a ZWJ. The face choice is a pure function, choose_faces, with regressions for complementary coverage. --- crates/text/src/lib.rs | 74 +++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 27 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2ca50820..1d07fffb 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -514,6 +514,40 @@ pub fn sanitize(style: &Style) -> Style { } } +/// The face drawing each byte of a paragraph, given how many faces there are and which has which +/// character: the chosen one (0) where it has the character, else the first fallback that does. +/// Spaces and marks stay with what comes before them, so a letter and its harakat are shaped +/// together; a mark its letter's face lacks takes the whole cluster (the letter and every mark +/// after it) to a face that has all of them, if there is one, and otherwise draws from a face +/// that has the mark, leaving the letter and the earlier marks where they were. +fn choose_faces(para: &str, faces: usize, has: impl Fn(usize, char) -> bool) -> Vec { + let mut face_of = vec![0usize; para.len()]; + let mut current = 0; + let mut base = 0; // the byte offset of the last letter + for (i, c) in para.char_indices() { + let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); + if !joins { + current = (0..faces).find(|f| has(*f, c)).unwrap_or(0); + base = i; + } else if needs_glyph(c) && !has(current, c) { + let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; + let cluster = para.get(base..i + c.len_utf8()).unwrap_or_default(); + if let Some(all) = (0..faces).find(|f| mark && cluster.chars().filter(|ch| needs_glyph(*ch)).all(|ch| has(*f, ch))) { + current = all; + if let Some(bytes) = face_of.get_mut(base..i) { + bytes.fill(all); + } + } else if let Some(f) = (0..faces).find(|f| has(*f, c)) { + current = f; + } + } + if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { + bytes.fill(current); + } + } + face_of +} + /// One shaped glyph: the face it comes from, its id, the byte it starts at in its paragraph, its /// offsets and advance (pixels). struct Glyph { @@ -568,33 +602,7 @@ fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style, want_glyphs: bool) let to_char = Arc::new(to_char); let lines_before = lines.len(); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); - // The face drawing each byte: the chosen one where it has the character, else the first - // fallback that does. Spaces and marks stay with what comes before them, so a letter and - // its harakat are shaped together; a mark its letter's face lacks takes the letter to a - // face that has both, if there is one. - let mut face_of = vec![0usize; para.len()]; - let mut current = 0; - let mut base = (0, '\0'); // the last letter: its byte offset and character - for (i, c) in para.char_indices() { - let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); - if !joins { - current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(0); - base = (i, c); - } else if !has(current, c) { - let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; - if let Some(both) = (0..fonts.len()).find(|f| mark && has(*f, base.1) && has(*f, c)) { - current = both; - if let Some(bytes) = face_of.get_mut(base.0..i) { - bytes.fill(both); - } - } else if let Some(f) = (0..fonts.len()).find(|f| has(*f, c)) { - current = f; - } - } - if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { - bytes.fill(current); - } - } + let face_of = choose_faces(para, fonts.len(), has); // A run shaped in one direction, split where the face changes; glyphs in visual order. let shape_run = |run: std::ops::Range, rtl: bool| { let mut parts: Vec> = Vec::new(); @@ -881,6 +889,18 @@ mod tests { assert!(boxed(Align::Right).min.x > 280.0); } + #[test] + fn a_mark_takes_its_whole_cluster_to_a_face_with_all_of_it() { + let covers = |sets: &'static [&'static str]| move |f: usize, c: char| sets.get(f).is_some_and(|s| s.contains(c)); + // Face 1 has the letter and the second mark but not the first; face 2 has all three. + assert_eq!(choose_faces("e\u{0301}\u{0323}", 3, covers(&["e\u{0301}", "e\u{0323}", "e\u{0301}\u{0323}"])), vec![2; 5]); + // No face has all three: the letter and its first mark stay together, and the second + // mark comes from a face that has it. + assert_eq!(choose_faces("q\u{0301}\u{0323}", 2, covers(&["q\u{0323}", "q\u{0301}"])), vec![1, 1, 1, 0, 0]); + // An invisible joiner the face doesn't map doesn't move the run to another face. + assert_eq!(choose_faces("ب\u{200D}ب", 2, covers(&["ب", "\u{200D}"])), vec![0; 7]); + } + #[test] fn mixed_directions_read_the_right_way_round() { // Lines are found in reading order: after the last space that fits, or within a word. From e4087e1c3ee50c1845ed084ec9dd4a556e4344b7 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:27:41 +0100 Subject: [PATCH 045/570] Morph a raw shape's stroke with its fill in shape tweens Fixes #119 Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/eval.rs | 126 +++++++++++++++++++++++++++++++ crates/doc/src/hints.rs | 10 +++ crates/engine/src/merge_tests.rs | 110 +++++++++++++++++++++++++++ crates/geom/src/morph.rs | 36 +++++++++ 4 files changed, 282 insertions(+) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index ffc68762..dd172fe4 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -271,6 +271,10 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) let t = Progress::of(tween, (frame - kf.start) as f32 / kf.duration.max(1) as f32); let morph = tween.kind == TweenKind::Shape; let path = guide.map(|g| (g, tween.orient)); + let runs = |els: &[Arc]| els.iter().filter(|e| raw_stroke(e).is_some()).count(); + if morph && runs(&kf.elements) != runs(&next.elements) { + return Some((kf.start, Cow::Owned(morph_raw_strokes(kf, next, t, path)))); + } let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() }; let els = kf .elements @@ -314,6 +318,128 @@ impl Progress { } } +/// A raw stroke run (merge drawing, ADR 0031): a raw shape's outline is stored as one element +/// per run of its stroke, apart from its fill. +fn raw_stroke(e: &Element) -> Option<&Stroke> { + match &e.kind { + ElementKind::Shape(s) if s.merge && s.fill.is_none() => s.stroke.as_ref(), + _ => None, + } +} + +/// Raw stroke runs joined into one outline: the indices of the runs (the first one's space is +/// the outline's) and the joined element. +struct Joined { + members: Vec, + el: Element, +} + +/// The raw stroke runs of `els` joined into one element per stroke style (and scale, rotation +/// and skew, which the stroke's width follows), each in the space of its first run. +fn joined_runs(els: &[Arc]) -> Vec { + let mut out: Vec = Vec::new(); + for (i, e) in els.iter().enumerate() { + let (Some(st), ElementKind::Shape(s)) = (raw_stroke(e), &e.kind) else { continue }; + let slot = out.iter_mut().find_map(|j| { + let ElementKind::Shape(js) = &mut j.el.kind else { return None }; + let into = j.el.transform.inverse()?.mul(&e.transform); + (j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st)).then_some((&mut j.members, js, into)) + }); + match slot { + Some((members, js, into)) => { + members.push(i); + Arc::make_mut(&mut js.path).cmds.extend(s.path.transformed(&into).cmds); + } + None => out.push(Joined { members: vec![i], el: (**e).clone() }), + } + } + for j in &mut out { + if let ElementKind::Shape(s) = &mut j.el.kind { + s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP)); + } + } + out +} + +/// The partner on `b` of each joined outline of `a`: one with the same stroke first, then the +/// rest in order. +fn pair_joined(a: &[Joined], b: &[Joined]) -> Vec> { + let mut taken = vec![false; b.len()]; + let mut out: Vec> = a + .iter() + .map(|x| { + let m = b.iter().zip(&taken).position(|(y, &used)| !used && raw_stroke(&y.el) == raw_stroke(&x.el))?; + if let Some(u) = taken.get_mut(m) { + *u = true; + } + Some(m) + }) + .collect(); + for slot in out.iter_mut().filter(|s| s.is_none()) { + *slot = taken.iter().position(|&used| !used); + if let Some(u) = slot.and_then(|m| taken.get_mut(m)) { + *u = true; + } + } + out +} + +/// `e` shrunk to the centre of its path: where an outline without a partner grows from or +/// shrinks to. +fn collapsed(e: &Element) -> Element { + let mut e = e.clone(); + if let ElementKind::Shape(s) = &mut e.kind { + let c = s.path.bounds().center(); + s.path = Arc::new(s.path.transformed(&Affine { m: [0.0, 0.0, 0.0, 0.0, c.x, c.y] })); + } + e +} + +/// A shape tween between keyframes whose raw shapes have different numbers of stroke runs: the +/// runs of each keyframe are joined into whole outlines that morph like the fills, in place of +/// pairing the runs one by one. An outline with no partner shrinks away or grows in. Hints +/// steer the outlines (and the other elements) they are placed on at both ends. Everything else +/// pairs in order, as in a plain shape tween. +fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, guide: Option<(&PathWalk, bool)>) -> Vec> { + let (a, b) = (&kf.elements, &next.elements); + let (runs_a, runs_b) = (joined_runs(a), joined_runs(b)); + let partner = pair_joined(&runs_a, &runs_b); + let placed = if kf.hints.is_empty() { Vec::new() } else { crate::hints::placed_hints(kf, next) }; + // The hints placed on what `on_a` and `on_b` pick, in the spaces of `x` and `y`. + let hints = + |on_a: &dyn Fn(usize) -> bool, on_b: &dyn Fn(usize) -> bool, x: &Element, y: &Element| -> Vec<(anicraft_geom::Vec2, anicraft_geom::Vec2)> { + let (Some(ia), Some(ib)) = (x.transform.inverse(), y.transform.inverse()) else { return Vec::new() }; + placed.iter().filter(|h| on_a(h.0) && on_b(h.1)).map(|h| (ia.apply(h.2), ib.apply(h.3))).collect() + }; + let mut rest_b = b.iter().enumerate().filter(|(_, e)| raw_stroke(e).is_none()); + let mut out = Vec::with_capacity(a.len()); + for (i, x) in a.iter().enumerate() { + if raw_stroke(x).is_none() { + let y = rest_b.next(); + out.push( + y.and_then(|(j, y)| interpolate(x, y, t, true, &hints(&|h| h == i, &|h| h == j, x, y), guide)).map_or_else(|| x.clone(), Arc::new), + ); + continue; + } + let Some((k, ra)) = runs_a.iter().enumerate().find(|(_, r)| r.members.first() == Some(&i)) else { continue }; + let el = match partner.get(k).copied().flatten().and_then(|m| runs_b.get(m)) { + Some(rb) => { + interpolate(&ra.el, &rb.el, t, true, &hints(&|h| ra.members.contains(&h), &|h| rb.members.contains(&h), &ra.el, &rb.el), guide) + } + // No partner on the end keyframe: it shrinks away. + None => interpolate(&ra.el, &collapsed(&ra.el), t, false, &[], guide), + }; + out.push(Arc::new(el.unwrap_or_else(|| ra.el.clone()))); + } + // Outlines only on the end keyframe grow in. + for (_, rb) in runs_b.iter().enumerate().filter(|(m, _)| !partner.contains(&Some(*m))) { + if let Some(el) = interpolate(&collapsed(&rb.el), &rb.el, t, false, &[], guide) { + out.push(Arc::new(el)); + } + } + out +} + /// Interpolates two elements; `None` when they cannot tween. With `morph` (a shape tween), /// shapes of different structure blend through [`anicraft_geom::morph`], steered by `hints` /// (shape hints in each element's own space, ADR 0023); otherwise a shape changes only when diff --git a/crates/doc/src/hints.rs b/crates/doc/src/hints.rs index f60a2ada..10a53db6 100644 --- a/crates/doc/src/hints.rs +++ b/crates/doc/src/hints.rs @@ -152,6 +152,16 @@ pub(crate) fn hint_pairs(kf: &Keyframe, next: &Keyframe) -> Vec<(usize, Vec2, Ve .collect() } +/// The hints of a shape tween from `kf` to `next` placed on an outline at both ends: the indices +/// of the elements they are placed on (start, end) and the points in layer space. +pub(crate) fn placed_hints(kf: &Keyframe, next: &Keyframe) -> Vec<(usize, usize, Vec2, Vec2)> { + kf.hints + .iter() + .take(MAX_SHAPE_HINTS) + .filter_map(|h| Some((placed_on(&kf.elements, h.start)?, placed_on(&next.elements, h.end)?, h.start, h.end))) + .collect() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/merge_tests.rs b/crates/engine/src/merge_tests.rs index b25aa588..ea682c11 100644 --- a/crates/engine/src/merge_tests.rs +++ b/crates/engine/src/merge_tests.rs @@ -141,3 +141,113 @@ fn dashed_raw_strokes_keep_their_style_when_cut() { let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap_or_default()).unwrap_or_default(); assert_eq!(back, s.doc); } + +/// A raw regular `n`-gon of radius 80 at the origin with `fill` and `stroke` (`null` for none). +fn polygon(s: &mut Session, n: u32, fill: &serde_json::Value, stroke: &serde_json::Value) { + let outer = 80.0f32; + let inner = outer * (std::f32::consts::PI / n as f32).cos(); + run(s, "draw.star", json!({"cx": 0, "cy": 0, "outer": outer, "inner": inner, "points": n, "fill": fill, "stroke": stroke})); +} + +/// A shape tween from polygon `a` on frame 0 to polygon `b` on frame 10 (sides, fill, stroke). +fn polygon_tween(a: (u32, serde_json::Value, serde_json::Value), b: (u32, serde_json::Value, serde_json::Value)) -> Session { + let mut s = blank(); + polygon(&mut s, a.0, &a.1, &a.2); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_blank_keyframe", json!({})); + polygon(&mut s, b.0, &b.1, &b.2); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_shape_tween", json!({})); + s +} + +/// The width of everything stroked at `frame`, and how many strokes there are. +fn stroked_width(s: &Session, frame: u32) -> (f32, usize) { + let list = anicraft_doc::evaluate(&s.doc, frame); + let strokes: Vec<_> = list.items.iter().filter(|i| i.stroke.is_some()).collect(); + let r = strokes.iter().fold(anicraft_geom::Rect::EMPTY, |r, i| r.union(&i.path.transformed(&i.transform).bounds())); + (if strokes.is_empty() { 0.0 } else { r.max.x - r.min.x }, strokes.len()) +} + +/// A stroke on only one keyframe of a shape tween shrinks away or grows in over the tween, in +/// place of standing still and vanishing at the end (#119). +#[test] +fn a_stroke_on_one_keyframe_only_shrinks_away_or_grows_in() { + let red = json!("#ff0000"); + // Stroked on the start only: it shrinks to nothing. + let s = polygon_tween((5, red.clone(), json!("#000000")), (3, red.clone(), json!(null))); + let (w0, _) = stroked_width(&s, 0); + let (w5, n5) = stroked_width(&s, 5); + let (w9, _) = stroked_width(&s, 9); + assert!(w0 > 100.0, "{w0}"); + assert!(n5 > 0 && (w5 - w0 * 0.5).abs() < w0 * 0.1, "halfway: {w5} of {w0}"); + assert!(w9 < w0 * 0.2, "near the end: {w9} of {w0}"); + assert_eq!(stroked_width(&s, 10).1, 0); + // Stroked on the end only: it grows from nothing. + let s = polygon_tween((3, red.clone(), json!(null)), (5, red, json!("#000000"))); + let (w10, _) = stroked_width(&s, 10); + let (w5, n5) = stroked_width(&s, 5); + assert!(w10 > 100.0, "{w10}"); + assert_eq!(stroked_width(&s, 0).1, 0); + assert!(n5 > 0 && (w5 - w10 * 0.5).abs() < w10 * 0.1, "halfway: {w5} of {w10}"); +} + +/// A shape hint placed on a raw outline's stroke steers the stroke's morph when the keyframes' +/// outlines have different numbers of runs (#119). +#[test] +fn a_hint_on_a_raw_stroke_steers_its_morph() { + let mut s = polygon_tween((3, json!(null), json!("#000000")), (5, json!(null), json!("#000000"))); + // The triangle's top corner goes to the pentagon's lower right corner. + let a = anicraft_geom::Vec2::new(0.0, -80.0); + let angle = (-90.0f32 + 144.0).to_radians(); + let b = anicraft_geom::Vec2::new(80.0 * angle.cos(), 80.0 * angle.sin()); + let half = a.lerp(b, 0.5); + let anchor_at = |s: &Session, q: anicraft_geom::Vec2| { + anicraft_doc::evaluate(&s.doc, 5).items.iter().filter(|i| i.stroke.is_some()).any(|i| { + i.path.cmds.iter().any(|c| match *c { + anicraft_geom::PathCmd::MoveTo(p) | anicraft_geom::PathCmd::LineTo(p) | anicraft_geom::PathCmd::CubicTo(_, _, p) => { + i.transform.apply(p).distance(q) < 0.5 + } + _ => false, + }) + }) + }; + assert!(!anchor_at(&s, half), "without a hint the corner goes elsewhere"); + run(&mut s, "tween.add_hint", json!({})); + run(&mut s, "tween.move_hint", json!({"hint": "a", "x": a.x, "y": a.y})); + run(&mut s, "tween.move_hint", json!({"hint": "a", "frame": 10, "x": b.x, "y": b.y})); + assert!(anchor_at(&s, half), "the corner travels to the hinted point"); +} + +/// A shape tween between raw polygons with different side counts morphs the outline's stroke +/// with its fill: the stroke covers the whole morphed edge, with no runs left behind (#119). +#[test] +fn a_shape_tween_morphs_the_stroke_with_the_fill() { + // The same stroke at both ends, and a stroke that changes colour. + for (from, to, end_stroke) in [(3u32, 5u32, "#000000"), (5, 3, "#000000"), (3, 5, "#0000ff"), (5, 3, "#0000ff")] { + let s = polygon_tween((from, json!("#ff0000"), json!("#000000")), (to, json!("#ff0000"), json!(end_stroke))); + for frame in [5u32, 9] { + let list = anicraft_doc::evaluate(&s.doc, frame); + let fills: Vec<_> = list.items.iter().filter(|i| i.fill.is_some()).collect(); + let strokes: Vec<_> = list.items.iter().filter(|i| i.stroke.is_some()).collect(); + assert_eq!(fills.len(), 1, "{from}->{to} frame {frame}"); + assert!(!strokes.is_empty(), "{from}->{to} frame {frame}"); + let fill = fills[0]; + // Every point of the fill's edge lies on some stroke, and every stroke on the fill's edge. + for pl in fill.path.flatten(&fill.transform, 0.25) { + for &p in &pl.points { + let d = strokes.iter().map(|st| st.path.distance_to_edge(p, &st.transform)).fold(f32::INFINITY, f32::min); + assert!(d < 1.5, "{from}->{to} frame {frame}: fill edge point {p:?} is {d} from any stroke"); + } + } + for st in &strokes { + for pl in st.path.flatten(&st.transform, 0.25) { + for &p in &pl.points { + let d = fill.path.distance_to_edge(p, &fill.transform); + assert!(d < 1.5, "{from}->{to} frame {frame}: stroke point {p:?} is {d} off the fill's edge"); + } + } + } + } + } +} diff --git a/crates/geom/src/morph.rs b/crates/geom/src/morph.rs index 1f95e61c..e68798e2 100644 --- a/crates/geom/src/morph.rs +++ b/crates/geom/src/morph.rs @@ -640,6 +640,42 @@ pub fn compatible_hinted(a: &Path, b: &Path, hints: &[(Vec2, Vec2)]) -> Option<( Some((to_path(&sa), to_path(&sb))) } +/// Joins open subpaths that meet end to end (within `tol`) into longer runs, reversing pieces +/// as needed, and closes the runs that come back to their start. The separate stroke runs of +/// a raw shape's outline then morph as one outline, the way its fill does. +pub fn chain(p: &Path, tol: f32) -> Path { + let (mut out, mut open): (Vec, Vec) = subpaths(p).into_iter().partition(|s| s.closed); + open.reverse(); // popped in drawing order + let end = |s: &Sub| s.segs.last().map_or(s.start, |g| g[2]); + while let Some(mut cur) = open.pop() { + loop { + let tail = end(&cur); + if let Some(j) = open.iter().rposition(|s| s.start.distance(tail) <= tol || end(s).distance(tail) <= tol) { + let next = open.remove(j); + let next = if next.start.distance(tail) <= tol { next } else { reverse(&next) }; + cur.segs.extend(next.segs); + continue; + } + if let Some(j) = open.iter().rposition(|s| end(s).distance(cur.start) <= tol || s.start.distance(cur.start) <= tol) { + let prev = open.remove(j); + let mut prev = if end(&prev).distance(cur.start) <= tol { prev } else { reverse(&prev) }; + prev.segs.extend(cur.segs); + cur = prev; + continue; + } + break; + } + if cur.segs.len() > 1 && end(&cur).distance(cur.start) <= tol { + if let Some(g) = cur.segs.last_mut() { + g[2] = cur.start; + } + cur.closed = true; + } + out.push(cur); + } + to_path(&out) +} + /// The shape `t` of the way from `a` to `b` (0 = `a`, 1 = `b`), for any two paths. /// /// Always goes through [`compatible`]: two paths with the same commands can still start at From 05705182584549f59a4712e480ca727a93195ed6 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:57:06 +0000 Subject: [PATCH 046/570] fix: keep colour effects apart when joining raw stroke runs; bound morph::chain with an endpoint grid Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/eval.rs | 8 +- crates/doc/src/eval_tests.rs | 30 ++++++++ crates/geom/src/morph.rs | 141 +++++++++++++++++++++++++++++++++-- 3 files changed, 168 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index dd172fe4..e5207ba6 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -335,7 +335,7 @@ struct Joined { } /// The raw stroke runs of `els` joined into one element per stroke style (and scale, rotation -/// and skew, which the stroke's width follows), each in the space of its first run. +/// and skew, which the stroke's width follows, and colour effect), each in the space of its first run. fn joined_runs(els: &[Arc]) -> Vec { let mut out: Vec = Vec::new(); for (i, e) in els.iter().enumerate() { @@ -343,7 +343,7 @@ fn joined_runs(els: &[Arc]) -> Vec { let slot = out.iter_mut().find_map(|j| { let ElementKind::Shape(js) = &mut j.el.kind else { return None }; let into = j.el.transform.inverse()?.mul(&e.transform); - (j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st)).then_some((&mut j.members, js, into)) + (j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st) && j.el.color == e.color).then_some((&mut j.members, js, into)) }); match slot { Some((members, js, into)) => { @@ -361,14 +361,14 @@ fn joined_runs(els: &[Arc]) -> Vec { out } -/// The partner on `b` of each joined outline of `a`: one with the same stroke first, then the +/// The partner on `b` of each joined outline of `a`: one with the same stroke and colour first, then the /// rest in order. fn pair_joined(a: &[Joined], b: &[Joined]) -> Vec> { let mut taken = vec![false; b.len()]; let mut out: Vec> = a .iter() .map(|x| { - let m = b.iter().zip(&taken).position(|(y, &used)| !used && raw_stroke(&y.el) == raw_stroke(&x.el))?; + let m = b.iter().zip(&taken).position(|(y, &used)| !used && raw_stroke(&y.el) == raw_stroke(&x.el) && y.el.color == x.el.color)?; if let Some(u) = taken.get_mut(m) { *u = true; } diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index 080ba5cc..eca9832f 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -580,3 +580,33 @@ fn instance_filters_tween_when_they_pair_up() { assert_eq!(crate::filter::lerp_filters(&[blur(1.0)], &[Filter::new("glow").unwrap()], 0.5), None); assert_eq!(crate::filter::lerp_filters(&[blur(1.0)], &[blur(1.0), blur(2.0)], 0.5), None); } + +/// Raw stroke runs with the same stroke but different colour effects are not joined, so the +/// run that the tween shrinks away keeps its own colour effect. +#[test] +fn raw_stroke_runs_with_different_colour_effects_keep_them_in_a_shape_tween() { + let v = anicraft_geom::Vec2::new; + let run = |id, y: f32, color| { + let mut p = Path::new(); + p.move_to(v(0.0, y)).line_to(v(50.0, y)); + let mut s = Shape::filled(p, Paint::Solid(Rgba::BLACK)).with_stroke(Rgba::BLACK, 2.0); + s.fill = None; + s.merge = true; + Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color, kind: ElementKind::Shape(s) }) + }; + let mut d = Document::default(); + let mut k0 = Keyframe::new(0, 10); + k0.elements = vec![run(1, 0.0, ColorEffect::None), run(2, 100.0, ColorEffect::Alpha(0.5))]; + k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() }); + let mut k1 = Keyframe::new(10, 1); + k1.elements = vec![run(1, 0.0, ColorEffect::None)]; + layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + let list = evaluate(&d, 1); + let strokes: Vec<_> = list.items.iter().filter(|i| i.stroke.is_some()).collect(); + assert_eq!(list.items.len(), 2); + assert_eq!(strokes.len(), 2); + // The run that the tween shrinks away (element 2) keeps its alpha; the first keeps none. + let by = |e: u64| strokes.iter().find(|i| i.element == ElementId(e)).unwrap(); + assert_eq!(by(2).color, ColorEffect::Alpha(0.5).transform(), "the later run lost its alpha"); + assert_eq!(by(1).color, ColorEffect::None.transform(), "the first run took the later run's colour"); +} diff --git a/crates/geom/src/morph.rs b/crates/geom/src/morph.rs index e68798e2..bb9f8d5e 100644 --- a/crates/geom/src/morph.rs +++ b/crates/geom/src/morph.rs @@ -18,6 +18,7 @@ //! is kept), as are hints whose subpaths are already paired another way. use crate::{Path, PathCmd, Vec2}; +use std::collections::HashMap; /// A cubic segment: control points and end point (the start is the previous end). type Seg = [Vec2; 3]; @@ -643,21 +644,88 @@ pub fn compatible_hinted(a: &Path, b: &Path, hints: &[(Vec2, Vec2)]) -> Option<( /// Joins open subpaths that meet end to end (within `tol`) into longer runs, reversing pieces /// as needed, and closes the runs that come back to their start. The separate stroke runs of /// a raw shape's outline then morph as one outline, the way its fill does. +/// +/// The work is bounded: each lookup visits at most [`CHAIN_SCAN`] runs per nearby grid cell, so +/// the cost grows linearly with the number of runs however they are spread. In a cell crowded +/// beyond that, a join may be missed (the runs stay separate, which is still a valid outline). pub fn chain(p: &Path, tol: f32) -> Path { + chain_counted(p, tol).0 +} + +/// Runs examined per grid cell by one [`chain`] lookup. +const CHAIN_SCAN: usize = 16; + +fn sub_end(s: &Sub) -> Vec2 { + s.segs.last().map_or(s.start, |g| g[2]) +} + +/// The last remaining run with an end within `tol` of `at`, scanning at most [`CHAIN_SCAN`] +/// entries per cell (taken runs at the back of a list are dropped as they are met). `steps` +/// counts the entries looked at. +fn chain_find(grid: &mut HashMap<(i64, i64), Vec>, slots: &[Option], at: Vec2, tol: f32, cell: f32, steps: &mut usize) -> Option { + let key = |v: Vec2| ((v.x / cell).floor() as i64, (v.y / cell).floor() as i64); + let (kx, ky) = key(at); + let mut best: Option = None; + for dx in -1..=1_i64 { + for dy in -1..=1_i64 { + let Some(list) = grid.get_mut(&(kx.saturating_add(dx), ky.saturating_add(dy))) else { continue }; + let mut seen = 0; + let mut k = list.len(); + while k > 0 && seen < CHAIN_SCAN { + k -= 1; + *steps += 1; + seen += 1; + let Some(&i) = list.get(k) else { break }; + let Some(s) = slots.get(i).and_then(Option::as_ref) else { + if k + 1 == list.len() { + list.pop(); + } + continue; + }; + if best.is_some_and(|b| b >= i) { + break; + } + if s.start.distance(at) <= tol || sub_end(s).distance(at) <= tol { + best = Some(i); + break; + } + } + } + } + best +} + +/// [`chain`], and the number of lookup steps it took. +fn chain_counted(p: &Path, tol: f32) -> (Path, usize) { let (mut out, mut open): (Vec, Vec) = subpaths(p).into_iter().partition(|s| s.closed); open.reverse(); // popped in drawing order - let end = |s: &Sub| s.segs.last().map_or(s.start, |g| g[2]); - while let Some(mut cur) = open.pop() { + let end = sub_end; + // Endpoints are looked up through a hashed grid of cell size `tol`. + let cell = if tol.is_finite() && tol > 0.0 { tol } else { 1.0 }; + let key = |v: Vec2| ((v.x / cell).floor() as i64, (v.y / cell).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, s) in open.iter().enumerate() { + let (a, b) = (key(s.start), key(end(s))); + grid.entry(a).or_default().push(i); + if b != a { + grid.entry(b).or_default().push(i); + } + } + let mut slots: Vec> = open.into_iter().map(Some).collect(); + let mut steps = 0; + while let Some(mut cur) = slots.iter_mut().rev().find_map(Option::take) { + while matches!(slots.last(), Some(None)) { + slots.pop(); + steps += 1; + } loop { let tail = end(&cur); - if let Some(j) = open.iter().rposition(|s| s.start.distance(tail) <= tol || end(s).distance(tail) <= tol) { - let next = open.remove(j); + if let Some(next) = chain_find(&mut grid, &slots, tail, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) { let next = if next.start.distance(tail) <= tol { next } else { reverse(&next) }; cur.segs.extend(next.segs); continue; } - if let Some(j) = open.iter().rposition(|s| end(s).distance(cur.start) <= tol || s.start.distance(cur.start) <= tol) { - let prev = open.remove(j); + if let Some(prev) = chain_find(&mut grid, &slots, cur.start, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) { let mut prev = if end(&prev).distance(cur.start) <= tol { prev } else { reverse(&prev) }; prev.segs.extend(cur.segs); cur = prev; @@ -673,7 +741,7 @@ pub fn chain(p: &Path, tol: f32) -> Path { } out.push(cur); } - to_path(&out) + (to_path(&out), steps) } /// The shape `t` of the way from `a` to `b` (0 = `a`, 1 = `b`), for any two paths. @@ -906,4 +974,63 @@ mod tests { assert!(r.is_none() || r.is_some_and(|p| p.cmds.iter().all(|c| !matches!(c, PathCmd::LineTo(_))))); assert!(t0.elapsed().as_secs_f32() < 2.0, "{:?}", t0.elapsed()); } + + #[test] + fn chaining_many_disconnected_runs_stays_cheap_and_correct() { + // Many separate open runs, with one chain of three pieces among them (the middle one + // drawn backwards): a scan per run would be quadratic. + let n = 100_000; + let mut p = Path::default(); + for i in 0..n { + let x = i as f32 * 10.0; + p.move_to(Vec2::new(x, 0.0)).line_to(Vec2::new(x + 1.0, 0.0)); + } + p.move_to(Vec2::new(0.0, 5.0)).line_to(Vec2::new(1.0, 5.0)); + p.move_to(Vec2::new(2.0, 5.0)).line_to(Vec2::new(1.0, 5.0)); + p.move_to(Vec2::new(2.0, 5.0)).line_to(Vec2::new(3.0, 5.0)); + let (c, steps) = chain_counted(&p, 0.01); + assert!(steps <= 100 * n, "{steps} steps"); + let subs = subpaths(&c); + assert_eq!(subs.len(), n + 1); + assert_eq!(subs.iter().filter(|s| s.segs.len() == 3).count(), 1); + assert!(subs.iter().all(|s| !s.closed)); + } + + #[test] + fn chaining_runs_crowded_into_one_cell_stays_bounded() { + // Every run starts and ends inside one cell of a large tolerance, and none touches + // another run's end exactly: lookups would each scan the whole cell. + let n = 20_000; + let mut p = Path::default(); + for i in 0..n { + let y = i as f32 * 1e-4; + p.move_to(Vec2::new(0.0, y)).line_to(Vec2::new(0.5, y)); + } + let (c, steps) = chain_counted(&p, 1000.0); + assert!(steps <= 200 * n, "{steps} steps"); + let subs = subpaths(&c); + // No segment is lost, whichever joins were made. + assert_eq!(subs.iter().map(|s| s.segs.len()).sum::(), n); + } + + #[test] + fn chaining_a_long_chain_does_not_rescan_taken_runs() { + // A long chain taken run by run, then many disconnected runs looked up after it: runs + // already taken must not be rescanned by every later lookup. + let n = 20_000; + let mut p = Path::default(); + for i in 0..n { + let x = i as f32; + p.move_to(Vec2::new(x, 0.0)).line_to(Vec2::new(x + 1.0, 0.0)); + } + for i in 0..n { + let y = 10.0 + i as f32 * 5.0; + p.move_to(Vec2::new(-100.0, y)).line_to(Vec2::new(-99.0, y)); + } + let (c, steps) = chain_counted(&p, 0.01); + assert!(steps <= 200 * n, "{steps} steps"); + let subs = subpaths(&c); + assert_eq!(subs.len(), n + 1); + assert_eq!(subs.iter().filter(|s| s.segs.len() == n).count(), 1); + } } From 06019106785ea8b167e548fd675433f8e056ca17 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:33:22 +0100 Subject: [PATCH 047/570] test(doc): cover frame limits in symbol timelines and at boundaries --- crates/doc/src/lib.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6dfa46a3..38820cf8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -751,8 +751,33 @@ mod tests { Arc::make_mut(&mut d.timeline.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.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.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.layers[0]).keyframes = keys.into_iter().map(Arc::new).collect(); + d.library.push(Arc::new(Symbol { + id: SymbolId(100), name: "boundary".into(), kind: SymbolKind::Graphic, timeline: d.timeline.clone(), + })); + d.sanitize(); + for timeline in [&d.timeline, &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); + } + } + } } From 4c94436ee0e9aeb66d77fde470c82abf62ba65bb Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 23:38:43 -0700 Subject: [PATCH 048/570] docs: reserve ADR 0096 for guide search and context help (M8) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..882d509d 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0096 | m8/guide-search-help | User guide search and context help | From 3ae20fe24f8b9a1d5dfca165e679ceb43cf4ad9c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 23:44:33 -0700 Subject: [PATCH 049/570] feat(guide): search in the bundled guide (prebuilt index, offline search page, same ranking in anicraft-cli guide search) (M8) --- Cargo.lock | 1 + crates/cli/src/lib.rs | 38 ++++- crates/guide/Cargo.toml | 3 + crates/guide/src/lib.rs | 126 +++++++++++++-- crates/guide/src/search.js | 254 +++++++++++++++++++++++++++++ crates/guide/src/search.rs | 318 +++++++++++++++++++++++++++++++++++++ crates/guide/src/style.css | 22 ++- crates/guide/src/tests.rs | 143 +++++++++++++++++ 8 files changed, 888 insertions(+), 17 deletions(-) create mode 100644 crates/guide/src/search.js create mode 100644 crates/guide/src/search.rs diff --git a/Cargo.lock b/Cargo.lock index 866d06a5..d77d16ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -342,6 +342,7 @@ name = "anicraft-guide" version = "0.2.1" dependencies = [ "pulldown-cmark", + "serde_json", ] [[package]] diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index d44b3c18..b5965591 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -33,6 +33,9 @@ USAGE: anicraft-cli exec [] [--save ] anicraft-cli new --out [--width W] [--height H] [--fps F] anicraft-cli guide --out writes the user guide as HTML pages (open index.html) + anicraft-cli guide search [--limit N] [--json yes] + searches the user guide: chapter, heading, page and a + passage for each result, best first (as its search page) anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release) anicraft-cli bench --check yes the default scenario against the budgets in docs/performance.md; fails when one is missed @@ -138,8 +141,26 @@ pub fn run(argv: &[String]) -> Result { serde_json::to_string_pretty(&list).map_err(|e| e.to_string()) } // The user guide as the static HTML book Help › User Guide opens (ADR 0069). + // Searching it, with the ranking the book's search page uses (ADR 0096). + "guide" if src == Some("search") => { + let words = a.positional.get(1..).unwrap_or_default().join(" "); + if anicraft_guide::search::terms(&words).is_empty() { + return Err("guide search needs words to look for, e.g. anicraft-cli guide search onion skin".into()); + } + let limit = a.num::("limit")?.unwrap_or(10).clamp(1, 100); + let hits = anicraft_guide::search::search(anicraft_guide::PAGES, &anicraft_guide::search::sections(anicraft_guide::PAGES), &words, limit); + if a.flag("json").is_some_and(|v| v == "yes") { + let list: Vec = hits.iter().map(|h| json!({"chapter": h.chapter, "heading": h.heading, "url": h.url, "snippet": h.snippet, "score": h.score})).collect(); + return serde_json::to_string_pretty(&list).map_err(|e| e.to_string()); + } + if hits.is_empty() { + return Ok(format!("nothing in the user guide matches “{}”", words.trim())); + } + let lines: Vec = hits.iter().enumerate().map(|(i, h)| format!("{}. {} · {}\n {}\n {}", i + 1, h.heading, h.chapter, h.url, h.snippet)).collect(); + Ok(lines.join("\n\n")) + } "guide" => { - let out = a.flag("out").ok_or("guide needs --out ")?; + let out = a.flag("out").ok_or("guide needs --out , or search ")?; let n = anicraft_guide::write_site(std::path::Path::new(out)).map_err(|e| format!("{out}: {e}"))?; Ok(format!("wrote {n} files of the user guide to {out}; open {out}/index.html")) } @@ -707,4 +728,19 @@ mod tests { assert!(run(&["commands".into()]).unwrap().contains("timeline.insert_keyframe")); assert!(run(&["guide".into()]).is_err()); } + + #[test] + fn guide_search_prints_chapter_heading_page_and_passage() { + let s = |v: &[&str]| run(&v.iter().map(|x| x.to_string()).collect::>()); + let out = s(&["guide", "search", "onion", "skin"]).unwrap(); + let first = out.lines().next().unwrap_or(""); + assert_eq!(first, "1. Onion skin · The timeline", "{out}"); + assert!(out.contains("timeline.html#onion-skin"), "{out}"); + let json: Value = serde_json::from_str(&s(&["guide", "search", "export", "gif", "--json", "yes", "--limit", "3"]).unwrap()).unwrap(); + let list = json.as_array().unwrap(); + assert!(list.len() <= 3 && list[0]["url"] == "getting-started.html#export-a-gif-or-a-video", "{json}"); + assert!(s(&["guide", "search", "zzzzqqq"]).unwrap().starts_with("nothing in the user guide matches")); + assert!(s(&["guide", "search"]).is_err() && s(&["guide", "search", "?!"]).is_err()); + assert!(s(&["guide", "search", "pen", "--limit", "x"]).is_err()); + } } diff --git a/crates/guide/Cargo.toml b/crates/guide/Cargo.toml index c7b99d53..4e69ed99 100644 --- a/crates/guide/Cargo.toml +++ b/crates/guide/Cargo.toml @@ -13,3 +13,6 @@ pulldown-cmark = { version = "0.13", default-features = false, features = ["html [lints] workspace = true + +[dev-dependencies] +serde_json.workspace = true diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs index f525299f..ee08deef 100644 --- a/crates/guide/src/lib.rs +++ b/crates/guide/src/lib.rs @@ -77,6 +77,7 @@ pub const IMAGES: &[(&str, &[u8])] = &[ ]; const STYLE: &str = include_str!("style.css"); +const SEARCH_JS: &str = include_str!("search.js"); const VERSION: &str = env!("CARGO_PKG_VERSION"); /// The stylesheet's path in the built book. pub const STYLESHEET: &str = "style.css"; @@ -211,38 +212,131 @@ fn root_prefix(file: &str) -> String { "../".repeat(file.matches('/').count()) } +/// What kind of page the chrome is around (the `data-page` the search script reads). +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Chapter, + Search, +} + +/// The book's chrome around `main`: the header with the search field, the chapter list (with +/// `current` marked) and the footer. `root` climbs from the page to the book's root. +fn chrome(pages: &[Page], root: &str, title: &str, current: Option, main: &str, kind: Kind) -> String { + let mut toc = String::new(); + for (i, p) in pages.iter().enumerate() { + let here = if Some(i) == current { " aria-current=\"page\"" } else { "" }; + toc.push_str(&format!("
  • {}
  • \n", html_path(p.file), escape(&self::title(p.markdown)))); + } + let (page, index, field) = match kind { + Kind::Chapter => ("chapter", String::new(), ""), + Kind::Search => ("search", format!("\n"), " aria-describedby=\"search-status\" aria-controls=\"results\""), + }; + format!( + "\n\n\n\n\n\ + {t} · AniCraft User Guide\n\n{index}\n\n\ + Skip to the chapter\n\ +
    AniCraft User Guide {VERSION}\ +
    \ +
    \n\ +
    \n\n\ +
    \n{main}
    \n
    \n\ +
    AniCraft {VERSION} · MIT OR Apache-2.0 · AniCraft is not affiliated with or endorsed by Adobe.
    \n\ + \n\n\n", + t = escape(title), + ) +} + /// A chapter as a complete HTML page, with the chapter list and previous / next links. pub fn render_page(pages: &[Page], at: usize) -> String { let Some(page) = pages.get(at) else { return String::new() }; let root = root_prefix(page.file); let mut body = String::new(); pulldown_cmark::html::push_html(&mut body, events(page.markdown).into_iter()); - let title = title(page.markdown); - let mut toc = String::new(); - for (i, p) in pages.iter().enumerate() { - let current = if i == at { " aria-current=\"page\"" } else { "" }; - toc.push_str(&format!("
  • {}
  • \n", html_path(p.file), escape(&self::title(p.markdown)))); - } let link = |p: Option<&Page>, rel: &str, word: &str| { p.map_or_else(String::new, |p| format!("{word}: {}", html_path(p.file), escape(&self::title(p.markdown)))) }; let prev = link(at.checked_sub(1).and_then(|i| pages.get(i)), "prev", "Previous"); let next = link(pages.get(at + 1), "next", "Next"); + let main = format!("{body}\n"); + chrome(pages, &root, &title(page.markdown), Some(at), &main, Kind::Chapter) +} + +/// The search page (ADR 0096): the field in its header searches as you type, and the results +/// are links with their chapter and a passage (`search.js`, over `search-index.js`). +pub fn render_search_page(pages: &[Page]) -> String { + let main = "

    Search

    \n\ +

    Type a word or two to search the guide.

    \n\ + \n\ +
      \n\ +

      Every word you type must match. ↓ and ↑ move through the results, Enter opens the first one, \ + Esc clears the search, and / brings you back to the search field from any page.

      \n"; + chrome(pages, "", "Search", None, main, Kind::Search) +} + +/// A page that sends the browser on to `target` (a page of the book with its anchor). Opening a +/// `file://` page at an anchor loses the anchor on some systems, so context help opens this. +pub fn redirect_page(target: &str) -> String { + let t = escape(target); format!( - "\n\n\n\n\n\ - {t} · AniCraft User Guide\n\n\n\n\ - Skip to the chapter\n\ -
      AniCraft User Guide {VERSION}
      \n\ -
      \n\n\ -
      \n{body}\n
      \n
      \n\ -
      AniCraft {VERSION} · MIT OR Apache-2.0 · AniCraft is not affiliated with or endorsed by Adobe.
      \n\n\n", - t = escape(&title), + "\n\n\n\n\n\ + AniCraft User Guide\n\n\n

      Open the AniCraft User Guide

      \n\n\n" ) } -/// The whole book: one HTML page per chapter, the stylesheet and the pictures. +/// The search page, its script and its index in the built book (ADR 0096). +pub const SEARCH_PAGE: &str = "search.html"; +pub const SEARCH_SCRIPT: &str = "search.js"; +pub const SEARCH_INDEX: &str = "search-index.js"; +/// The page context help writes beside the book and opens ([`redirect_page`]). +pub const HELP_PAGE: &str = "help.html"; + +/// A place in the book written as a chapter link (`timeline.md#onion-skin`) as the page to open +/// (`timeline.html#onion-skin`). +pub fn target_html(target: &str) -> String { + rewrite_link(target) +} + +/// The heading a chapter link names (`timeline.md#onion-skin` → "Onion skin"; a page alone, its +/// title), or `None` when it names nothing in the book. +pub fn heading_of(pages: &[Page], target: &str) -> Option { + let (file, anchor) = target.split_once('#').map_or((target, None), |(f, a)| (f, Some(a))); + let at = pages.iter().position(|p| p.file == file)?; + let page = pages.get(at)?; + match anchor { + None => Some(title(page.markdown)), + Some(a) => search::sections(std::slice::from_ref(page)).into_iter().find(|s| s.anchor == a).map(|s| s.heading), + } +} + +/// Every place in `targets` (chapter links: `file.md` or `file.md#anchor`) that isn't a page +/// and heading of the book. Context help's map is checked with this, as the chapters' own links +/// are checked by [`check`]. +pub fn check_targets(pages: &[Page], targets: &[&str]) -> Vec { + let scans: BTreeMap<&str, Scan> = pages.iter().map(|p| (p.file, scan(p.markdown))).collect(); + let mut problems = Vec::new(); + for t in targets { + let (file, anchor) = t.split_once('#').map_or((*t, None), |(f, a)| (f, Some(a))); + match scans.get(file) { + None => problems.push(format!("{t}: {file} is not a page of the book")), + Some(s) => { + if let Some(a) = anchor + && !s.anchors.contains(a) + { + problems.push(format!("{t}: {file} has no heading #{a}")); + } + } + } + } + problems +} + +/// The whole book: one HTML page per chapter, the search page with its script and index, the +/// stylesheet and the pictures. pub fn site() -> Vec { let mut out: Vec = (0..PAGES.len()).filter_map(|i| PAGES.get(i).map(|p| SiteFile { path: html_path(p.file), bytes: render_page(PAGES, i).into_bytes() })).collect(); + out.push(SiteFile { path: SEARCH_PAGE.to_string(), bytes: render_search_page(PAGES).into_bytes() }); + out.push(SiteFile { path: SEARCH_SCRIPT.to_string(), bytes: SEARCH_JS.as_bytes().to_vec() }); + out.push(SiteFile { path: SEARCH_INDEX.to_string(), bytes: search::index_js(PAGES).into_bytes() }); out.push(SiteFile { path: STYLESHEET.to_string(), bytes: STYLE.as_bytes().to_vec() }); out.extend(IMAGES.iter().map(|(path, bytes)| SiteFile { path: (*path).to_string(), bytes: bytes.to_vec() })); out @@ -385,5 +479,7 @@ pub fn check(pages: &[Page], images: &[&str]) -> Vec { problems } +pub mod search; + #[cfg(test)] mod tests; diff --git a/crates/guide/src/search.js b/crates/guide/src/search.js new file mode 100644 index 00000000..d685dec6 --- /dev/null +++ b/crates/guide/src/search.js @@ -0,0 +1,254 @@ +// AniCraft User Guide search (ADR 0096). Works offline from a file:// folder: the index is +// search-index.js, loaded with a script tag. The ranking is a port of crates/guide/src/search.rs +// (`anicraft-cli guide search` prints the same results); keep the two in step. Results are built +// with textContent only, never as markup. +(function () { + "use strict"; + var MAX_QUERY = 200, MAX_TERMS = 8, SNIPPET = 180, LEAD = 60; + var STOP_WORDS = ["a", "an", "and", "are", "as", "at", "be", "by", "can", "do", "does", "for", "from", "how", "i", "if", "in", "is", "it", "my", "of", "on", "or", "the", "to", "what", "when", "where", "with"]; + var WORD = /[\p{Alphabetic}\p{N}]/u; + + function words(s) { + var out = [], cur = "", start = 0, chars = Array.from(s); + for (var i = 0; i < chars.length; i++) { + var c = chars[i]; + if (WORD.test(c)) { + if (cur === "") start = i; + cur += c.toLowerCase(); + } else if (cur !== "") { + out.push([start, cur]); + cur = ""; + } + } + if (cur !== "") out.push([start, cur]); + return out; + } + + function terms(query) { + var all = []; + words(Array.from(query).slice(0, MAX_QUERY).join("")).forEach(function (w) { + if (all.indexOf(w[1]) < 0) all.push(w[1]); + }); + var kept = all.filter(function (w) { return STOP_WORDS.indexOf(w) < 0; }); + return (kept.length ? kept : all).slice(0, MAX_TERMS); + } + + function len(s) { return Array.from(s).length; } + + function matchClass(q, t) { + if (q === t) return 3; + var ql = len(q), tl = len(t); + if (ql >= 2 && t.indexOf(q) === 0) return 2; + if (tl >= 3 && ql <= tl + 2 && q.indexOf(t) === 0) return 1; + return 0; + } + + function best(q, ws) { + var b = 0; + for (var i = 0; i < ws.length; i++) b = Math.max(b, matchClass(q, ws[i][1])); + return b; + } + + function phrase(ws) { + return " " + ws.map(function (w) { return w[1]; }).join(" ") + " "; + } + + function score(p, ts) { + var total = 0; + for (var i = 0; i < ts.length; i++) { + var q = ts[i], body = 0; + for (var j = 0; j < p.body.length; j++) body += matchClass(q, p.body[j][1]); + var s = 30 * best(q, p.heading) + 8 * best(q, p.title) + Math.min(body, 15); + if (s === 0) return null; + total += s; + } + if (ts.length > 1) { + var wanted = " " + ts.join(" ") + " "; + if (phrase(p.heading).indexOf(wanted) >= 0) total += 60; + else if (phrase(p.body).indexOf(wanted) >= 0) total += 20; + } + return total; + } + + function snippet(text, ts) { + var chars = Array.from(text), ws = words(text), at = 0; + for (var i = 0; i < ws.length; i++) { + if (ts.some(function (q) { return matchClass(q, ws[i][1]) > 0; })) { at = ws[i][0]; break; } + } + var start = Math.max(0, at - LEAD); + if (start > 0) { + while (start < at && chars[start - 1] !== " ") start++; + } + var end = Math.min(start + SNIPPET, chars.length); + if (end < chars.length) { + var e = end; + while (e > start + SNIPPET / 2 && chars[e] !== undefined && chars[e] !== " ") e--; + end = e; + } + var body = chars.slice(start, end).join("").trim(); + return (start > 0 ? "…" : "") + body + (end < chars.length ? "…" : ""); + } + + // The words of every section, worked out once. + var prepared = null; + function prepare(index) { + if (prepared && prepared.index === index) return prepared.list; + var titles = index.pages.map(function (p) { return words(p.t); }); + var list = index.sections.map(function (s) { + return { s: s, heading: words(s.h), title: titles[s.p] || [], body: words(s.x) }; + }); + prepared = { index: index, list: list }; + return list; + } + + // The best `limit` sections for `query`, best first: {chapter, heading, url, snippet, score}. + function search(index, query, limit) { + var ts = terms(query); + if (!ts.length || limit <= 0) return []; + var scored = []; + prepare(index).forEach(function (p, i) { + var n = score(p, ts); + if (n !== null) scored.push({ n: n, i: i, p: p }); + }); + scored.sort(function (a, b) { return b.n - a.n || a.i - b.i; }); + return scored.slice(0, limit).map(function (r) { + var s = r.p.s, page = index.pages[s.p] || { f: "", t: "" }; + return { + chapter: page.t, + heading: s.h, + url: s.l === 1 || !s.a ? page.f : page.f + "#" + s.a, + snippet: snippet(s.x, ts), + score: r.n, + terms: ts + }; + }); + } + + if (typeof module !== "undefined" && module.exports) { + module.exports = { search: search, terms: terms, words: words }; + } + if (typeof document === "undefined") return; + + // ---- In the book ---- + var LIMIT = 30; + var root = document.documentElement.getAttribute("data-root") || ""; + + function isTyping(el) { + return el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable); + } + + // "/" anywhere in the book goes to the search field. + document.addEventListener("keydown", function (e) { + var q = document.getElementById("q"); + if (e.key === "/" && !e.ctrlKey && !e.metaKey && !e.altKey && q && !isTyping(document.activeElement)) { + e.preventDefault(); + q.focus(); + q.select(); + } + }); + + if (document.body.getAttribute("data-page") !== "search") return; + + var input = document.getElementById("q"); + var status = document.getElementById("search-status"); + var results = document.getElementById("results"); + var index = window.ANICRAFT_GUIDE_INDEX; + + // The snippet with the matching words marked. + function marked(text, ts) { + var frag = document.createDocumentFragment(), chars = Array.from(text), at = 0; + words(text).forEach(function (w) { + if (!ts.some(function (q) { return matchClass(q, w[1]) > 0; })) return; + var n = len(w[1]); + frag.appendChild(document.createTextNode(chars.slice(at, w[0]).join(""))); + var m = document.createElement("mark"); + m.textContent = chars.slice(w[0], w[0] + n).join(""); + frag.appendChild(m); + at = w[0] + n; + }); + frag.appendChild(document.createTextNode(chars.slice(at).join(""))); + return frag; + } + + function links() { + return Array.prototype.slice.call(results.querySelectorAll("a")); + } + + function run() { + var query = input.value; + while (results.firstChild) results.removeChild(results.firstChild); + if (!index) { + status.textContent = "The search index is missing. Use the chapter list instead."; + return; + } + if (!terms(query).length) { + status.textContent = "Type a word or two to search the guide."; + return; + } + var hits = search(index, query, LIMIT); + status.textContent = hits.length === 0 + ? "Nothing in the guide matches “" + query.trim() + "”." + : (hits.length === 1 ? "1 result" : hits.length + (hits.length === LIMIT ? "+ results" : " results")) + " for “" + query.trim() + "”."; + hits.forEach(function (h) { + var li = document.createElement("li"); + var a = document.createElement("a"); + a.href = root + h.url; + var head = document.createElement("span"); + head.className = "hit-heading"; + head.textContent = h.heading; + var chapter = document.createElement("span"); + chapter.className = "hit-chapter"; + chapter.textContent = h.chapter; + a.appendChild(head); + a.appendChild(chapter); + li.appendChild(a); + if (h.snippet) { + var p = document.createElement("p"); + p.className = "hit-snippet"; + p.appendChild(marked(h.snippet, h.terms)); + li.appendChild(p); + } + results.appendChild(li); + }); + try { + history.replaceState(null, "", "?q=" + encodeURIComponent(query)); + } catch (_) { + // Some browsers refuse to change a file:// address; the results stand all the same. + } + } + + input.addEventListener("input", run); + input.addEventListener("keydown", function (e) { + var first = links()[0]; + if (e.key === "ArrowDown" && first) { + e.preventDefault(); + first.focus(); + } else if (e.key === "Enter") { + e.preventDefault(); + if (first) first.click(); + } else if (e.key === "Escape") { + input.value = ""; + run(); + } + }); + results.addEventListener("keydown", function (e) { + var all = links(), i = all.indexOf(document.activeElement); + if (i < 0) return; + if (e.key === "ArrowDown" && i + 1 < all.length) { + e.preventDefault(); + all[i + 1].focus(); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + if (i === 0) input.focus(); + else all[i - 1].focus(); + } else if (e.key === "Escape") { + e.preventDefault(); + input.focus(); + } + }); + + var params = new URLSearchParams(location.search); + input.value = params.get("q") || ""; + run(); + input.focus(); +})(); diff --git a/crates/guide/src/search.rs b/crates/guide/src/search.rs new file mode 100644 index 00000000..01111a52 --- /dev/null +++ b/crates/guide/src/search.rs @@ -0,0 +1,318 @@ +//! Searching the book (ADR 0096). +//! +//! The book is split into sections, one per heading, each with its plain text. [`index_js`] +//! writes them into `search-index.js`, which the book's search page loads with a `"), "{} has no search field", f.path); + } + let nested = site.iter().find(|f| f.path == "reference/commands.html").expect("a nested page"); + assert!(String::from_utf8_lossy(&nested.bytes).contains("action=\"../search.html\"")); + let page = render_search_page(PAGES); + assert!(page.contains("src=\"search-index.js\"") && page.contains("role=\"status\"") && page.contains("aria-live")); + // The search script never builds markup from the index's text. + assert!(!SEARCH_JS.contains("innerHTML") && !SEARCH_JS.contains("insertAdjacentHTML") && !SEARCH_JS.contains("document.write")); + let js = search::index_js(PAGES); + assert!(js.len() < 512 * 1024, "the index is {} KB", js.len() / 1024); +} + +#[test] +fn context_help_targets_are_checked_and_named() { + assert!(check_targets(PAGES, &["timeline.md#onion-skin", "drawing.md", "reference/commands.md#file"]).is_empty()); + let problems = check_targets(PAGES, &["timeline.md#nope", "nowhere.md#x"]).join("\n"); + assert!(problems.contains("has no heading #nope") && problems.contains("nowhere.md is not a page"), "{problems}"); + assert_eq!(heading_of(PAGES, "timeline.md#onion-skin").as_deref(), Some("Onion skin")); + assert_eq!(heading_of(PAGES, "timeline.md").as_deref(), Some("The timeline")); + assert_eq!(heading_of(PAGES, "timeline.md#nope"), None); + assert_eq!(target_html("timeline.md#onion-skin"), "timeline.html#onion-skin"); + let r = redirect_page("timeline.html#a\"b"); + assert!(r.contains("url=timeline.html#a"b") && !r.contains("a\"b"), "{r}"); +} From 1538c8e2778f68decd1057f897d59fb143ce1eea Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 23:57:47 -0700 Subject: [PATCH 050/570] =?UTF-8?q?feat(app):=20context=20help=20on=20F1,?= =?UTF-8?q?=20Help=20=E2=80=BA=20Help=20for=20This=20and=20each=20panel=20?= =?UTF-8?q?menu,=20with=20a=20checked=20map=20to=20the=20guide;=20Using=20?= =?UTF-8?q?this=20guide=20chapter=20(M8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/guide/src/lib.rs | 1 + docs/guide/coming-from-animate.md | 4 +- docs/guide/drawing.md | 2 +- docs/guide/index.md | 9 +- .../preferences-shortcuts-accessibility.md | 5 +- docs/guide/reference/commands.md | 2 +- docs/guide/reference/shortcuts.md | 5 +- docs/guide/timeline.md | 2 +- docs/guide/troubleshooting-and-faq.md | 2 +- docs/guide/using-this-guide.md | 111 ++++ docs/guide/working-headless.md | 11 + docs/guide/workspace.md | 2 +- src/a11y.rs | 19 +- src/app.rs | 43 +- src/context_help.rs | 514 ++++++++++++++++++ src/dialogs.rs | 20 +- src/dock_ui.rs | 7 + src/guide_reference_tests.rs | 4 +- src/keymap.rs | 2 +- src/main.rs | 3 +- src/menus.rs | 10 +- src/panels.rs | 4 + src/platform.rs | 22 + 23 files changed, 781 insertions(+), 23 deletions(-) create mode 100644 docs/guide/using-this-guide.md create mode 100644 src/context_help.rs diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs index ee08deef..b37b51aa 100644 --- a/crates/guide/src/lib.rs +++ b/crates/guide/src/lib.rs @@ -58,6 +58,7 @@ pub const PAGES: &[Page] = &[ page!("preferences-shortcuts-accessibility.md"), page!("plugins.md"), page!("working-headless.md"), + page!("using-this-guide.md"), page!("troubleshooting-and-faq.md"), page!("coming-from-animate.md"), page!("reference/commands.md"), diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 0134c835..b9114cad 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -106,6 +106,8 @@ Asset Warp, the Paint Brush and Fluid Brush, Deco and the Spray Brush. More on t | Snap to objects | **Ctrl+Shift+/** | View › Snapping › Snap to Objects | | Zoom in and out | **Ctrl+=**, **Ctrl+-** | View | | Preferences (Windows and Linux) | **Ctrl+U** | Edit › Preferences… | +| Help | **F1** | Help › Help for This (the guide at the section for what you are pointing at) | +| Keyboard Shortcuts | **Ctrl+Alt+Shift+K** | Help › Keyboard Shortcuts | AniCraft also has **Home** and **End** (and **Shift+,** and **Shift+.**) for the first and last frame, and **Shift+PageUp** and **Shift+PageDown** for the previous and next scene. @@ -122,7 +124,7 @@ frame, and **Shift+PageUp** and **Shift+PageDown** for the previous and next sce * Panel toggles such as **Ctrl+L** for the Library have no key yet; use the **Window** menu. * **Ctrl+0** fits the stage in the window and **Ctrl+1** shows it at 100 %. -Any key can be changed in **Help › Keyboard Shortcuts** (**F1**), so you can bring back a habit +Any key can be changed in **Help › Keyboard Shortcuts** (**Ctrl+Alt+Shift+K**, as in Animate), so you can bring back a habit of your own. See [Preferences, shortcuts, accessibility and languages](preferences-shortcuts-accessibility.md) and the full list in [the shortcut reference](reference/shortcuts.md). diff --git a/docs/guide/drawing.md b/docs/guide/drawing.md index ee33bd5e..d53b15b0 100644 --- a/docs/guide/drawing.md +++ b/docs/guide/drawing.md @@ -40,7 +40,7 @@ your hand. While a drawing tool is in your hand, its options appear at the top of **Properties**: fill and stroke, line style, and the tool's own settings. You can change any of these keys in the -shortcut editor (**F1**). +shortcut editor (**Ctrl+Alt+Shift+K**). The Bone and Camera tools are covered in [Masks, guides, camera and bones](masks-guides-camera-bones.md), and the Text tool in diff --git a/docs/guide/index.md b/docs/guide/index.md index deebc197..6933792e 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -38,8 +38,9 @@ the panels, tools and shortcuts you know to AniCraft's, and lists what works dif ## Help -16. [Troubleshooting and FAQ](troubleshooting-and-faq.md). -17. [Coming from Animate](coming-from-animate.md). +16. [Using this guide](using-this-guide.md): searching it, and help for whatever you are working on (**F1**). +17. [Troubleshooting and FAQ](troubleshooting-and-faq.md). +18. [Coming from Animate](coming-from-animate.md). ## Reference @@ -52,7 +53,9 @@ have. On macOS, **Ctrl** in this guide means **⌘** (Command) and **Alt** means ## About this guide The guide comes with AniCraft: **Help › User Guide** opens it in your web browser, and it works -without an internet connection. You can also read it on +without an internet connection. Search it from the field at the top of every page, or press +**F1** in AniCraft to open it at the section for what you are working on; see +[Using this guide](using-this-guide.md). You can also read it on [GitHub](https://github.com/storytold/AniCraft). Found a mistake or something missing? Please [open an issue](https://github.com/storytold/AniCraft/issues). diff --git a/docs/guide/preferences-shortcuts-accessibility.md b/docs/guide/preferences-shortcuts-accessibility.md index 921753ca..7e06a99f 100644 --- a/docs/guide/preferences-shortcuts-accessibility.md +++ b/docs/guide/preferences-shortcuts-accessibility.md @@ -90,7 +90,7 @@ AniCraft starts**. Every menu command, every tool and the view keys (zoom, onion skin, panel focus and so on) can have shortcuts. The full list of defaults is in [the shortcut reference](reference/shortcuts.md). -Open the editor with **Help › Keyboard Shortcuts** (**F1**). Actions are grouped by menu, then +Open the editor with **Help › Keyboard Shortcuts** (**Ctrl+Alt+Shift+K**). Actions are grouped by menu, then **Tools**, **View** and **Other**. Type in **Filter by name or key…** to find an action by its name or by the key it uses: typing `F6` shows what F6 does. @@ -126,7 +126,8 @@ lists them as **fixed** and won't assign them to anything else: | Key | Kept for | |---|---| | **Ctrl+K**, **Ctrl+Shift+P** | the command palette | -| **F1**, **Ctrl+Alt+Shift+K** | the shortcut editor | +| **F1** | help for what you are pointing at (see [Using this guide](using-this-guide.md#help-for-what-youre-working-on)) | +| **Ctrl+Alt+Shift+K** | the shortcut editor | | **Ctrl+U**, **Ctrl+,** | Preferences | | **Ctrl+Q** | quitting | | **Enter** | play and stop | diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index c68a55f3..6f1ff76a 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -1,6 +1,6 @@ # Command reference -Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 352 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). +Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 352 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). This page is generated from the command registry, so it always matches the version of AniCraft it came with. diff --git a/docs/guide/reference/shortcuts.md b/docs/guide/reference/shortcuts.md index a5e006f1..a4b3bb65 100644 --- a/docs/guide/reference/shortcuts.md +++ b/docs/guide/reference/shortcuts.md @@ -1,6 +1,6 @@ # Shortcut reference -AniCraft's default keyboard shortcuts. On macOS, **Ctrl** is **⌘** (Command) and **Alt** is **⌥** (Option). To change a shortcut, open **Help › Keyboard Shortcuts** (**F1**): see [Preferences, shortcuts, accessibility and languages](../preferences-shortcuts-accessibility.md). The keys in the fixed rows can't be reassigned. Every command, with or without a key, is in the [command reference](commands.md). +AniCraft's default keyboard shortcuts. On macOS, **Ctrl** is **⌘** (Command) and **Alt** is **⌥** (Option). To change a shortcut, open **Help › Keyboard Shortcuts** (**Ctrl+Alt+Shift+K**): see [Preferences, shortcuts, accessibility and languages](../preferences-shortcuts-accessibility.md). The keys in the fixed rows can't be reassigned. Every command, with or without a key, is in the [command reference](commands.md). This page is generated from the editor's shortcut map, so it always matches the version of AniCraft it came with. @@ -9,7 +9,8 @@ This page is generated from the editor's shortcut map, so it always matches the | Action | Windows and Linux | macOS | |---|---|---| | Command palette | Ctrl+K | ⌘K | -| Keyboard shortcuts (this editor) | F1, Ctrl+Alt+Shift+K | F1, ⌥⇧⌘K | +| Help for what you are pointing at | F1 | F1 | +| Keyboard shortcuts (this editor) | Ctrl+Alt+Shift+K | ⌥⇧⌘K | | Play / Stop | Enter | ↩ | | Preferences | Ctrl+U, Ctrl+, | ⌘U, ⌘, | | Exit (Quit on macOS) | Ctrl+Q | ⌘Q | diff --git a/docs/guide/timeline.md b/docs/guide/timeline.md index a88e877a..a27ce791 100644 --- a/docs/guide/timeline.md +++ b/docs/guide/timeline.md @@ -6,7 +6,7 @@ onion skin and Edit Multiple Frames. A note on keys: AniCraft uses **Ctrl** on Windows and Linux and **⌘** (Command) on macOS, and **Alt** is **⌥** (Option) on macOS. So **Ctrl+Alt+C** is **⌥⌘C** on a Mac. Every shortcut -here is a default you can change in the shortcut editor (**F1**); see +here is a default you can change in the shortcut editor (**Ctrl+Alt+Shift+K**); see [Preferences, shortcuts and accessibility](preferences-shortcuts-accessibility.md). ## A tour of the timeline diff --git a/docs/guide/troubleshooting-and-faq.md b/docs/guide/troubleshooting-and-faq.md index fbab3bb5..ac7adf09 100644 --- a/docs/guide/troubleshooting-and-faq.md +++ b/docs/guide/troubleshooting-and-faq.md @@ -160,7 +160,7 @@ damaged preferences file never stops AniCraft from starting: it falls back to th where windows go. To keep the movie inside the editor, turn off **Preferences › Test Movie › Play Test Movie in a window of its own**. * **A shortcut doesn't do anything.** Check what the key is bound to in **Help › Keyboard - Shortcuts** (**F1**): type the key in the filter. See + Shortcuts** (**Ctrl+Alt+Shift+K**): type the key in the filter. See [Preferences, shortcuts, accessibility and languages](preferences-shortcuts-accessibility.md). ## The web version diff --git a/docs/guide/using-this-guide.md b/docs/guide/using-this-guide.md new file mode 100644 index 00000000..0c30c221 --- /dev/null +++ b/docs/guide/using-this-guide.md @@ -0,0 +1,111 @@ +# Using this guide + +This guide comes with AniCraft and matches the version you have. It opens in your web browser and +works without an internet connection. This chapter shows how to find things in it quickly: by +searching, and by asking AniCraft for help on whatever you are working on. + +On macOS, read **⌘** wherever this chapter says **Ctrl**. + +## Opening the guide + +* **Help › User Guide** opens the contents page. +* **Help › Help for This** (**F1**) opens it at the section for what you are working on (see + [below](#help-for-what-youre-working-on)). +* **Help › Search the User Guide** opens the search page, ready for you to type. + +All three are also in the command palette (**Ctrl+K**). + +## Searching the guide + +Every page has a **Search** field at the top. Type a word or two and press **Enter**; the search +page lists the sections that match, best first. On the search page itself the results update as +you type. + +Each result shows the section's heading, the chapter it is in and a short passage with your words +highlighted. Click a result to go straight to that section. + +* **Every word must match.** `onion skin` finds the sections about onion skinning; `onion gif` + finds only the ones that mention both. +* **Words match their longer forms.** `tween` finds "tweens" and "tweening", and `masks` finds + "mask". +* **Headings count most.** A section whose heading has your words comes before one that only + mentions them. +* Small words such as "how", "do", "the" and "a" are skipped, so you can type a question: + `how do I add a camera`. + +### With the keyboard + +| Key | What it does | +|---|---| +| **/** | Goes to the search field from anywhere in the guide. | +| **↓** and **↑** | Move from the field through the results, and back. | +| **Enter** | Opens the first result (or the result you are on). | +| **Esc** | Clears the search; in the results, goes back to the field. | + +Screen readers announce how many results there are as you type. + +## Help for what you're working on + +Press **F1** in AniCraft and the guide opens at the section for what you are working on. AniCraft +decides what that is in this order: + +| What | Opens | +|---|---| +| A dialog that is waiting for an answer, such as Convert to Symbol or a question before a command | That dialog, or the command it is asking about. | +| The command palette | The command or tool you have chosen in it. | +| The window or panel under the pointer | That window or panel: for example **Publish Settings**, the **Library** or the **Timeline**. | +| A tool's button under the pointer, or with keyboard focus | That tool. | +| The stage | The tool in your hand. Press **F1** with the Bone tool and the guide opens at building an armature. | +| The panel with keyboard focus (**Ctrl+F6** moves between them) | That panel. | +| Anything else | The window in front, or else the tool in your hand. | + +**F1** works even while you are typing in a field or a dialog is open. The status bar names the +section that opened. + +**Help › Help for This** does the same from the menu. Because the pointer is on the menu then, it +goes by the window in front, the focused panel or the tool in your hand. + +### From a panel's menu + +Every panel's menu (the **☰** button at the end of its tab row, or a right-click on its tab) has +**? Help for** the panel at its end: **? Help for Library**, **? Help for Swatches**, and so on. + +### In the command palette + +In the command palette (**Ctrl+K**), choose a command with the arrow keys and press **F1** to +read about it before you run it. The palette stays open. + +**F1** used to open the keyboard shortcut editor. That is now **Ctrl+Alt+Shift+K**, as in +Animate, or **Help › Keyboard Shortcuts**. See +[Preferences, shortcuts, accessibility and languages](preferences-shortcuts-accessibility.md#keyboard-shortcuts). + +## Searching from the command line + +`anicraft-cli guide search` searches the same guide from a terminal and prints the same results, +in the same order, as the search page: + +```sh +anicraft-cli guide search onion skin +anicraft-cli guide search export gif --limit 3 --json yes +``` + +See [Working headless](working-headless.md#this-guide-as-a-web-page). + +## Printing the guide + +Use your browser's **Print** to print a chapter, or to save it as a PDF (choose **Save as PDF** +as the printer). The chapter list, the search field and the previous and next links are left out +of the printout. + +## In the web version + +In AniCraft in a web browser, the guide is served next to the editor and opens in a new tab. +Search and **Help › Help for This** work there too. **F1** does as well, but some browsers also +open their own help page when you press it; use the menu item if yours does. + +## Not there yet + +* The guide in other languages. The interface can be translated already; the guide is English + for now. +* A PDF edition of the whole guide in one file. For now, print each chapter from your browser. +* Help for a single field or menu item. **F1** goes by the window, panel or tool. diff --git a/docs/guide/working-headless.md b/docs/guide/working-headless.md index 3f6ce06f..01e6f1e5 100644 --- a/docs/guide/working-headless.md +++ b/docs/guide/working-headless.md @@ -274,6 +274,17 @@ pictures, so you can read it offline or host it next to your studio's own docume anicraft-cli guide --out docs/anicraft-guide ``` +`anicraft-cli guide search ` searches it from the terminal, with the same results, in the +same order, as the search field in the guide's pages: + +```sh +anicraft-cli guide search onion skin +anicraft-cli guide search export gif --limit 3 --json yes +``` + +Each result gives the section's heading, its chapter, the page to open and a passage around the +first match. See [Using this guide](using-this-guide.md). + ## Performance check `anicraft-cli bench` builds a large generated document and times editing, undo, rendering, diff --git a/docs/guide/workspace.md b/docs/guide/workspace.md index dca9e266..1d198315 100644 --- a/docs/guide/workspace.md +++ b/docs/guide/workspace.md @@ -144,7 +144,7 @@ and **Enter** to run it. Installed plug-ins show up here too. It's the fastest way to reach anything when you don't remember which menu it lives in. -For a list of every shortcut, choose **Help › Keyboard Shortcuts** (**F1**). That sheet also +For a list of every shortcut, choose **Help › Keyboard Shortcuts** (**Ctrl+Alt+Shift+K**). That sheet also lets you change them (see [Preferences, shortcuts and accessibility](preferences-shortcuts-accessibility.md)). ## Moving around the stage diff --git a/src/a11y.rs b/src/a11y.rs index 52c4c465..64ed1a85 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -214,6 +214,8 @@ struct Anchor { /// The pass that drew it: a panel that stopped drawing (the timeline while the Motion /// Editor shows) has no anchor. pass: u64, + /// The layer it is drawn on: a docked panel under a floating window isn't the one pointed at. + layer: egui::LayerId, } /// Registers `resp` as the anchor of `region`, which covers `area` on screen. While a surface's @@ -221,7 +223,7 @@ struct Anchor { /// of moving focus to the neighbouring widget. pub fn anchor(ui: &egui::Ui, region: Region, area: Rect, resp: &Response) { let pass = ui.ctx().cumulative_pass_nr(); - ui.ctx().data_mut(|d| d.insert_temp(region.key(), Anchor { id: resp.id, rect: area, pass })); + ui.ctx().data_mut(|d| d.insert_temp(region.key(), Anchor { id: resp.id, rect: area, pass, layer: ui.layer_id() })); if region.is_surface() && resp.has_focus() { let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }; ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, filter)); @@ -234,6 +236,21 @@ fn anchor_of(ctx: &egui::Context, region: Region) -> Option { ctx.data(|d| d.get_temp::(region.key())).filter(|a| a.pass + 1 >= now) } +/// The panel under the pointer at `pos`, if any (context help, ADR 0096): the one drawn on the +/// topmost layer there. +pub fn region_at(ctx: &egui::Context, pos: egui::Pos2) -> Option { + let top = ctx.layer_id_at(pos); + let order = order(ctx); + let hits: Vec<(Region, Anchor)> = order.into_iter().filter_map(|r| anchor_of(ctx, r).map(|a| (r, a))).filter(|(_, a)| a.rect.contains(pos)).collect(); + hits.iter().find(|(_, a)| Some(a.layer) == top).or(hits.first()).map(|(r, _)| *r) +} + +/// Where a panel was drawn this pass or the one before. +#[cfg(test)] +pub fn region_rect(ctx: &egui::Context, region: Region) -> Option { + anchor_of(ctx, region).map(|a| a.rect) +} + /// The panel holding the focused widget, if any. pub fn focused_region(ctx: &egui::Context) -> Option { let id = ctx.memory(|m| m.focused())?; diff --git a/src/app.rs b/src/app.rs index 897d36b9..b60f8d86 100644 --- a/src/app.rs +++ b/src/app.rs @@ -492,6 +492,10 @@ pub struct App { /// Undoable-tier confirmations the user chose not to see again this session. pub skip_confirm: HashSet, pub palette: Option, + /// What a widget under the pointer or keyboard offers F1 this pass (ADR 0096). + pub help_offered: Option, + /// The guide place context help last opened (`timeline.md#onion-skin`). + pub help_opened: Option, /// The open plug-in dialog (its preview is an open gesture). pub plugin_dialog: Option, /// File › Export with an exporter plug-in: its window, and the export while it runs (ADR 0088). @@ -749,6 +753,8 @@ impl App { confirm: None, skip_confirm: HashSet::new(), palette: None, + help_offered: None, + help_opened: None, plugin_dialog: None, plugin_export: None, show_plugins: false, @@ -956,6 +962,28 @@ impl App { } } + /// Context help (ADR 0096): the guide at `target`, a chapter link from the context map + /// (`timeline.md#onion-skin`), naming the section in the status bar. + pub fn open_help(&mut self, target: &str) { + self.help_opened = Some(target.to_string()); + // A screenshot run shows what F1 did without starting a browser. + let opened = if self.shot.is_some() { Ok(()) } else { platform::open_user_guide_at(&crate::context_help::page_of(target)) }; + match (opened, crate::context_help::heading_of(target)) { + // The guide is English for now (ADR 0069): the section's name is as it is written. + (Ok(()), Some(heading)) => self.status_ok(tr!("Opened the user guide at “{section}”", section = heading)), + (Ok(()), None) => self.status_ok(tr!("Opened the user guide in your browser")), + (Err(e), _) => self.status_err(e), + } + } + + /// Help › Search the User Guide: the guide's search page, ready to type in. + pub fn open_guide_search(&mut self) { + match platform::open_user_guide_at(crate::context_help::SEARCH_PAGE) { + Ok(()) => self.status_ok(tr!("Opened the user guide's search in your browser")), + Err(e) => self.status_err(e), + } + } + pub fn open_prefs(&mut self) { self.show_prefs = true; self.scan_system_fonts(); @@ -1128,7 +1156,12 @@ impl App { crate::plugin_export_ui::open(self, &id); } } - Some("palette") => self.palette = Some(dialogs::Palette { query: "key".into(), selected: 0 }), + // F1 with the Bone tool in hand (ADR 0096): the status bar names the guide's section. + Some("helpbone") => { + self.tool = Tool::Bone; + self.script_keys([(K::F1, M::NONE)]); + } + Some("palette") => self.palette = Some(dialogs::Palette { query: "key".into(), ..Default::default() }), Some("shortcuts") => self.show_shortcuts = true, Some("lastscene") => { let last = self.s.doc.scenes.len().saturating_sub(1); @@ -3171,6 +3204,12 @@ impl App { } fn handle_shortcuts(&mut self, ctx: &egui::Context) { + // F1: help for what the person is working with (ADR 0096), from anywhere, a dialog that + // holds the editor and a text field included; only the shortcut editor's recording + // takes it. + if self.key_capture.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::F1)) { + crate::context_help::help_for_this(self, ctx, true); + } // While the shortcut editor records a key, every key press belongs to it. if self.modal_open() || self.key_capture.is_some() { return; @@ -3186,7 +3225,7 @@ impl App { let (palette, sheet, prefs_key, quit) = ctx.input_mut(|i| { // The shortcut sheet first: Ctrl+Alt+Shift+K (Animate's Keyboard Shortcuts) must not // be taken by Ctrl+K, which egui would match with the extra modifiers ignored. - let sheet = i.consume_key(Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT, Key::K) || i.consume_key(Modifiers::NONE, Key::F1); + let sheet = i.consume_key(Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT, Key::K); ( i.consume_key(Modifiers::COMMAND, Key::K) || i.consume_key(Modifiers::COMMAND | Modifiers::SHIFT, Key::P), sheet, diff --git a/src/context_help.rs b/src/context_help.rs new file mode 100644 index 00000000..c96562cc --- /dev/null +++ b/src/context_help.rs @@ -0,0 +1,514 @@ +//! Context help (ADR 0096): F1, or Help › Help for This, opens the user guide at the section +//! for whatever the person is working with: the dialog in front, the tool or panel under the +//! pointer, the panel that has the keyboard, else the tool in hand. Each panel's ☰ menu has +//! Help for its own section, and F1 in the command palette opens the chosen command's. +//! +//! The map from tools, panels, dialogs and command namespaces to the guide is here, written as +//! chapter links (`timeline.md#onion-skin`) so the guide's own link check proves every one of +//! them names a heading that exists (`anicraft_guide::check_targets`); tests also require one +//! for every tool, panel, dialog and command namespace, so a new one can't ship without help. + +use crate::app::{App, Tool}; +use crate::dock::Panel; + +/// The guide's place for a tool. +pub fn tool_topic(t: Tool) -> &'static str { + match t { + Tool::Select => "drawing.md#the-tools", + Tool::Subselect => "drawing.md#editing-points-with-subselection", + Tool::Transform => "drawing.md#transforming-artwork", + Tool::Warp => "masks-guides-camera-bones.md#asset-warp", + Tool::GradientTransform => "drawing.md#gradients-and-bitmap-fills", + Tool::Width => "drawing.md#variable-width-lines", + Tool::Bone => "masks-guides-camera-bones.md#building-an-armature", + Tool::Bind => "masks-guides-camera-bones.md#bones-inside-a-shape", + Tool::Pen => "drawing.md#the-pen", + Tool::Text => "text.md#typing-text", + Tool::Pencil | Tool::Rect | Tool::Oval | Tool::Star | Tool::Line => "drawing.md#drawing-shapes-and-lines", + Tool::Brush | Tool::PaintBrush => "drawing.md#the-brush", + Tool::Eraser => "drawing.md#eraser", + Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper => "drawing.md#paint-bucket-ink-bottle-and-eyedropper", + Tool::Camera => "masks-guides-camera-bones.md#moving-the-camera", + Tool::Hand => "workspace.md#panning", + Tool::Zoom => "workspace.md#zooming", + } +} + +/// The guide's place for a panel. +pub fn panel_topic(p: Panel) -> &'static str { + match p { + Panel::Properties => "workspace.md#properties", + Panel::Align => "drawing.md#align-and-distribute", + Panel::Colour => "drawing.md#choosing-colours", + Panel::Library => "symbols-and-library.md#the-library-panel", + Panel::MovieExplorer => "workspace.md#the-movie-explorer", + Panel::History => "workspace.md#undo-and-history", + Panel::LayerDepth => "masks-guides-camera-bones.md#layer-depth", + Panel::Timeline => "timeline.md#a-tour-of-the-timeline", + Panel::MotionEditor => "tweens.md#the-motion-editor", + Panel::Actions => "interactivity.md#the-actions-panel", + Panel::Output => "workspace.md#colour-and-output", + Panel::Swatches => "drawing.md#swatches", + Panel::Tools => "drawing.md#the-tools", + } +} + +/// A window or dialog with a place in the guide. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Dialog { + Preferences, + Shortcuts, + Licenses, + About, + ProjectFiles, + PublishSettings, + PublishProgress, + FindReplace, + BrushLibrary, + ConvertSymbol, + LayerProperties, + EditGrid, + EditGuides, + Plugins, + PluginSettings, + PluginExport, + SaveTemplate, + TestMovie, + EaseEditor, + SoundEnvelope, + Recover, + Updates, + ManageWorkspaces, + Palette, + CloseUnsaved, +} + +impl Dialog { + pub const ALL: [Dialog; 25] = [ + Dialog::Preferences, + Dialog::Shortcuts, + Dialog::Licenses, + Dialog::About, + Dialog::ProjectFiles, + Dialog::PublishSettings, + Dialog::PublishProgress, + Dialog::FindReplace, + Dialog::BrushLibrary, + Dialog::ConvertSymbol, + Dialog::LayerProperties, + Dialog::EditGrid, + Dialog::EditGuides, + Dialog::Plugins, + Dialog::PluginSettings, + Dialog::PluginExport, + Dialog::SaveTemplate, + Dialog::TestMovie, + Dialog::EaseEditor, + Dialog::SoundEnvelope, + Dialog::Recover, + Dialog::Updates, + Dialog::ManageWorkspaces, + Dialog::Palette, + Dialog::CloseUnsaved, + ]; + + /// The id its window is drawn under (`egui::Window::id`), for the ones that are windows. + pub fn window_id(self) -> Option<&'static str> { + Some(match self { + Dialog::Preferences => "prefs_window", + Dialog::Shortcuts => "shortcuts_window", + Dialog::Licenses => "licenses_window", + Dialog::About => "about_window", + Dialog::ProjectFiles => "files_window", + Dialog::PublishSettings => "publish_settings", + Dialog::PublishProgress => "publish_progress", + Dialog::FindReplace => "find_replace", + Dialog::BrushLibrary => "brush_library", + Dialog::ConvertSymbol => "convert_symbol", + Dialog::LayerProperties => "layer_props", + Dialog::EditGrid => "edit_grid", + Dialog::EditGuides => "edit_guides", + Dialog::Plugins => "plugins_window", + Dialog::PluginExport => "plugin_export", + Dialog::SaveTemplate => "save_template", + Dialog::TestMovie => "test_movie", + Dialog::EaseEditor => "ease_editor", + Dialog::SoundEnvelope => "envelope_editor", + Dialog::Recover => "recover_window", + Dialog::ManageWorkspaces => "manage_workspaces", + Dialog::Updates | Dialog::PluginSettings | Dialog::Palette | Dialog::CloseUnsaved => return None, + }) + } + + /// The guide's place for it. + pub fn topic(self) -> &'static str { + match self { + Dialog::Preferences => "preferences-shortcuts-accessibility.md#preferences", + Dialog::Shortcuts => "preferences-shortcuts-accessibility.md#keyboard-shortcuts", + Dialog::Licenses => "troubleshooting-and-faq.md#what-is-the-licence", + Dialog::About => "preferences-shortcuts-accessibility.md#about", + Dialog::ProjectFiles => "index.md#about-this-guide", + Dialog::PublishSettings => "exporting-and-publish.md#publish-settings", + Dialog::PublishProgress => "exporting-and-publish.md#publish", + Dialog::FindReplace => "workspace.md#find-and-replace", + Dialog::BrushLibrary => "drawing.md#the-brush", + Dialog::ConvertSymbol => "symbols-and-library.md#making-a-symbol", + Dialog::LayerProperties => "timeline.md#layer-properties", + Dialog::EditGrid | Dialog::EditGuides => "drawing.md#rulers-grid-and-guides", + Dialog::Plugins => "plugins.md#managing-plug-ins", + Dialog::PluginSettings => "plugins.md#the-settings-dialog", + Dialog::PluginExport => "plugins.md#exporting-with-a-plug-in", + Dialog::SaveTemplate => "getting-started.md#the-start-screen", + Dialog::TestMovie => "interactivity.md#test-movie", + Dialog::EaseEditor => "tweens.md#custom-eases", + Dialog::SoundEnvelope => "images-and-sound.md#effects-and-the-envelope", + Dialog::Recover => "getting-started.md#autosave-and-crash-recovery", + Dialog::Updates => "getting-started.md#install-anicraft", + Dialog::ManageWorkspaces => "workspace.md#workspaces", + Dialog::Palette => "workspace.md#the-command-palette", + Dialog::CloseUnsaved => "getting-started.md#save-your-work", + } + } +} + +/// Commands by id prefix, the longest that fits winning: a namespace (`layer.`) or a family +/// within one (`file.export`). Every namespace in the registry has a row (checked by test). +pub const COMMAND_TOPICS: &[(&str, &str)] = &[ + ("actions.", "interactivity.md#the-actions-panel"), + ("align.", "drawing.md#align-and-distribute"), + ("arrange.", "drawing.md#stacking-order"), + ("bone.", "masks-guides-camera-bones.md#bones-and-inverse-kinematics"), + ("brush.", "drawing.md#the-brush"), + ("camera.", "masks-guides-camera-bones.md#the-camera"), + ("control.", "interactivity.md#test-movie"), + ("desktop.", "getting-started.md#running-the-appimage"), + ("doc.", "workspace.md#properties"), + ("draw.", "drawing.md#drawing-shapes-and-lines"), + ("ease.", "tweens.md#easing"), + ("edit.", "drawing.md#clipboard-and-duplicates"), + ("edit.undo", "getting-started.md#undo-anything"), + ("edit.redo", "getting-started.md#undo-anything"), + ("element.", "drawing.md#transforming-artwork"), + ("explorer.", "workspace.md#the-movie-explorer"), + ("file.", "getting-started.md#save-your-work"), + ("file.new", "getting-started.md#the-start-screen"), + ("file.export", "exporting-and-publish.md#exporting-one-format"), + ("file.import", "images-and-sound.md#importing-images"), + ("file.publish", "exporting-and-publish.md#publish"), + ("file.recovery", "getting-started.md#autosave-and-crash-recovery"), + ("filter.", "drawing.md#filters-and-blend-modes"), + ("find.", "workspace.md#find-and-replace"), + ("frames.", "timeline.md#frames-and-keyframes"), + ("instance.", "symbols-and-library.md#instance-properties"), + ("layer.", "timeline.md#layers"), + ("library.", "symbols-and-library.md#the-library-panel"), + ("modify.", "drawing.md#transforming-artwork"), + ("modify.convert_to_symbol", "symbols-and-library.md#making-a-symbol"), + ("motion.", "tweens.md#motion-tweens"), + ("paint.", "drawing.md#paint-bucket-ink-bottle-and-eyedropper"), + ("path.", "drawing.md#editing-points-with-subselection"), + ("plugin.", "plugins.md#running-a-plug-in"), + ("prefs.", "preferences-shortcuts-accessibility.md#preferences"), + ("publish.", "exporting-and-publish.md#publish-settings"), + ("raw.", "drawing.md#merge-drawing-and-drawing-objects"), + ("scene.", "timeline.md#scenes"), + ("script.", "interactivity.md#frame-scripts-in-actionscript-30"), + ("sound.", "images-and-sound.md#sounds-on-keyframes"), + ("stroke.", "drawing.md#line-styles"), + ("swatch.", "drawing.md#swatches"), + ("symbol.", "symbols-and-library.md#making-a-symbol"), + ("text.", "text.md#typing-text"), + ("timeline.", "timeline.md#frames-and-keyframes"), + ("tween.", "tweens.md#which-tween-should-i-use"), + ("view.", "workspace.md#moving-around-the-stage"), + ("view.grid", "drawing.md#rulers-grid-and-guides"), + ("view.guide", "drawing.md#rulers-grid-and-guides"), + ("view.onion", "timeline.md#onion-skin"), + ("warp.", "masks-guides-camera-bones.md#asset-warp"), +]; + +/// Where the command reference lists every command, for one without a row. +pub const COMMAND_REFERENCE: &str = "reference/commands.md"; + +/// The guide's place for a command. +pub fn command_topic(id: &str) -> &'static str { + COMMAND_TOPICS.iter().filter(|(prefix, _)| id.starts_with(prefix)).max_by_key(|(prefix, _)| prefix.len()).map_or(COMMAND_REFERENCE, |(_, t)| t) +} + +/// The book's page for a chapter link: `timeline.md#onion-skin` → `timeline.html#onion-skin` +/// (the book's own rule, `anicraft_guide::target_html`; the web build doesn't link the book). +pub fn page_of(target: &str) -> String { + let html = |f: &str| f.strip_suffix(".md").map_or_else(|| f.to_string(), |stem| format!("{stem}.html")); + match target.split_once('#') { + Some((file, anchor)) => format!("{}#{anchor}", html(file)), + None => html(target), + } +} + +/// The book's search page. +pub const SEARCH_PAGE: &str = "search.html"; + +/// The heading a chapter link names, for the status bar. The desktop carries the book; the web +/// build serves it beside the editor instead, so it doesn't know the headings. +pub fn heading_of(target: &str) -> Option { + #[cfg(not(target_arch = "wasm32"))] + return anicraft_guide::heading_of(anicraft_guide::PAGES, target); + #[cfg(target_arch = "wasm32")] + { + let _ = target; + None + } +} + +/// What context help is about. +#[derive(Clone, Debug, PartialEq)] +pub enum Subject { + Tool(Tool), + Panel(Panel), + Dialog(Dialog), + Command(String), + /// A place in the guide given directly (a plug-in, a palette entry without a command). + Topic(&'static str), +} + +impl Subject { + pub fn topic(&self) -> &'static str { + match self { + Subject::Tool(t) => tool_topic(*t), + Subject::Panel(p) => panel_topic(*p), + Subject::Dialog(d) => d.topic(), + Subject::Command(id) => command_topic(id), + Subject::Topic(t) => t, + } + } +} + +/// A subject a widget offers while the pointer or keyboard is on it this pass (a tool's button), +/// read by [`subject`] in the next pass's shortcut handling. +#[derive(Clone, Debug)] +pub struct Offered { + pub pass: u64, + pub subject: Subject, +} + +/// Called by a widget the person is on (hovered or focused): F1 is about it. +pub fn offer(app: &mut App, ctx: &egui::Context, subject: Subject) { + app.help_offered = Some(Offered { pass: ctx.cumulative_pass_nr(), subject }); +} + +/// The dialog drawn on `layer`, if it is one of ours. +fn dialog_on(layer: egui::LayerId) -> Option { + Dialog::ALL.into_iter().find(|d| d.window_id().is_some_and(|w| layer.id == egui::Id::new(w))) +} + +fn visible(ctx: &egui::Context, d: Dialog) -> bool { + d.window_id().is_some_and(|w| ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, egui::Id::new(w))))) +} + +/// What F1 is about now. `pointer`: whether the pointer counts (not when the request comes from +/// a menu, which the pointer is on). +pub fn subject(app: &App, ctx: &egui::Context, pointer: bool) -> Subject { + // A dialog that holds the editor until it is answered. + if let Some(c) = &app.confirm { + return Subject::Command(c.id.clone()); + } + if let Some(p) = &app.prompt { + return Subject::Command(p.cmd.to_string()); + } + if app.convert.is_some() { + return Subject::Dialog(Dialog::ConvertSymbol); + } + if app.plugin_dialog.is_some() { + return Subject::Dialog(Dialog::PluginSettings); + } + if app.templates.save.is_some() { + return Subject::Dialog(Dialog::SaveTemplate); + } + if app.close_dialog { + return Subject::Dialog(Dialog::CloseUnsaved); + } + if let Some(p) = &app.palette { + return p.help.clone().unwrap_or(Subject::Dialog(Dialog::Palette)); + } + let now = ctx.cumulative_pass_nr(); + let offered = app.help_offered.as_ref().filter(|o| o.pass + 1 >= now).map(|o| o.subject.clone()); + if pointer && let Some(pos) = ctx.pointer_hover_pos() { + if let Some(d) = ctx.layer_id_at(pos).and_then(dialog_on) { + return Subject::Dialog(d); + } + if let Some(s) = offered.clone() { + return s; + } + match crate::a11y::region_at(ctx, pos) { + Some(crate::a11y::Region::Panel(p)) => return Subject::Panel(p), + Some(crate::a11y::Region::Tools) => return Subject::Panel(Panel::Tools), + Some(crate::a11y::Region::Stage) => return Subject::Tool(app.tool), + None => {} + } + } + // The keyboard: a focused tool button offers its tool; a focused panel, the panel. + if let Some(s) = offered { + return s; + } + if let Some(id) = ctx.memory(|m| m.focused()) + && let Some(d) = ctx.read_response(id).and_then(|r| dialog_on(r.layer_id)) + { + return Subject::Dialog(d); + } + match crate::a11y::focused_region(ctx) { + Some(crate::a11y::Region::Panel(p)) => return Subject::Panel(p), + Some(crate::a11y::Region::Tools | crate::a11y::Region::Stage) => return Subject::Tool(app.tool), + None => {} + } + // The window in front, if one is open; else the tool in hand. + if let Some(d) = ctx.memory(|m| m.areas().top_layer_id(egui::Order::Middle)).and_then(dialog_on).filter(|d| visible(ctx, *d)) { + return Subject::Dialog(d); + } + if let Some(d) = Dialog::ALL.into_iter().find(|d| visible(ctx, *d)) { + return Subject::Dialog(d); + } + Subject::Tool(app.tool) +} + +/// F1 / Help › Help for This: the guide at the place for what the person is working with. +pub fn help_for_this(app: &mut App, ctx: &egui::Context, pointer: bool) { + let s = subject(app, ctx, pointer); + app.open_help(s.topic()); +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::sample; + + fn all_targets() -> Vec<&'static str> { + let mut v: Vec<&'static str> = Tool::ALL.iter().map(|t| tool_topic(*t)).collect(); + v.extend(Panel::ALL.iter().map(|p| panel_topic(*p))); + v.extend(Dialog::ALL.iter().map(|d| d.topic())); + v.extend(COMMAND_TOPICS.iter().map(|(_, t)| *t)); + v.push(COMMAND_REFERENCE); + v + } + + #[test] + fn every_place_in_the_map_is_a_heading_of_the_guide() { + let problems = anicraft_guide::check_targets(anicraft_guide::PAGES, &all_targets()); + assert!(problems.is_empty(), "context help points at places the guide doesn't have:\n{}", problems.join("\n")); + // And each opens a page the book has, with a heading to name in the status bar. + let site: Vec = anicraft_guide::site().into_iter().map(|f| f.path).collect(); + assert_eq!(SEARCH_PAGE, anicraft_guide::SEARCH_PAGE); + for t in all_targets() { + let page = anicraft_guide::target_html(t); + assert_eq!(page_of(t), page, "the shell opens the page the book has"); + let file = page.split('#').next().unwrap_or(""); + assert!(site.iter().any(|p| p == file), "{t}: no page {file}"); + assert!(anicraft_guide::heading_of(anicraft_guide::PAGES, t).is_some(), "{t}"); + } + } + + #[test] + fn every_command_namespace_has_a_place() { + let mut missing: Vec = Vec::new(); + for c in anicraft_engine::commands() { + let ns = c.id.split('.').next().unwrap_or(""); + if !COMMAND_TOPICS.iter().any(|(p, _)| *p == format!("{ns}.")) && !missing.contains(&ns.to_string()) { + missing.push(ns.to_string()); + } + } + assert!(missing.is_empty(), "command namespaces without context help (add a row to COMMAND_TOPICS): {missing:?}"); + assert_eq!(command_topic("file.export_gif"), "exporting-and-publish.md#exporting-one-format"); + assert_eq!(command_topic("file.save"), "getting-started.md#save-your-work"); + assert_eq!(command_topic("view.onion_skin"), "timeline.md#onion-skin"); + assert_eq!(command_topic("nobody.knows"), COMMAND_REFERENCE); + // Every dialog has a window id or is found some other way, and the ids are distinct. + let ids: Vec<&str> = Dialog::ALL.iter().filter_map(|d| d.window_id()).collect(); + let mut sorted = ids.clone(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), ids.len(), "two dialogs share a window id"); + } + + fn input(events: Vec) -> egui::RawInput { + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), events, ..Default::default() } + } + + fn frame(ctx: &egui::Context, app: &mut App, events: Vec) { + ctx.run_ui(input(events), |ui| app.frame(ui)).textures_delta.clear(); + } + + fn app(ctx: &egui::Context) -> App { + App::with_context(ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png"))) + } + + fn settle(ctx: &egui::Context, app: &mut App) { + for _ in 0..3 { + frame(ctx, app, Vec::new()); + } + } + + fn f1() -> Vec { + vec![egui::Event::Key { key: egui::Key::F1, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }] + } + + #[test] + fn f1_on_the_stage_opens_the_active_tool_and_over_a_panel_that_panel() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + app.tool = Tool::Bone; + settle(&ctx, &mut app); + // Nothing hovered or focused: the tool in hand. + assert_eq!(subject(&app, &ctx, true), Subject::Tool(Tool::Bone)); + frame(&ctx, &mut app, f1()); + assert_eq!(app.help_opened.as_deref(), Some("masks-guides-camera-bones.md#building-an-armature")); + // Over the stage, the same; over the timeline, the timeline's section. + let stage = crate::a11y::region_rect(&ctx, crate::a11y::Region::Stage).expect("the stage drew"); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(stage.center())]); + assert_eq!(subject(&app, &ctx, true), Subject::Tool(Tool::Bone)); + let tl = crate::a11y::region_rect(&ctx, crate::a11y::Region::Timeline).expect("the timeline drew"); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tl.center())]); + assert_eq!(subject(&app, &ctx, true), Subject::Panel(Panel::Timeline)); + frame(&ctx, &mut app, f1()); + assert_eq!(app.help_opened.as_deref(), Some("timeline.md#a-tour-of-the-timeline")); + // From the menu the pointer doesn't count. + assert_eq!(subject(&app, &ctx, false), Subject::Tool(Tool::Bone)); + } + + #[test] + fn f1_in_a_dialog_opens_its_section() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + app.show_prefs = true; + settle(&ctx, &mut app); + assert_eq!(subject(&app, &ctx, false), Subject::Dialog(Dialog::Preferences)); + frame(&ctx, &mut app, f1()); + assert_eq!(app.help_opened.as_deref(), Some("preferences-shortcuts-accessibility.md#preferences")); + app.show_prefs = false; + settle(&ctx, &mut app); + // A dialog that asks first: help for the command it asks about. + app.close_dialog = true; + assert_eq!(subject(&app, &ctx, true), Subject::Dialog(Dialog::CloseUnsaved)); + frame(&ctx, &mut app, f1()); + assert_eq!(app.help_opened.as_deref(), Some("getting-started.md#save-your-work"), "F1 works while a dialog holds the editor"); + } + + #[test] + fn f1_in_the_palette_opens_the_chosen_command() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + app.palette = Some(crate::dialogs::Palette { query: "export animated gif".into(), ..Default::default() }); + settle(&ctx, &mut app); + frame(&ctx, &mut app, f1()); + assert_eq!(app.help_opened.as_deref(), Some("exporting-and-publish.md#exporting-one-format")); + assert!(app.palette.is_some(), "the palette stays open"); + } + + #[test] + fn the_panel_menu_offers_help_for_its_panel() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + settle(&ctx, &mut app); + crate::dock_ui::apply(&mut app, vec![crate::dock_ui::Act::Help(Panel::Library)]); + assert_eq!(app.help_opened.as_deref(), Some("symbols-and-library.md#the-library-panel")); + } +} diff --git a/src/dialogs.rs b/src/dialogs.rs index eb02aaab..77bc4df7 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -22,6 +22,8 @@ pub struct PendingConfirm { pub struct Palette { pub query: String, pub selected: usize, + /// What F1 opens the guide at: the chosen entry (ADR 0096), as of the last frame. + pub help: Option, } pub fn show_all(app: &mut App, ctx: &egui::Context) { @@ -169,6 +171,17 @@ enum Entry { } impl Entry { + /// What F1 on it opens in the guide (ADR 0096); view entries have no section of their own. + fn help(&self) -> Option { + use crate::context_help::Subject; + match self { + Entry::Command(c) => Some(Subject::Command(c.id.to_string())), + Entry::Tool(t) => Some(Subject::Tool(*t)), + Entry::View(..) => None, + Entry::Plugin(..) => Some(Subject::Topic("plugins.md#running-a-plug-in")), + } + } + /// The menu path to the entry, in the interface language (`local`) or in English, so /// either finds it. fn title(&self, local: bool) -> String { @@ -216,8 +229,9 @@ fn entries() -> Vec { v.push(Entry::View(tr_noop!("Onion Skin"), "", crate::onion::toggle_ghosts)); v.push(Entry::View(tr_noop!("Preview Through Camera"), "", App::toggle_camera_preview)); v.push(Entry::View(tr_noop!("Fit Stage in Window"), "Ctrl+0", |a| a.view.fit = true)); - v.push(Entry::View(tr_noop!("Keyboard Shortcuts"), "F1", |a| a.show_shortcuts = true)); + v.push(Entry::View(tr_noop!("Keyboard Shortcuts"), "Ctrl+Alt+Shift+K", |a| a.show_shortcuts = true)); v.push(Entry::View(tr_noop!("User Guide"), "", App::open_user_guide)); + v.push(Entry::View(tr_noop!("Search the User Guide"), "", App::open_guide_search)); v.push(Entry::View(tr_noop!("Project Files & Docs"), "", |a| a.show_files = true)); v.push(Entry::View(tr_noop!("Licenses & Notices"), "", |a| a.show_licenses = true)); v.push(Entry::View(tr_noop!("Preferences"), "Ctrl+U", App::open_prefs)); @@ -274,6 +288,7 @@ fn palette(app: &mut App, ctx: &egui::Context) { let mut run: Option = None; let mut close = esc; let selected = p.selected; + p.help = matches.get(selected).and_then(|(_, e, _)| e.help()); egui::Area::new(egui::Id::new("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, 70.0]).show(ctx, |ui| { egui::Frame::popup(ui.style()).fill(T.panel_alt).inner_margin(egui::Margin::same(10)).show(ui, |ui| { ui.set_width(560.0); @@ -732,7 +747,8 @@ pub(crate) fn fixed_rows() -> Vec<(&'static str, &'static str, Vec<&'static str> // Keys in registry notation; the words among them are translated by `fixed_key`. vec![ (essentials, tr_noop!("Command palette"), vec!["Ctrl+K"]), - (essentials, tr_noop!("Keyboard shortcuts (this editor)"), vec!["F1", "Ctrl+Alt+Shift+K"]), + (essentials, tr_noop!("Help for what you are pointing at"), vec!["F1"]), + (essentials, tr_noop!("Keyboard shortcuts (this editor)"), vec!["Ctrl+Alt+Shift+K"]), (essentials, tr_noop!("Play / Stop"), vec!["Enter"]), (essentials, tr_noop!("Preferences"), vec!["Ctrl+U", "Ctrl+,"]), (essentials, quit, vec!["Ctrl+Q"]), diff --git a/src/dock_ui.rs b/src/dock_ui.rs index 2e11277d..6e75e7ae 100644 --- a/src/dock_ui.rs +++ b/src/dock_ui.rs @@ -151,6 +151,8 @@ pub(crate) enum Act { Placed(u32, [f32; 2], [f32; 2]), Collapse(Side, bool), Flyout(Option), + /// The panel's section of the user guide (ADR 0096). + Help(Panel), } /// Where a control is, in its id: a panel's tab or menu is drawn in one place a frame, but a @@ -870,6 +872,10 @@ pub(crate) fn panel_menu(ui: &mut egui::Ui, at: Where, p: Panel, layout: &Layout Where::Bar(_) => {} } ui.separator(); + // "?": the panel's section of the user guide (ADR 0096), as in other studios' panel menus. + if item(ui, &tr!("? Help for {panel}", panel = crate::i18n::t(p.label()))) { + acts.push(Act::Help(p)); + } if item(ui, &tr!("Close {panel}", panel = crate::i18n::t(p.label()))) { acts.push(Act::Close(p)); } @@ -1320,6 +1326,7 @@ pub(crate) fn apply(app: &mut App, acts: Vec) { app.dock_view.flyout = None; changed = true; } + Act::Help(p) => app.open_help(crate::context_help::panel_topic(p)), Act::Flyout(p) => { app.dock_view.flyout = p; if let Some(p) = p diff --git a/src/guide_reference_tests.rs b/src/guide_reference_tests.rs index e4ff16ed..59532ede 100644 --- a/src/guide_reference_tests.rs +++ b/src/guide_reference_tests.rs @@ -68,7 +68,7 @@ pub fn commands_md() -> String { "Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), \ `anicraft-cli` and AI assistants over MCP all run the same {} commands, listed here by menu. The id is what scripts and \ [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the \ - document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the \ + document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the \ [shortcut reference](shortcuts.md).\n\n", cmds.len() )); @@ -114,7 +114,7 @@ pub fn shortcuts_md() -> String { let mut out = String::from("# Shortcut reference\n\n"); out.push_str( "AniCraft's default keyboard shortcuts. On macOS, **Ctrl** is **⌘** (Command) and **Alt** is **⌥** (Option). \ - To change a shortcut, open **Help › Keyboard Shortcuts** (**F1**): see \ + To change a shortcut, open **Help › Keyboard Shortcuts** (**Ctrl+Alt+Shift+K**): see \ [Preferences, shortcuts, accessibility and languages](../preferences-shortcuts-accessibility.md). \ The keys in the fixed rows can't be reassigned. Every command, with or without a key, is in the \ [command reference](commands.md).\n\n\ diff --git a/src/keymap.rs b/src/keymap.rs index d5d2c48a..611ef37e 100644 --- a/src/keymap.rs +++ b/src/keymap.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; pub const RESERVED: &[(&str, &str)] = &[ ("Ctrl+K", tr_noop!("the command palette")), ("Ctrl+Shift+P", tr_noop!("the command palette")), - ("F1", tr_noop!("the shortcut editor")), + ("F1", tr_noop!("help for what you are pointing at")), ("Ctrl+Alt+Shift+K", tr_noop!("the shortcut editor")), ("Ctrl+U", tr_noop!("Preferences")), ("Ctrl+,", tr_noop!("Preferences")), diff --git a/src/main.rs b/src/main.rs index 8c62d086..afd2a9d8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,6 +38,7 @@ mod bind_tool; mod warp_tool; mod bone_tool; mod camera_tool; +mod context_help; mod convert_symbol; mod layer_depth; mod layer_props; @@ -266,7 +267,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ diff --git a/src/menus.rs b/src/menus.rs index 64b5f9f1..baa4c930 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -722,6 +722,14 @@ pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: & if ui_item(ui, tr!("User Guide"), "", None) { app.open_user_guide(); } + // The guide at the section for the dialog in front, the focused panel or the tool + // in hand (F1 also counts what the pointer is over; ADR 0096). + if ui_item(ui, tr!("Help for This"), "F1", None) { + crate::context_help::help_for_this(app, ui.ctx(), false); + } + if ui_item(ui, tr!("Search the User Guide"), "", None) { + app.open_guide_search(); + } ui.separator(); #[cfg(not(target_arch = "wasm32"))] if ui_item(ui, tr!("Check for Updates…"), "", None) { @@ -730,7 +738,7 @@ pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: & if ui_item(ui, tr!("Command Palette…"), "Ctrl+K", None) { app.palette = Some(crate::dialogs::Palette::default()); } - if ui_item(ui, tr!("Keyboard Shortcuts"), "F1", None) { + if ui_item(ui, tr!("Keyboard Shortcuts"), "Ctrl+Alt+Shift+K", None) { app.show_shortcuts = true; } ui.separator(); diff --git a/src/panels.rs b/src/panels.rs index 42213b6f..81744142 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -100,6 +100,10 @@ fn tool_items(app: &mut App, ui: &mut egui::Ui, area: Rect, flow: ToolFlow) { if active { a11y::anchor(ui, a11y::Region::Tools, area, &resp); } + // F1 over (or on) a tool's button: that tool's section of the guide (ADR 0096). + if resp.hovered() || resp.has_focus() { + crate::context_help::offer(app, ui.ctx(), crate::context_help::Subject::Tool(tool)); + } let resp = resp.on_hover_text(format!("{name} {}", crate::i18n::t(tool.hint()))); if resp.clicked() { diff --git a/src/platform.rs b/src/platform.rs index dc4d30a6..2780253d 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -451,6 +451,28 @@ pub fn open_user_guide() -> Result<(), String> { } } +/// Context help and search (ADR 0096): the bundled book at `page` (a page of the book with its +/// anchor, `timeline.html#onion-skin`). A `file://` page opened by the system loses its anchor +/// on some systems, so the desktop writes a page beside the book that sends the browser on. +pub fn open_user_guide_at(page: &str) -> Result<(), String> { + #[cfg(not(target_arch = "wasm32"))] + { + // Tests press F1 and click every control: they never write to the cache or open a browser. + if cfg!(test) { + return Ok(()); + } + let dir = guide_dir(); + anicraft_guide::write_site(&dir).map_err(|e| tr!("could not write the user guide to {path}: {e}", path = dir.display(), e = e))?; + let help = dir.join(anicraft_guide::HELP_PAGE); + std::fs::write(&help, anicraft_guide::redirect_page(page)).map_err(|e| tr!("could not write the user guide to {path}: {e}", path = dir.display(), e = e))?; + crate::app::open_in_system(&help) + } + #[cfg(target_arch = "wasm32")] + { + crate::web::open_page(&format!("guide/{page}")) + } +} + /// Where settings are kept, for Preferences (in the interface language). pub fn settings_place() -> String { if WEB { From 1767410510818d90afb008dc875fcf9380c04b39 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 23:58:50 -0700 Subject: [PATCH 051/570] docs: ADR 0096 guide search and context help; roadmap, changelog (M8) --- CHANGELOG.md | 11 +++ docs/adr/0069-the-user-guide.md | 4 +- .../adr/0096-guide-search-and-context-help.md | 94 +++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 4 +- 5 files changed, 109 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0096-guide-search-and-context-help.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c91def60..09ea7d69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +* **Search the user guide, and help for what you are working on** (ADR 0096, M8). + * **Search** in every page of the bundled guide, offline: results as you type with the + chapter, heading and a passage with your words marked; `/` goes to the field, arrows move + through results, Enter opens one. `anicraft-cli guide search ` prints the same results. + * **F1** opens the guide at the section for the dialog in front, the panel or tool under the + pointer, the focused panel or the tool in hand (F1 on the Bone tool: building an armature). + Also **Help › Help for This**, **Help › Search the User Guide**, **? Help for…** in every + panel menu, and F1 on a command in the command palette. + * The keyboard shortcut editor moves from F1 to **Ctrl+Alt+Shift+K**, as in Animate. + * A new chapter, **Using this guide**. + * **Portable copies and AppImage desktop integration** (ADR 0094, M8). * **The Windows zip and the Linux tar.gz are portable**: preferences, autosaved work, logs, plug-ins, templates, brushes, filter presets, workspaces and recent files stay in a `data` diff --git a/docs/adr/0069-the-user-guide.md b/docs/adr/0069-the-user-guide.md index fe449083..8b06b0e1 100644 --- a/docs/adr/0069-the-user-guide.md +++ b/docs/adr/0069-the-user-guide.md @@ -70,6 +70,6 @@ isn't there yet. It must work offline from the app, match the version it ships w ## Not yet -* Translated guides, search inside the book, and a printable single-page or PDF edition. -* Context help (a "?" in a panel opening its chapter at the right heading). +* Translated guides, and a printable single-page or PDF edition. +* ~~Search inside the book~~ and ~~context help~~: ADR 0096. * Screenshots on macOS and Linux, and in high contrast. diff --git a/docs/adr/0096-guide-search-and-context-help.md b/docs/adr/0096-guide-search-and-context-help.md new file mode 100644 index 00000000..8eb0a541 --- /dev/null +++ b/docs/adr/0096-guide-search-and-context-help.md @@ -0,0 +1,94 @@ +# ADR 0096: User guide search and context help + +* Status: accepted (2026-11-13) +* Relates to: ADR 0069 (the bundled guide), ADR 0004 (destructive actions), ADR 0022 and 0064 + (accessibility, Ctrl+F6 panel focus), ADR 0036 (web build), ADR 0040 (interface languages), + ADR 0075 and 0087 (dockable panels), roadmap M8 ("next: translated guides, search, PDF, context + help") + +## Context + +ADR 0069 bundled the user guide as static HTML that Help › User Guide opens offline. Two things +were missing for artists: finding a topic without knowing which chapter holds it, and getting +from the thing in front of them (a tool, a panel, a dialog) to the page about it. Animate users +expect **F1** to open help. The book is opened from a `file://` folder, often with no network, so +nothing may come from a server or a CDN, and a `file://` page may not `fetch` a JSON file. + +## Decision + +1. **Search: a prebuilt index, a small script, one ranking.** `anicraft_guide::search` splits + the book into sections (one per heading, every heading of every page, levels 1 to 6) with + their plain text. The book gains three files: `search-index.js` (the sections as JSON assigned + to a global, so a `\n"), " aria-describedby=\"search-status\" aria-controls=\"results\""), }; format!( - "\n\n\n\n\n\ + "\n\n\n\n\n\ {t} · AniCraft User Guide\n\n{index}\n\n\ Skip to the chapter\n\
      AniCraft User Guide {VERSION}\ diff --git a/crates/guide/src/search.js b/crates/guide/src/search.js index d685dec6..6c143ba0 100644 --- a/crates/guide/src/search.js +++ b/crates/guide/src/search.js @@ -131,7 +131,9 @@ // ---- In the book ---- var LIMIT = 30; - var root = document.documentElement.getAttribute("data-root") || ""; + // A page of the book from the index (search.html sits at the book's root): `page.html` or + // `page.html#anchor`, never a scheme or a path that climbs out. + var PAGE = /^[a-z0-9-]+(\/[a-z0-9-]+)*\.html(#[\p{L}\p{N}_-]*)?$/u; function isTyping(el) { return el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable); @@ -191,8 +193,9 @@ : (hits.length === 1 ? "1 result" : hits.length + (hits.length === LIMIT ? "+ results" : " results")) + " for “" + query.trim() + "”."; hits.forEach(function (h) { var li = document.createElement("li"); + if (!PAGE.test(h.url)) return; var a = document.createElement("a"); - a.href = root + h.url; + a.setAttribute("href", h.url); var head = document.createElement("span"); head.className = "hit-heading"; head.textContent = h.heading; diff --git a/crates/guide/src/tests.rs b/crates/guide/src/tests.rs index be951d0e..bbc3c3ac 100644 --- a/crates/guide/src/tests.rs +++ b/crates/guide/src/tests.rs @@ -130,6 +130,13 @@ fn the_index_covers_every_heading_of_every_page() { assert_eq!(anchors, indexed, "{}: every heading is a section of the index", p.file); } assert!(sections.iter().all(|s| !s.heading.trim().is_empty()), "every section has its heading"); + // search.js links only to `page.html#anchor` of this shape (its PAGE pattern). + for s in §ions { + let file = html_path(PAGES[s.page].file); + let ok_file = file.ends_with(".html") && file.split('/').all(|part| !part.is_empty() && part.trim_end_matches(".html").chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')); + let ok_anchor = s.anchor.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_'); + assert!(ok_file && ok_anchor, "{file}#{} would not be linked by search.js", s.anchor); + } let json: serde_json::Value = serde_json::from_str(&search::index_json(PAGES, §ions)).expect("the index is JSON"); assert_eq!(json["sections"].as_array().map(Vec::len), Some(sections.len())); assert_eq!(json["pages"].as_array().map(Vec::len), Some(PAGES.len())); From c4544466777f560e75502b372bd49baf2c68bc47 Mon Sep 17 00:00:00 2001 From: macallantheroot Date: Sat, 14 Nov 2026 12:43:05 +0300 Subject: [PATCH 053/570] fix(mcp): correct render caption dimension separator --- crates/cli/src/mcp.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 44e3543e..d0e50baf 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -164,7 +164,7 @@ fn call_tool(s: &mut Session, name: &str, args: &Value) -> Result json!({ "content": [ {"type": "image", "data": anicraft_doc::base64_encode(&png), "mimeType": "image/png"}, - {"type": "text", "text": format!("Frame {frame} of scene {} at {:.0}% ({}×{} stage).", s.scene, scale * 100.0, stage.width, stage.height)} + {"type": "text", "text": format!("Frame {frame} of scene {} at {:.0}% ({}×{} stage).", s.scene, scale * 100.0, stage.width, stage.height)} ], "isError": false }) @@ -297,9 +297,16 @@ mod tests { fn render_returns_a_png_picture() { let mut s = Session::new(anicraft_doc::sample::demo()); let r = tool(&mut s, "anicraft_render", json!({"frame": 3, "scale": 0.25})); + assert_eq!(r["isError"], false); + assert_eq!(r["content"].as_array().unwrap().len(), 2); + assert_eq!(r["content"][1]["type"], "text"); + assert_eq!(r["content"][1]["text"], "Frame 3 of scene 0 at 25% (1280×720 stage)."); assert_eq!(r["content"][0]["type"], "image"); assert_eq!(r["content"][0]["mimeType"], "image/png"); assert!(r["content"][0]["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "base64 of the PNG signature"); + let png = anicraft_doc::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(); + let pixels = anicraft_doc::decode_png(&png).unwrap(); + assert_eq!((pixels.width, pixels.height), (320, 180)); assert_eq!(tool(&mut s, "anicraft_render", json!({"frame": 1_000_000}))["isError"], true); assert_eq!(call(&mut s, 7, "tools/call", json!({"name": "anicraft_render", "arguments": {"scale": -1}}))["error"]["code"], -32602); } From b0c4d624e90ba6fbdebc06b3d9a51678348d87ed Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:21:40 -0700 Subject: [PATCH 054/570] docs: reserve ADR 0097 for command macros (M6) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..2f429b1e 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0097 | (this track, M6) | Command macros (saved commands) | From f167ebe3daba0709c0206f94dc8dbcf2573a9b2a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:56:16 -0700 Subject: [PATCH 055/570] feat(engine): command macros: history records each step's commands, macro.* commands (M6) Every undo step keeps the commands it ran; Save As Command rewrites ids of this document to act on the selection or active layer, or names the step it can't keep. macro.run is one transactional undo step; macros call only what a plug-in may, and plug-ins can't call macro.*. anicraft-cli run reads saved command files. ADR 0097. --- crates/cli/src/lib.rs | 30 +- crates/engine/src/cmds_macro.rs | 516 +++++++++++++++++++++++++++++ crates/engine/src/cmds_plugin.rs | 3 + crates/engine/src/cmds_template.rs | 2 +- crates/engine/src/confirm.rs | 19 ++ crates/engine/src/history.rs | 93 +++++- crates/engine/src/lib.rs | 70 +++- crates/engine/src/macro_tests.rs | 353 ++++++++++++++++++++ crates/engine/src/plugin_tests.rs | 2 +- 9 files changed, 1075 insertions(+), 13 deletions(-) create mode 100644 crates/engine/src/cmds_macro.rs create mode 100644 crates/engine/src/macro_tests.rs diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index d44b3c18..d9f21d60 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -30,6 +30,8 @@ USAGE: anicraft-cli formats lists every export format, plug-ins included (JSON) anicraft-cli commands anicraft-cli run [--save ] + a JSON array of {cmd, params}, or a saved command + (one undo step; nothing changes if a step fails) anicraft-cli exec [] [--save ] anicraft-cli new --out [--width W] [--height H] [--fps F] anicraft-cli guide --out writes the user guide as HTML pages (open index.html) @@ -239,7 +241,16 @@ pub fn run(argv: &[String]) -> Result { let script = a.positional.get(1).ok_or("run needs a script.json")?; let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?; // Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it. - let steps: Vec = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?; + let parsed: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}} or a saved command: {e}"))?; + // A saved command (ADR 0097) runs as one transactional step, as in the app. + if parsed.is_object() { + let v = exec(&mut s, "macro.run", &json!({"path": script}))?; + if let Some(out) = a.flag("save") { + exec(&mut s, "file.save", &json!({"path": out}))?; + } + return serde_json::to_string_pretty(&v).map_err(|e| e.to_string()); + } + let steps: Vec = serde_json::from_value(parsed).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?; let mut results = Vec::new(); for (i, step) in steps.iter().enumerate() { let id = step.get("cmd").and_then(Value::as_str).ok_or_else(|| format!("step {}: missing \"cmd\"", i + 1))?; @@ -699,6 +710,23 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn run_takes_a_saved_command_file() { + let dir = std::env::temp_dir().join(format!("anicraft-cli-macro-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Spin.json"); + std::fs::write(&file, r#"{"format": "anicraft-command", "version": 1, "steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}]}"#).unwrap(); + let out = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap(); + let v: Value = serde_json::from_str(&out).unwrap(); + assert_eq!((v["name"].as_str(), v["steps"].as_u64()), (Some("Spin"), Some(2)), "{out}"); + // A failing step names itself and leaves nothing behind. + std::fs::write(&file, r#"{"steps": [{"cmd": "modify.rotate_cw"}, {"cmd": "layer.set_height", "params": {"height": 7}}]}"#).unwrap(); + let e = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap_err(); + assert!(e.contains("stopped at step 2 of 2"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn usage_and_errors() { assert!(run(&[]).unwrap().contains("USAGE")); diff --git a/crates/engine/src/cmds_macro.rs b/crates/engine/src/cmds_macro.rs new file mode 100644 index 00000000..dce54ad7 --- /dev/null +++ b/crates/engine/src/cmds_macro.rs @@ -0,0 +1,516 @@ +//! Saved commands (command macros, ADR 0097): steps picked in the History panel, kept as a +//! small JSON file and run again as one undo step. +//! +//! Every undo step remembers the commands it ran (`history::Recorded`). Save As Command turns +//! the picked steps into a saved command, rewriting what only makes sense in this document +//! (an element's or layer's id) to act on the current selection or active layer where the +//! command allows it, and refusing, with the step named, what can't be kept. A saved command +//! may call what a plug-in may (`plugin_may_call`) and never the `macro.*` commands, so it +//! can't recurse, touch files or the clipboard. +//! +//! A saved command is a file `/.json`: `{"format": "anicraft-command", +//! "version": 1, "steps": [{"cmd", "params", "label"}]}`. The file's name is the command's +//! name, so a shared file keeps whatever name it is given. `anicraft-cli run` scripts (a bare +//! JSON array of `{cmd, params}`) run the same way. Their order in the Commands menu is kept +//! in `/.order.json`. The shell passes the folder (its settings folder's `Commands`); +//! the engine never looks for it, as with templates. + +use crate::history::Recorded; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, vfs}; +use serde_json::{Map, Value, json}; +use std::path::{Path, PathBuf}; + +/// The `format` a saved command's file declares. +pub const FORMAT: &str = "anicraft-command"; +/// The newest file version this build reads and the one it writes. +pub const VERSION: u64 = 1; +/// Most steps in one saved command. +pub const MAX_STEPS: usize = 1000; +/// Largest saved command file read. +pub const MAX_FILE_BYTES: u64 = 1 << 20; +/// Most saved commands listed from one folder. +pub const MAX_LISTED: usize = 500; +/// The file that keeps the order of the saved commands (a dot-name: no command is called that). +pub const ORDER_FILE: &str = ".order.json"; +/// Longest command id and step label kept from a file. +const MAX_CMD_CHARS: usize = 128; +const MAX_LABEL_CHARS: usize = 200; + +pub fn specs() -> Vec { + let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run }; + vec![ + c("macro.run", "Run Command…", "Commands", "{name + folder (a saved command) | path (a saved command's file, or a JSON array of {cmd, params}) | steps: [{cmd, params?, label?}], name? (for steps)} → {name, steps, results}: runs the steps in order as one undo step named after it. At the first step that fails nothing is changed and the error names the step. Steps may call what a plug-in may, never macro.*", true, run as crate::RunFn), + c("macro.list", "Manage Saved Commands…", "Commands", "{folder} → {commands: [{name, path, steps}], problems: [{file, error}]}: the saved commands in the folder, in their order (the app shows them in a window)", false, list), + c("macro.history", "List History Steps", "", "{} → {steps: [{index, label, undone, keep, commands?, why?, rewritten?}]}: every undo-history step as Save As Command keeps it: `keep` false says `why` it can't be kept; `rewritten` names params dropped so the step acts on the selection or active layer", false, history), + c("macro.save", "Save As Command…", "", "{folder, name, history: [index, ..] (as macro.history lists them) | steps: [{cmd, params?, label?}], confirm? (to replace a saved command of that name)} → {name, path, steps, rewritten}: keeps the steps as /.json, last in the list", false, save), + c("macro.rename", "Rename Saved Command", "", "{folder, name, to} → {name, from, path}: renames a saved command (its file); its place in the list stays", false, rename), + c("macro.delete", "Delete Saved Command", "", "{folder, name, confirm}: deletes a saved command's file (cannot be undone)", false, delete), + c("macro.move", "Move Saved Command", "", "{folder, name, index (its new place in the list, 0-based)}", false, move_to), + c("macro.import", "Add Saved Command from File", "", "{folder, path (a saved command's file), name? (default: the file's), confirm? (to replace one of that name)} → {name, path, steps}: checks it and copies it in, last in the list", false, import), + ] +} + +/// Whether a saved command may run command `id`, and if not, why: what a plug-in may, and +/// never a `macro.*` command (a saved command doesn't run, save or change saved commands). +pub fn macro_may_call(id: &str) -> std::result::Result<(), String> { + if id.split('.').next() == Some("macro") { + return Err("a saved command can't run, save or change saved commands".into()); + } + crate::cmds_plugin::plugin_may_call(id).map_err(|why| format!("{why} (a saved command may do only what a plug-in may)")) +} + +/// One step of a saved command. +#[derive(Clone, Debug, PartialEq)] +pub struct Step { + pub cmd: String, + /// Always an object. + pub params: Value, + /// What the History panel called it (may be empty: then the command's label). + pub label: String, +} + +impl Step { + /// The step's name in messages. + pub fn name(&self) -> String { + if !self.label.is_empty() { + return self.label.clone(); + } + crate::find_command(&self.cmd).map_or_else(|| self.cmd.clone(), |c| c.label.trim_end_matches('…').to_string()) + } +} + +/// A saved command: its name and steps. +#[derive(Clone, Debug, PartialEq)] +pub struct Macro { + pub name: String, + pub steps: Vec, +} + +impl Macro { + /// The file's content. + pub fn to_json(&self) -> Value { + let steps: Vec = self.steps.iter().map(|s| json!({"cmd": s.cmd, "params": s.params, "label": s.label})).collect(); + json!({"format": FORMAT, "version": VERSION, "steps": steps}) + } + + /// Reads a saved command named `name`: a file's object, or a bare array of steps (an + /// `anicraft-cli run` script). Every step is checked: a known command a saved command may + /// call, with object params. + pub fn from_json(v: &Value, name: &str) -> Result { + let steps = match v { + Value::Array(a) => a, + Value::Object(o) => { + if let Some(f) = o.get("format") + && f.as_str() != Some(FORMAT) + { + return Err(EngineError::Format(format!("not a saved command (its format is {f}, not \"{FORMAT}\")"))); + } + if let Some(v) = o.get("version") { + let v = v.as_u64().ok_or_else(|| EngineError::Format("a saved command's version is a whole number".into()))?; + if v > VERSION { + return Err(EngineError::Format(format!("this saved command was made by a newer AniCraft (version {v}); update AniCraft to run it"))); + } + } + o.get("steps").and_then(Value::as_array).ok_or_else(|| EngineError::Format("a saved command has a \"steps\" list".into()))? + } + _ => return Err(EngineError::Format("a saved command is a JSON object with \"steps\", or a list of {cmd, params}".into())), + }; + if steps.len() > MAX_STEPS { + return Err(EngineError::Format(format!("a saved command has at most {MAX_STEPS} steps (this one has {})", steps.len()))); + } + let mut out = Vec::with_capacity(steps.len()); + for (i, st) in steps.iter().enumerate() { + let n = i + 1; + let o = st.as_object().ok_or_else(|| EngineError::Format(format!("step {n} is not an object {{cmd, params}}")))?; + let cmd = o.get("cmd").or_else(|| o.get("command")).and_then(Value::as_str).ok_or_else(|| EngineError::Format(format!("step {n} has no \"cmd\"")))?; + if cmd.chars().count() > MAX_CMD_CHARS || crate::find_command(cmd).is_none() { + let shown: String = cmd.chars().take(40).collect(); + return Err(EngineError::Format(format!("step {n}: unknown command '{shown}'"))); + } + macro_may_call(cmd).map_err(|why| EngineError::Format(format!("step {n} ({cmd}) can't be in a saved command: {why}")))?; + let params = match o.get("params") { + None | Some(Value::Null) => Value::Object(Map::new()), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(EngineError::Format(format!("step {n} ({cmd}): params are an object"))), + }; + let label: String = o.get("label").and_then(Value::as_str).unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_LABEL_CHARS).collect(); + out.push(Step { cmd: cmd.to_string(), params, label }); + } + Ok(Macro { name: name.to_string(), steps: out }) + } +} + +/// The file of the saved command called `name` in `folder`. +pub fn command_path(folder: &Path, name: &str) -> Result { + let name = crate::cmds_template::clean_name(name, "command")?; + Ok(folder.join(format!("{name}.json"))) +} + +/// Reads a saved command's file (its name is the file's). +pub fn load(path: &Path) -> Result { + let len = vfs::len(path).map_err(|e| EngineError::Io(std::io::Error::new(e.kind(), format!("{}: {e}", path.display()))))?; + if len > MAX_FILE_BYTES { + return Err(EngineError::Format(format!("{} is larger than a saved command can be ({} KiB at most)", path.display(), MAX_FILE_BYTES / 1024))); + } + let text = vfs::read_to_string(path)?; + // Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it. + let v: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| EngineError::Format(format!("{}: not JSON ({e})", path.display())))?; + let name = path.file_stem().map_or_else(|| "Command".to_string(), |n| n.to_string_lossy().into_owned()); + Macro::from_json(&v, &name) +} + +/// A saved command found in the folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Saved { + pub name: String, + pub path: PathBuf, + pub steps: usize, +} + +fn read_order(folder: &Path) -> Vec { + let path = folder.join(ORDER_FILE); + if vfs::len(&path).map_or(true, |n| n > MAX_FILE_BYTES) { + return Vec::new(); + } + let v: Value = vfs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(t.trim_start_matches('\u{feff}')).ok()).unwrap_or(Value::Null); + v.as_array().into_iter().flatten().filter_map(Value::as_str).take(MAX_LISTED).map(str::to_string).collect() +} + +fn write_order(folder: &Path, names: &[String]) -> Result<()> { + let text = serde_json::to_string_pretty(names).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(&folder.join(ORDER_FILE), text)?; + Ok(()) +} + +/// The saved commands in `folder`, in their order (then by name), and the files that aren't +/// saved commands with why: `(file name, error)`. +pub fn saved_commands(folder: &Path) -> (Vec, Vec<(String, String)>) { + let order: Vec = read_order(folder).into_iter().map(|n| n.to_lowercase()).collect(); + let mut found = Vec::new(); + let mut problems = Vec::new(); + for f in vfs::list(folder, MAX_LISTED * 2) { + let Some(stem) = f.file_stem().map(|n| n.to_string_lossy().into_owned()) else { continue }; + if stem.starts_with('.') || !f.extension().is_some_and(|e| e.eq_ignore_ascii_case("json")) || !vfs::is_file(&f) { + continue; + } + let file = f.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + match load(&f) { + Ok(m) if found.len() < MAX_LISTED => found.push(Saved { name: m.name, path: f, steps: m.steps.len() }), + Ok(_) => {} + Err(e) => problems.push((file, e.to_string())), + } + } + found.sort_by_key(|s| (order.iter().position(|o| *o == s.name.to_lowercase()).unwrap_or(usize::MAX), s.name.to_lowercase())); + problems.sort(); + (found, problems) +} + +fn folder(p: &Value) -> Result { + let f = str_req(p, "folder")?; + if f.trim().is_empty() { + return Err(EngineError::Param("name the saved commands' folder".into())); + } + Ok(PathBuf::from(f)) +} + +/// The saved command file the params name (`folder` and `name`). +pub(crate) fn target(p: &Value) -> Result { + command_path(&folder(p)?, str_req(p, "name")?) +} + +/// Where `macro.import` copies its file to. +pub(crate) fn import_target(p: &Value) -> Result { + let from = PathBuf::from(str_req(p, "path")?); + let name = match opt_str(p, "name")? { + Some(n) => n.to_string(), + None => from.file_stem().map(|n| n.to_string_lossy().into_owned()).ok_or_else(|| EngineError::Param("the file has no name".into()))?, + }; + command_path(&folder(p)?, &name) +} + +fn name_of(path: &Path) -> String { + path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) +} + +/// The saved command the params name: by `name` in `folder`, a file's `path`, or `steps`. +fn resolve(p: &Value) -> Result { + if let Some(steps) = p.get("steps") { + let name = opt_str(p, "name")?.map_or_else(|| "Saved command".to_string(), |n| n.chars().filter(|c| !c.is_control()).take(crate::cmds_template::MAX_NAME_CHARS).collect()); + return Macro::from_json(steps, &name); + } + if let Some(path) = opt_str(p, "path")? { + return load(Path::new(path)); + } + let path = target(p).map_err(|e| EngineError::Param(format!("name a saved command (name and folder), a file (path) or steps: {e}")))?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + load(&path) +} + +fn run(s: &mut Session, p: &Value) -> Result { + let m = resolve(p)?; + if m.steps.is_empty() { + return Err(EngineError::State(format!("“{}” has no steps to run", m.name))); + } + let n = m.steps.len(); + let mut results = Vec::with_capacity(n); + for (i, st) in m.steps.iter().enumerate() { + // (Checked when it was read; the rule is the run's, so it is checked here too.) + let r = macro_may_call(&st.cmd).map_err(EngineError::State).and_then(|()| s.execute_nested(&st.cmd, &st.params)); + match r { + Ok(v) => results.push(v), + // The session puts the document back as it was before the run. + Err(e) => return Err(EngineError::State(format!("“{}” stopped at step {} of {n} ({}): {e}. Nothing was changed.", m.name, i + 1, st.name()))), + } + } + s.step_label = Some(m.name.clone()); + // History keeps the steps, so a run can itself be saved again with other steps. + s.record_as = Some(m.steps.iter().map(|st| Recorded::new(&st.cmd, &st.params)).collect()); + Ok(json!({"name": m.name, "steps": n, "results": results})) +} + +fn list(_: &mut Session, p: &Value) -> Result { + let (found, problems) = saved_commands(&folder(p)?); + let commands: Vec = found.iter().map(|c| json!({"name": c.name, "path": c.path.display().to_string(), "steps": c.steps})).collect(); + let problems: Vec = problems.iter().map(|(f, e)| json!({"file": f, "error": e})).collect(); + Ok(json!({"commands": commands, "problems": problems})) +} + +/// Params naming who a step acts on: dropped, where the command then acts on the selection +/// (or, for layers, the active layer), so the step replays elsewhere. +const TARGETS: &[&str] = &["layer", "layers", "element", "elements", "id", "ids", "shape", "path", "symbol"]; +/// Params naming things that exist only in this document: Library items, folders and bones. +const FIXED: &[&str] = &["bitmap", "sound", "folder", "bone", "parent", "items"]; + +/// What a param names, in a sentence. +fn noun(key: &str) -> &'static str { + match key { + "layer" | "layers" => "particular layers", + "symbol" | "bitmap" | "sound" | "folder" | "items" => "particular Library items", + "bone" | "parent" | "from" | "to" => "particular bones", + _ => "particular objects", + } +} + +/// Whether the command's params doc makes `key` optional (`key?`), and, but for layers, says +/// it defaults to what is selected. +fn defaults_to_selection(doc: &str, key: &str) -> bool { + let pat = format!("{key}?"); + doc.match_indices(&pat).any(|(i, _)| { + let whole = doc.get(..i).and_then(|b| b.chars().next_back()).is_none_or(|c| !c.is_alphanumeric() && c != '_'); + let after: String = doc.get(i + pat.len()..).unwrap_or("").chars().take(90).collect(); + whole && (key.starts_with("layer") || after.contains("select")) + }) +} + +/// A recorded command as a saved command keeps it: its params without what names this +/// document's layers and objects (and which of those went), or why it can't be kept. +pub fn portable(cmd: &str, params: &Value) -> std::result::Result<(Value, Vec), String> { + macro_may_call(cmd)?; + let spec = crate::find_command(cmd).ok_or_else(|| format!("'{cmd}' is not a command any more"))?; + let Some(o) = params.as_object() else { return Ok((Value::Object(Map::new()), Vec::new())) }; + let mut out = Map::new(); + let mut dropped = Vec::new(); + for (k, v) in o { + let fixed = FIXED.contains(&k.as_str()) || (cmd.starts_with("bone.") && matches!(k.as_str(), "from" | "to")) || (cmd == "library.move" && k == "to"); + if v.is_null() || !(fixed || TARGETS.contains(&k.as_str())) { + out.insert(k.clone(), v.clone()); + } else if !fixed && defaults_to_selection(spec.params, k) { + dropped.push(k.clone()); + } else { + return Err(format!("it works on {} of this document", noun(k))); + } + } + Ok((Value::Object(out), dropped)) +} + +/// An undo step as a saved command keeps it: its steps and the params dropped, or why not. +fn keep_step(label: &str, cmds: Option<&[Recorded]>) -> std::result::Result<(Vec, Vec), String> { + let cmds = cmds.ok_or("it ran too many commands to keep (a very long drag?)")?; + if cmds.is_empty() { + return Err("it has nothing to run again".into()); + } + let mut steps = Vec::with_capacity(cmds.len()); + let mut dropped = Vec::new(); + for r in cmds { + let (params, gone) = portable(&r.cmd, &r.params)?; + for g in gone { + if !dropped.contains(&g) { + dropped.push(g); + } + } + steps.push(Step { cmd: r.cmd.clone(), params, label: label.to_string() }); + } + Ok((steps, dropped)) +} + +/// What dropped params mean for the step, in a sentence. +fn rewritten_note(dropped: &[String]) -> Option { + let layers = dropped.iter().any(|d| d.starts_with("layer")); + let objects = dropped.iter().any(|d| !d.starts_with("layer")); + match (objects, layers) { + (true, true) => Some("acts on the selection and the active layer".into()), + (true, false) => Some("acts on the selection".into()), + (false, true) => Some("acts on the active layer".into()), + (false, false) => None, + } +} + +fn history(s: &mut Session, _: &Value) -> Result { + let done = s.history().undo_len(); + let steps: Vec = s + .history() + .steps() + .enumerate() + .map(|(i, (label, cmds))| { + let mut v = json!({"index": i, "label": label, "undone": i >= done}); + match keep_step(label, cmds) { + Ok((steps, dropped)) => { + v["keep"] = json!(true); + v["commands"] = json!(steps.len()); + if let Some(note) = rewritten_note(&dropped) { + v["rewritten"] = json!(note); + } + } + Err(why) => { + v["keep"] = json!(false); + v["why"] = json!(why); + } + } + v + }) + .collect(); + Ok(json!({"steps": steps})) +} + +/// The steps the params ask to save: history steps by index, or steps given outright; and +/// what was rewritten, a sentence per step. +fn steps_to_save(s: &Session, p: &Value) -> Result<(Vec, Vec)> { + if let Some(v) = p.get("steps") { + return Ok((Macro::from_json(v, "")?.steps, Vec::new())); + } + let mut picked = opt_u64_list(p, "history")?.ok_or_else(|| EngineError::Param("pick the steps to keep: history (as macro.history lists them) or steps".into()))?; + picked.sort_unstable(); + picked.dedup(); + if picked.is_empty() { + return Err(EngineError::Param("pick at least one step to keep".into())); + } + let all: Vec<(&str, Option<&[Recorded]>)> = s.history().steps().collect(); + let mut steps = Vec::new(); + let mut notes = Vec::new(); + for i in picked { + let (label, cmds) = usize::try_from(i).ok().and_then(|i| all.get(i).copied()).ok_or_else(|| EngineError::Param(format!("there is no history step {i} (macro.history lists them)")))?; + let (kept, dropped) = keep_step(label, cmds).map_err(|why| EngineError::State(format!("step {} “{label}” can't be kept: {why}", i + 1)))?; + if let Some(note) = rewritten_note(&dropped) { + notes.push(json!({"index": i, "label": label, "note": note})); + } + steps.extend(kept); + if steps.len() > MAX_STEPS { + return Err(EngineError::State(format!("a saved command has at most {MAX_STEPS} steps"))); + } + } + Ok((steps, notes)) +} + +/// Adds `name` to the end of the folder's order (or leaves it where it is). +fn order_add(folder: &Path, name: &str) -> Result<()> { + let mut order = read_order(folder); + if !order.iter().any(|o| o.to_lowercase() == name.to_lowercase()) { + // The order holds every listed command, so a new one goes after all of them. + let (found, _) = saved_commands(folder); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + names.push(name.to_string()); + order = names; + } + write_order(folder, &order) +} + +fn write_macro(path: &Path, m: &Macro) -> Result<()> { + if let Some(dir) = path.parent() { + vfs::create_dir_all(dir)?; + } + let text = serde_json::to_string_pretty(&m.to_json()).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(path, text)?; + Ok(()) +} + +fn save(s: &mut Session, p: &Value) -> Result { + let path = target(p)?; + let (steps, rewritten) = steps_to_save(s, p)?; + if steps.is_empty() { + return Err(EngineError::Param("a saved command needs at least one step".into())); + } + let m = Macro { name: name_of(&path), steps }; + write_macro(&path, &m)?; + if let Some(dir) = path.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": path.display().to_string(), "steps": m.steps.len(), "rewritten": rewritten})) +} + +fn import(_: &mut Session, p: &Value) -> Result { + let to = import_target(p)?; + let from = PathBuf::from(str_req(p, "path")?); + let m = Macro { name: name_of(&to), ..load(&from)? }; + write_macro(&to, &m)?; + if let Some(dir) = to.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": to.display().to_string(), "steps": m.steps.len()})) +} + +fn existing(p: &Value) -> Result { + let path = target(p)?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + Ok(path) +} + +fn rename(_: &mut Session, p: &Value) -> Result { + let from = existing(p)?; + let dir = folder(p)?; + let to = command_path(&dir, str_req(p, "to")?)?; + let (old, new) = (name_of(&from), name_of(&to)); + if old == new { + return Ok(json!({"name": new, "from": old})); + } + // A change of case only is the same file on Windows and macOS. + if old.to_lowercase() != new.to_lowercase() && vfs::exists(&to) { + return Err(EngineError::State(format!("there is already a saved command “{new}”"))); + } + vfs::rename(&from, &to)?; + let mut order = read_order(&dir); + for o in &mut order { + if o.to_lowercase() == old.to_lowercase() { + o.clone_from(&new); + } + } + write_order(&dir, &order)?; + Ok(json!({"name": new, "from": old, "path": to.display().to_string()})) +} + +fn delete(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + vfs::remove_file(&path)?; + let order: Vec = read_order(&dir).into_iter().filter(|o| o.to_lowercase() != name.to_lowercase()).collect(); + write_order(&dir, &order)?; + Ok(json!({"deleted": name})) +} + +fn move_to(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + let index = opt_u64(p, "index")?.ok_or_else(|| EngineError::Param("give the new place: index (0-based)".into()))?; + let (found, _) = saved_commands(&dir); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + let at = usize::try_from(index).unwrap_or(usize::MAX).min(names.len()); + names.insert(at, name.clone()); + write_order(&dir, &names)?; + Ok(json!({"name": name, "index": at})) +} diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 5fa3167c..4b00ff27 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -56,6 +56,9 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { "swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"), "swatch" => Ok(()), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), + // Saved commands are files in your preferences (ADR 0097), and running one from a + // plug-in would let the two call each other. + "macro" => Err("plug-ins can't run, save or change saved commands"), "desktop" => Err("plug-ins can't change your applications menu or which app opens your files"), "control" => Err("plug-ins can't play the movie"), // A scene's guides are the document's (ADR 0076); whether rulers, grid and guides diff --git a/crates/engine/src/cmds_template.rs b/crates/engine/src/cmds_template.rs index 881eb2ba..17c0e2c8 100644 --- a/crates/engine/src/cmds_template.rs +++ b/crates/engine/src/cmds_template.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { } /// A name usable as a file or folder name on every system, or why not. -fn clean_name(raw: &str, what: &str) -> Result { +pub(crate) fn clean_name(raw: &str, what: &str) -> Result { let name = raw.trim(); if name.is_empty() { return Err(EngineError::Param(format!("give the {what} a name"))); diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 064a752b..f39c0c73 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -116,6 +116,25 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } + // Saved commands are files in your preferences (ADR 0097). + "macro.save" => { + let path = crate::cmds_macro::target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Saving the command")) + } + "macro.import" => { + let path = crate::cmds_macro::import_target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Adding the command")) + } + "macro.delete" => { + let path = crate::cmds_macro::target(p).ok()?; + let name = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + crate::vfs::is_file(&path).then(|| Confirmation { + title: "Delete saved command?".into(), + message: format!("The saved command “{name}” will be deleted from your commands. This cannot be undone."), + action: "Delete Command".into(), + irreversible: true, + }) + } // Brushes of your own live in your preferences, outside undo (ADR 0068). "brush.preset_delete" => { let name = p.get("name").and_then(Value::as_str)?; diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index a621124a..e62ab2e1 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -35,6 +35,89 @@ pub struct Snapshot { pub selection: crate::Selection, /// Estimated bytes this snapshot keeps alive that the neighbouring state does not share. pub bytes: usize, + /// The commands the step from this state ran, in order, as a saved command would run them + /// again (ADR 0097). `None`: they weren't kept (too many, or the step came from elsewhere). + pub commands: Option>, +} + +/// A command a history step ran: its id and params (ADR 0097). +#[derive(Clone, Debug, PartialEq)] +pub struct Recorded { + pub cmd: String, + pub params: serde_json::Value, + /// Roughly how much memory the params hold (their JSON's length). + pub bytes: usize, +} + +impl Recorded { + pub fn new(cmd: &str, params: &serde_json::Value) -> Recorded { + Recorded { cmd: cmd.to_string(), params: params.clone(), bytes: cmd.len() + params.to_string().len() } + } +} + +/// Most commands one step keeps: a longer step (a very long drag) can't be saved as a command. +pub const MAX_RECORDED: usize = 4096; +/// Most bytes of params one step keeps. +pub const MAX_RECORDED_BYTES: usize = 1 << 20; + +/// The commands run since the last step was recorded (ADR 0097). +#[derive(Clone, Debug, Default)] +pub(crate) struct Recording { + pub cmds: Vec, + pub bytes: usize, + /// More than [`MAX_RECORDED`] commands or [`MAX_RECORDED_BYTES`] bytes: none are kept. + pub overflow: bool, +} + +impl Recording { + /// Adds a command that changed the document. Moves in a row (a drag) add up into one. + pub fn push(&mut self, r: Recorded) { + if self.overflow { + return; + } + if let Some(last) = self.cmds.last_mut() + && let Some(sum) = merged_translate(last, &r) + { + *last = sum; + return; + } + self.bytes += r.bytes; + self.cmds.push(r); + if self.cmds.len() > MAX_RECORDED || self.bytes > MAX_RECORDED_BYTES { + self.overflow = true; + self.cmds = Vec::new(); + self.bytes = 0; + } + } + + pub fn truncate(&mut self, len: usize) { + if !self.overflow && len < self.cmds.len() { + self.cmds.truncate(len); + self.bytes = self.cmds.iter().map(|r| r.bytes).sum(); + } + } + + pub fn clear(&mut self) { + *self = Recording::default(); + } + + /// The commands for a step being recorded, leaving this empty. + pub fn take(&mut self) -> Option> { + let r = std::mem::take(self); + (!r.overflow).then(|| r.cmds.into()) + } +} + +/// Two `element.translate {dx, dy}` in a row as one, or `None`. +fn merged_translate(a: &Recorded, b: &Recorded) -> Option { + let plain = |r: &Recorded| { + let o = r.params.as_object()?; + (r.cmd == "element.translate" && o.len() == 2).then_some(())?; + Some((o.get("dx")?.as_f64()?, o.get("dy")?.as_f64()?)) + }; + let ((ax, ay), (bx, by)) = (plain(a)?, plain(b)?); + let (dx, dy) = (ax + bx, ay + by); + (dx.is_finite() && dy.is_finite()).then(|| Recorded::new("element.translate", &serde_json::json!({"dx": dx, "dy": dy}))) } /// Default memory budget for undo history. @@ -62,7 +145,7 @@ impl Default for History { impl History { /// Records `before` as an undo step leading to `current`, and clears redo. pub fn record(&mut self, mut before: Snapshot, current: &Document) { - before.bytes = unique_bytes(&before.doc, current); + before.bytes = unique_bytes(&before.doc, current) + before.commands.as_ref().map_or(0, |c| c.iter().map(|r| r.bytes).sum()); self.undo_bytes += before.bytes; self.undo.push_back(before); self.redo.clear(); @@ -85,6 +168,7 @@ impl History { self.undo_bytes = self.undo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.redo_bytes += current.bytes; self.redo.push(current); Some(s) @@ -96,6 +180,7 @@ impl History { self.redo_bytes = self.redo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.undo_bytes += current.bytes; self.undo.push_back(current); self.enforce_budget(); @@ -128,6 +213,12 @@ impl History { pub fn redo_labels(&self) -> impl Iterator { self.redo.iter().rev().map(|s| s.label.as_str()) } + /// Every step as the History panel lists it, oldest first: the steps that can be undone, + /// then the ones that can be redone (next to redo first), each with its label and the + /// commands it ran (ADR 0097). + pub fn steps(&self) -> impl Iterator)> { + self.undo.iter().chain(self.redo.iter().rev()).map(|s| (s.label.as_str(), s.commands.as_deref())) + } /// Estimated memory held by history. pub fn bytes(&self) -> usize { self.undo_bytes + self.redo_bytes diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ce55f0aa..748bdaa8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ mod cmds_retime; mod cmds_hints; mod cmds_layer; pub mod cmds_library; +pub mod cmds_macro; pub mod cmds_paint; mod cmds_path; pub mod cmds_raw; @@ -180,6 +181,7 @@ pub fn commands() -> Vec { v.extend(cmds_sound::specs()); v.extend(cmds_actions::specs()); v.extend(cmds_script::specs()); + v.extend(cmds_macro::specs()); v } @@ -198,7 +200,7 @@ pub fn find_command(id: &str) -> Option { commands().into_iter().find(|c| c.id == id) } -pub use history::{Snapshot, StateId}; +pub use history::{Recorded, Snapshot, StateId}; pub use selection::Selection; pub use snap::{Accuracy, SnapTo, ViewAids}; pub use cmds_layer::LAYER_COLORS; @@ -380,6 +382,13 @@ pub struct Session { pub filter_clipboard: Option>, /// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture. pub(crate) envelope: Option, + /// The commands run since the last undo step was recorded, which the next step keeps so it + /// can be saved as a command (ADR 0097). + rec: history::Recording, + /// How many commands were recorded when the open gesture began (a revert goes back there). + gesture_rec: usize, + /// What the running command records instead of itself (`macro.run` records its steps). + pub(crate) record_as: Option>, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -455,6 +464,9 @@ impl Session { filter_presets: filter_library::FilterLibrary::default(), filter_clipboard: None, envelope: None, + rec: history::Recording::default(), + gesture_rec: 0, + record_as: None, } } @@ -497,6 +509,7 @@ impl Session { } // On a marquee's cut, the step (if the gesture makes one) starts from before the cut. let cut = self.live_cut().map(|p| (history::Snapshot { label: label.to_string(), ..p.before.clone() }, p.cut.clone())); + self.gesture_rec = self.rec.cmds.len(); match cut { Some((before, doc)) => { self.gesture_cut = Some(doc); @@ -520,8 +533,17 @@ impl Session { } self.provisional = None; } + self.record(before); + } + + /// Records `before` as the undo step to the current document, with the commands run since + /// the last step; an unchanged document records nothing and forgets them. + fn record(&mut self, mut before: Snapshot) { if self.doc != before.doc { + before.commands = self.rec.take(); self.history.record(before, &self.doc); + } else { + self.rec.clear(); } } @@ -565,10 +587,7 @@ impl Session { { return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message))); } - // A group open for editing is one layer and one frame (ADR 0073). - if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { - return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); - } + self.group_allows(&spec)?; self.settle_cut(id, params); if !spec.mutates { let r = (spec.run)(self, params); @@ -588,7 +607,9 @@ impl Session { self.pending_cut = None; self.motion_edit = None; self.step_label = None; + self.record_as = None; let result = (spec.run)(self, params); + let record_as = self.record_as.take(); // Edits to a motion tween's target become property keys (auto-key). if let Some(edit) = self.motion_edit.take() && result.is_ok() @@ -610,6 +631,10 @@ impl Session { if changed { self.state = history::fresh_state(); self.revision += 1; + match record_as { + Some(steps) => steps.into_iter().for_each(|r| self.rec.push(r)), + None => self.rec.push(Recorded::new(id, params)), + } match pending.filter(|_| self.gesture.is_none()) { // A marquee's cut: provisional, no step (yet). Some((origin, inside)) => self.begin_cut(before, cut.is_some(), origin, inside), @@ -617,8 +642,8 @@ impl Session { if cut.is_some() { self.provisional = None; } - if self.gesture.is_none() && self.doc != before.doc { - self.history.record(before, &self.doc); + if self.gesture.is_none() { + self.record(before); } } } @@ -635,6 +660,16 @@ impl Session { } } + /// A group open for editing is one layer and one frame (ADR 0073): commands that change + /// the timeline are refused inside it. + fn group_allows(&self, spec: &CommandSpec) -> Result<()> { + let id = spec.id; + if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { + return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); + } + Ok(()) + } + /// Inside a group (ADR 0073) the playhead stays on its only frame. fn hold_group_frame(&mut self) { if self.frame != 0 && self.editing_group() { @@ -699,6 +734,8 @@ impl Session { if self.saved_state == Some(p.state) { self.saved_state = Some(p.before.state); } + // The cut's commands went with it. + self.rec.clear(); self.doc = p.before.doc; self.state = p.before.state; self.selection = sel; @@ -720,9 +757,19 @@ impl Session { if !spec.mutates { return (spec.run)(self, params); } + self.group_allows(&spec)?; let before = self.snapshot(""); self.dl_cache.replace(None); + // Each command's edits to a motion tween's target become its keys, as when it runs on + // its own (the next one may work at another frame). + let outer = self.motion_edit.take(); let result = (spec.run)(self, params); + if let Some(edit) = self.motion_edit.take() + && result.is_ok() + { + cmds_motion::finish_edit(self, edit); + } + self.motion_edit = outer; self.dl_cache.replace(None); self.pending_cut = None; match result { @@ -752,14 +799,15 @@ impl Session { if g.doc == self.doc && g.selection == self.selection { return; } - let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; + let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0, commands: None }; + self.rec.truncate(self.gesture_rec); self.restore(back); self.revision += 1; self.fix_selection(); } fn snapshot(&self, label: &str) -> Snapshot { - Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } + Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0, commands: None } } fn restore(&mut self, s: Snapshot) { @@ -790,6 +838,7 @@ impl Session { pub fn undo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?; let label = s.label.clone(); @@ -802,6 +851,7 @@ impl Session { pub fn redo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?; let label = s.label.clone(); @@ -1128,6 +1178,8 @@ mod motion_pin_tests; #[cfg(test)] mod plugin_tests; #[cfg(test)] +mod macro_tests; +#[cfg(test)] mod plugin_kinds_tests; #[cfg(test)] mod tests_sound; diff --git a/crates/engine/src/macro_tests.rs b/crates/engine/src/macro_tests.rs new file mode 100644 index 00000000..e41ca157 --- /dev/null +++ b/crates/engine/src/macro_tests.rs @@ -0,0 +1,353 @@ +//! Saved commands (ADR 0097): what history records, Save As Command from history steps, a run +//! as one transactional undo step, the folder's order, the policy, and hostile files. + +use super::*; +use crate::cmds_macro::{self, Macro, macro_may_call}; +use serde_json::json; +use std::path::PathBuf; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-macros-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The elements on the active layer at the playhead, without their ids (which differ between +/// documents), as JSON. +fn looks(s: &Session) -> Vec { + s.visible_elements() + .iter() + .map(|e| { + let mut v = serde_json::to_value(&**e).unwrap(); + v.as_object_mut().unwrap().remove("id"); + v + }) + .collect() +} + +/// A rectangle, selected. +fn with_rect(x: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": x, "y": 20, "w": 80, "h": 40})); + run(&mut s, "edit.select_all", json!({})); + s +} + +/// Three edits on the selection: a drag (many moves in one step), a quarter turn and a fade. +fn edit(s: &mut Session) { + s.begin_gesture("Move"); + for _ in 0..30 { + run(s, "element.translate", json!({"dx": 2, "dy": -1})); + } + s.end_gesture(); + run(s, "modify.rotate_cw", json!({})); + run(s, "element.set_color_effect", json!({"style": "alpha", "alpha": 40})); +} + +#[test] +fn history_keeps_each_steps_commands_and_a_drag_as_one_move() { + let mut s = with_rect(10.0); + edit(&mut s); + let steps: Vec<(String, Option>)> = s.history().steps().map(|(l, c)| (l.to_string(), c.map(<[Recorded]>::to_vec))).collect(); + assert_eq!(steps.len(), 4, "{:?}", steps.iter().map(|s| &s.0).collect::>()); + let cmds = |i: usize| steps[i].1.clone().unwrap(); + assert_eq!(cmds(0)[0].cmd, "draw.rect"); + // Thirty moves in a drag add up to one. + assert_eq!(cmds(1).len(), 1); + assert_eq!(cmds(1)[0].params, json!({"dx": 60.0, "dy": -30.0})); + assert_eq!(cmds(2)[0].cmd, "modify.rotate_cw"); + assert_eq!(cmds(3)[0].params, json!({"style": "alpha", "alpha": 40})); + // Undo and redo carry them along. + s.undo().unwrap(); + s.redo().unwrap(); + assert_eq!(s.history().steps().nth(3).and_then(|(_, c)| c).map(<[Recorded]>::len), Some(1)); +} + +#[test] +fn a_live_preview_records_only_what_it_ended_on() { + let mut s = with_rect(10.0); + s.begin_gesture("Nudge"); + run(&mut s, "modify.rotate_cw", json!({})); + s.revert_gesture(); + run(&mut s, "element.translate", json!({"dx": 5, "dy": 0})); + s.end_gesture(); + let last = s.history().steps().last().and_then(|(_, c)| c.map(<[Recorded]>::to_vec)).unwrap(); + assert_eq!(last.iter().map(|r| r.cmd.as_str()).collect::>(), ["element.translate"]); +} + +#[test] +fn record_and_replay_equals_the_original_edits_on_a_fresh_selection() { + let dir = temp_dir("replay"); + let folder = dir.display().to_string(); + let mut original = with_rect(10.0); + edit(&mut original); + let listed = run(&mut original, "macro.history", json!({})); + let keep: Vec = listed["steps"].as_array().unwrap().iter().map(|v| v["keep"].as_bool().unwrap()).collect(); + assert_eq!(keep, [true, true, true, true], "{listed}"); + let saved = run(&mut original, "macro.save", json!({"folder": folder, "name": "Turn and Fade", "history": [1, 2, 3]})); + assert_eq!(saved["steps"], 3); + assert!(dir.join("Turn and Fade.json").is_file()); + + // Elsewhere: another document, another rectangle drawn the same way but with other ids. + let mut other = Session::default(); + run(&mut other, "draw.ellipse", json!({"x": 300, "y": 300, "w": 10, "h": 10})); + run(&mut other, "edit.deselect", json!({})); + run(&mut other, "draw.rect", json!({"x": 10, "y": 20, "w": 80, "h": 40})); + let rect = other.visible_elements().last().unwrap().id; + run(&mut other, "element.select", json!({"ids": [rect.0]})); + let steps = other.history_len(); + let before_run = looks(&other); + let oval = before_run.first().cloned(); + let v = run(&mut other, "macro.run", json!({"folder": folder, "name": "Turn and Fade"})); + assert_eq!(v["steps"], 3); + assert_eq!(other.history_len(), steps + 1, "one undo step"); + assert_eq!(other.undo_label(), Some("Turn and Fade")); + let mine = looks(&other); + assert_eq!(mine.last(), looks(&original).last(), "the rectangle ends up as in the original"); + // The oval, not selected, is untouched. + assert_eq!(mine.first().cloned(), oval); + // One undo takes the whole run back. + other.undo().unwrap(); + assert_eq!(looks(&other), before_run); + // And the run's step can itself be saved again: history keeps its steps, not macro.run. + other.redo().unwrap(); + let again = run(&mut other, "macro.history", json!({})); + let last = again["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!((last["keep"].as_bool(), last["commands"].as_u64()), (Some(true), Some(3)), "{last}"); +} + +#[test] +fn a_failing_step_changes_nothing_and_is_named() { + let mut s = with_rect(10.0); + let (doc, state, steps) = (s.doc.clone(), s.state, s.history_len()); + let steps_json = json!([ + {"cmd": "element.translate", "params": {"dx": 10, "dy": 0}}, + {"cmd": "modify.rotate_cw"}, + {"cmd": "layer.set_height", "params": {"height": 7}, "label": "Taller row"}, + ]); + let e = s.execute("macro.run", &json!({"name": "Broken", "steps": steps_json})).unwrap_err().to_string(); + assert!(e.contains("“Broken” stopped at step 3 of 3 (Taller row)") && e.contains("Nothing was changed"), "{e}"); + assert!(s.doc == doc, "the document is as it was"); + assert_eq!((s.state, s.history_len()), (state, steps)); + assert_eq!(s.selection.len(), 1, "the selection too"); +} + +#[test] +fn steps_tied_to_this_document_act_on_the_selection_or_say_why_they_cant_be_kept() { + let mut s = with_rect(10.0); + let layer = s.layer.0; + let id = s.selection.id_list()[0]; + // A layer named by id: the step acts on the active layer instead. + run(&mut s, "layer.set_color", json!({"color": "#ff0000", "layer": layer})); + // An element named by id where the command can take the selection instead. + run(&mut s, "stroke.set_profile", json!({"profile": "taper_both", "id": id})); + // An element named by id where the command can't do without it. + run(&mut s, "path.move_points", json!({"id": id, "points": [[0, 0]], "dx": 3, "dy": 0})); + let v = run(&mut s, "macro.history", json!({})); + let steps = v["steps"].as_array().unwrap(); + assert_eq!(steps[1]["rewritten"], "acts on the active layer", "{v}"); + assert_eq!(steps[2]["rewritten"], "acts on the selection", "{v}"); + assert_eq!(steps[3]["keep"], false); + assert!(steps[3]["why"].as_str().unwrap().contains("particular objects"), "{v}"); + let dir = temp_dir("rewrite"); + let folder = dir.display().to_string(); + let e = s.execute("macro.save", &json!({"folder": folder, "name": "Mixed", "history": [1, 2, 3]})).unwrap_err().to_string(); + assert!(e.starts_with("step 4 “") && e.contains("can't be kept"), "{e}"); + assert!(!dir.join("Mixed.json").exists(), "nothing saved"); + let saved = run(&mut s, "macro.save", json!({"folder": folder, "name": "Mixed", "history": [2, 1]})); + assert_eq!(saved["rewritten"].as_array().map(Vec::len), Some(2)); + let m = cmds_macro::load(&dir.join("Mixed.json")).unwrap(); + assert_eq!(m.steps[0].params, json!({"color": "#ff0000"}), "in history order, the layer's id gone"); + assert_eq!(m.steps[1].params, json!({"profile": "taper_both"})); +} + +#[test] +fn saved_commands_call_only_what_a_plug_in_may() { + assert!(macro_may_call("element.translate").is_ok()); + for id in ["file.save", "edit.paste", "edit.undo", "plugin.run", "macro.run", "macro.delete", "prefs.set", "view.rulers"] { + assert!(macro_may_call(id).is_err(), "{id}"); + } + // Plug-ins can't reach saved commands either, so the two never call each other. + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + assert!(crate::cmds_plugin::plugin_may_call(c.id).is_err(), "{}", c.id); + } + for (step, why) in [(json!({"cmd": "file.save", "params": {"path": "x.anicraft"}}), "files"), (json!({"cmd": "macro.run", "params": {"path": "x.json"}}), "saved commands"), (json!({"cmd": "no.such"}), "unknown command")] { + let e = Macro::from_json(&json!([step]), "x").unwrap_err().to_string(); + assert!(e.contains("step 1") && e.contains(why), "{e}"); + } + // A history step that used the clipboard can't be kept. + let mut s = with_rect(10.0); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.paste", json!({})); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("clipboard"), "{last}"); +} + +#[test] +fn the_folder_keeps_order_renames_and_deletes_only_when_confirmed() { + let dir = temp_dir("manage"); + let folder = dir.display().to_string(); + let mut s = with_rect(10.0); + run(&mut s, "modify.rotate_cw", json!({})); + for name in ["Alpha", "Bravo", "Charlie"] { + run(&mut s, "macro.save", json!({"folder": folder, "name": name, "history": [1]})); + } + let names = |s: &mut Session| -> Vec { run(s, "macro.list", json!({"folder": folder}))["commands"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap().to_string()).collect() }; + assert_eq!(names(&mut s), ["Alpha", "Bravo", "Charlie"], "in the order saved"); + run(&mut s, "macro.move", json!({"folder": folder, "name": "Charlie", "index": 0})); + assert_eq!(names(&mut s), ["Charlie", "Alpha", "Bravo"]); + run(&mut s, "macro.rename", json!({"folder": folder, "name": "Alpha", "to": "Delta"})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a rename keeps its place"); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "Bravo"})).unwrap_err().to_string().contains("already")); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "a/b"})).is_err()); + // Saving over one asks first; deleting always does (a file: undo can't bring it back). + assert!(matches!(s.execute("macro.save", &json!({"folder": folder, "name": "Bravo", "history": [1]})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.save", json!({"folder": folder, "name": "Bravo", "history": [0, 1], "confirm": true})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a replaced command keeps its place"); + assert!(matches!(s.execute("macro.delete", &json!({"folder": folder, "name": "Charlie"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.delete", json!({"folder": folder, "name": "Charlie", "confirm": true})); + assert_eq!(names(&mut s), ["Delta", "Bravo"]); + // A shared file comes in under its own name, checked. + let shared = dir.join("shared"); + std::fs::create_dir_all(&shared).unwrap(); + std::fs::write(shared.join("Spin.json"), r#"[{"cmd": "modify.rotate_cw"}, {"command": "modify.rotate_cw"}]"#).unwrap(); + let v = run(&mut s, "macro.import", json!({"folder": folder, "path": shared.join("Spin.json").display().to_string()})); + assert_eq!(v["steps"], 2); + assert_eq!(names(&mut s), ["Delta", "Bravo", "Spin"]); + // ...and runs straight from where it is (Run Command…). + let before = s.visible_elements()[0].transform; + run(&mut s, "macro.run", json!({"path": shared.join("Spin.json").display().to_string()})); + assert_eq!(s.undo_label(), Some("Spin")); + assert_ne!(s.visible_elements()[0].transform, before); + // Files that aren't saved commands are listed as problems, never as commands. + std::fs::write(dir.join("junk.json"), "{nope").unwrap(); + let v = run(&mut s, "macro.list", json!({"folder": folder})); + assert_eq!(v["problems"][0]["file"], "junk.json"); + assert_eq!(names(&mut s).len(), 3); +} + +#[test] +fn hostile_saved_command_files_never_panic() { + let dir = temp_dir("hostile"); + let deep = format!("{}{}", "[".repeat(5000), "]".repeat(5000)); + let many = serde_json::to_string(&vec![json!({"cmd": "modify.rotate_cw"}); cmds_macro::MAX_STEPS + 1]).unwrap(); + let mut bodies: Vec> = vec![ + Vec::new(), + b"\xef\xbb\xbf".to_vec(), + b"\xff\xfe\x00\x01garbage".to_vec(), + deep.into_bytes(), + many.into_bytes(), + "x".repeat((cmds_macro::MAX_FILE_BYTES + 10) as usize).into_bytes(), + ]; + for text in [ + "null", + "7", + "\"steps\"", + "{}", + r#"{"format": "something-else", "steps": []}"#, + r#"{"format": "anicraft-command", "version": 99, "steps": []}"#, + r#"{"format": "anicraft-command", "version": -1, "steps": []}"#, + r#"{"steps": "no"}"#, + r#"{"steps": [7, null, "x"]}"#, + r#"{"steps": [{"cmd": 7}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": [1, 2]}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": 1e308, "dy": -1e308}}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": "a"}}]}"#, + r#"{"steps": [{"cmd": "draw.rect", "params": {"x": 0, "y": 0, "w": 1e30, "h": -1}, "label": 5}]}"#, + r#"{"steps": [{"cmd": "layer.delete"}, {"cmd": "layer.delete"}, {"cmd": "layer.delete"}]}"#, + r#"{"steps": [{"cmd": "edit.undo"}]}"#, + r#"{"steps": [{"cmd": "file.export_png", "params": {"path": "/tmp/x.png"}}]}"#, + r#"{"steps": [{"cmd": "macro.run", "params": {"path": "self.json"}}]}"#, + r#"{"steps": [{"cmd": "plugin.run", "params": {"id": "x"}}]}"#, + ] { + bodies.push(text.as_bytes().to_vec()); + } + bodies.push(json!({"steps": [{"cmd": "modify.rotate_cw", "label": "\u{0}\u{202e} evil"}]}).to_string().into_bytes()); + // Truncations of a good file at every byte, and a few flipped bytes. + let good = serde_json::to_vec(&Macro { name: String::new(), steps: vec![cmds_macro::Step { cmd: "element.translate".into(), params: json!({"dx": 3, "dy": 4}), label: "Move".into() }] }.to_json()).unwrap(); + for i in 0..good.len() { + bodies.push(good[..i].to_vec()); + let mut flipped = good.clone(); + flipped[i] ^= 0x5a; + bodies.push(flipped); + } + let mut s = with_rect(10.0); + for (i, body) in bodies.iter().enumerate() { + let path = dir.join(format!("h{i}.json")); + std::fs::write(&path, body).unwrap(); + let (doc, steps) = (s.doc.clone(), s.history_len()); + match s.execute("macro.run", &json!({"path": path.display().to_string()})) { + Ok(_) => assert!(s.history_len() <= steps + 1), + Err(_) => assert!(s.doc == doc && s.history_len() == steps, "a refused file changed the document"), + } + let _ = s.execute("macro.import", &json!({"folder": dir.join("in").display().to_string(), "path": path.display().to_string(), "confirm": true})); + } + // Listing a folder full of them never panics either. + let v = run(&mut s, "macro.list", json!({"folder": dir.display().to_string()})); + assert!(!v["problems"].as_array().unwrap().is_empty()); + // Hostile params, with every folder inside the temporary one. + let folder = dir.display().to_string(); + for p in [ + Value::Null, + json!({"folder": folder}), + json!({"folder": folder, "name": "", "history": [u64::MAX]}), + json!({"folder": folder, "name": "x", "history": "all"}), + json!({"folder": folder, "name": "x", "history": []}), + json!({"folder": folder, "name": "..", "history": [0]}), + json!({"folder": folder, "name": "CON", "history": [0]}), + json!({"folder": folder, "name": "a", "to": "", "index": u64::MAX}), + json!({"folder": "", "name": "a"}), + json!({"steps": {"steps": []}, "name": "\u{0}".repeat(500)}), + json!({"steps": []}), + json!({"path": folder}), + ] { + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + let _ = s.execute(c.id, &p); + } + } +} + +#[test] +fn a_step_too_long_to_keep_says_so() { + let mut s = with_rect(10.0); + s.begin_gesture("Scribble"); + for i in 0..(history::MAX_RECORDED + 2) { + // Alternating commands, so they don't add up into one. + let id = if i % 2 == 0 { "element.translate" } else { "modify.rotate_cw" }; + run(&mut s, id, json!({"dx": 1, "dy": 0, "snap": 0})); + } + s.end_gesture(); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("too many"), "{last}"); +} + +#[test] +fn steps_run_inside_a_motion_tween_key_it_as_on_their_own() { + // Each step's edit becomes the tween's keys at the frame it ran at. + let tweened = || { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s + }; + let (mut a, mut b) = (tweened(), tweened()); + a.set_frame(5); + run(&mut a, "edit.select_all", json!({})); + run(&mut a, "element.translate", json!({"dx": 40, "dy": 0})); + b.set_frame(5); + run(&mut b, "edit.select_all", json!({})); + run(&mut b, "macro.run", json!({"steps": [{"cmd": "element.translate", "params": {"dx": 40, "dy": 0}}]})); + assert!(a.doc == b.doc, "a step in a saved command keys the tween as the command does alone"); +} diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index 73944b76..454a95a6 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -179,7 +179,7 @@ fn every_command_namespace_has_a_plugin_policy() { let ns = c.id.split('.').next().unwrap_or(""); let verdict = plugin_may_call(c.id); match ns { - "file" | "plugin" | "control" | "prefs" | "desktop" => assert!(verdict.is_err(), "{} must be refused", c.id), + "file" | "plugin" | "control" | "prefs" | "desktop" | "macro" => assert!(verdict.is_err(), "{} must be refused", c.id), // Publish Settings (ADR 0060): read yes, change no (it says what Publish writes). "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), // Brushes (ADR 0068): list yes; your own brushes and brush set files no. From 98bb6e98e55b7b43e810e1ad89ed89c7e5bc6281 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:56:16 -0700 Subject: [PATCH 056/570] feat(app): Save As Command in History, saved commands in the Commands menu, Manage Saved Commands (M6) --- crates/guide/src/lib.rs | 1 + docs/guide/reference/commands.md | 18 +- src/app.rs | 72 ++++- src/dialogs.rs | 14 + src/keymap.rs | 70 ++++- src/macros_ui.rs | 444 +++++++++++++++++++++++++++++++ src/macros_ui_tests.rs | 115 ++++++++ src/main.rs | 3 + src/panels.rs | 64 ++++- src/platform.rs | 18 +- src/plugins_ui.rs | 2 + 11 files changed, 800 insertions(+), 21 deletions(-) create mode 100644 src/macros_ui.rs create mode 100644 src/macros_ui_tests.rs diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs index f525299f..bb0e15c2 100644 --- a/crates/guide/src/lib.rs +++ b/crates/guide/src/lib.rs @@ -57,6 +57,7 @@ pub const PAGES: &[Page] = &[ page!("opening-animate-files.md"), page!("preferences-shortcuts-accessibility.md"), page!("plugins.md"), + page!("saved-commands.md"), page!("working-headless.md"), page!("troubleshooting-and-faq.md"), page!("coming-from-animate.md"), diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index c68a55f3..6bc4801f 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -1,6 +1,6 @@ # Command reference -Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 352 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). +Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 360 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). This page is generated from the command registry, so it always matches the version of AniCraft it came with. @@ -249,6 +249,10 @@ This page is generated from the command registry, so it always matches the versi Parameters: `{} lists the installed plug-ins (the app shows them in a window)` - **Reload Plug-ins** `plugin.reload` Parameters: `{folder? (makes it the plug-ins folder first)} re-reads every .wasm in the plug-ins folder` +- **Run Command…** `macro.run` · changes the document + Parameters: `{name + folder (a saved command) | path (a saved command's file, or a JSON array of {cmd, params}) | steps: [{cmd, params?, label?}], name? (for steps)} → {name, steps, results}: runs the steps in order as one undo step named after it. At the first step that fails nothing is changed and the error names the step. Steps may call what a plug-in may, never macro.*` +- **Manage Saved Commands…** `macro.list` + Parameters: `{folder} → {commands: [{name, path, steps}], problems: [{file, error}]}: the saved commands in the folder, in their order (the app shows them in a window)` ## Control @@ -733,3 +737,15 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: ``{text: the script, language?: actionscript3|actionscript1or2|other (default actionscript3)} whether it would run (the ActionScript 3.0 subset, ADR 0013), its problems with line and column, what is ignored, the names it takes from other frames of its timeline (`uses`), and what it compiles to (`steps`, `program`); changes nothing`` - **Set Script Class** `script.set_class` · changes the document Parameters: `{symbol?: id (default: the document), class: dotted class name ("" clears), base?: the class it extends} sets a symbol's linkage class, or the document class; kept as text, not run` +- **List History Steps** `macro.history` + Parameters: ``{} → {steps: [{index, label, undone, keep, commands?, why?, rewritten?}]}: every undo-history step as Save As Command keeps it: `keep` false says `why` it can't be kept; `rewritten` names params dropped so the step acts on the selection or active layer`` +- **Save As Command…** `macro.save` + Parameters: `{folder, name, history: [index, ..] (as macro.history lists them) | steps: [{cmd, params?, label?}], confirm? (to replace a saved command of that name)} → {name, path, steps, rewritten}: keeps the steps as /.json, last in the list` +- **Rename Saved Command** `macro.rename` + Parameters: `{folder, name, to} → {name, from, path}: renames a saved command (its file); its place in the list stays` +- **Delete Saved Command** `macro.delete` + Parameters: `{folder, name, confirm}: deletes a saved command's file (cannot be undone)` +- **Move Saved Command** `macro.move` + Parameters: `{folder, name, index (its new place in the list, 0-based)}` +- **Add Saved Command from File** `macro.import` + Parameters: `{folder, path (a saved command's file), name? (default: the file's), confirm? (to replace one of that name)} → {name, path, steps}: checks it and copies it in, last in the list` diff --git a/src/app.rs b/src/app.rs index da2d4af3..70002f13 100644 --- a/src/app.rs +++ b/src/app.rs @@ -579,6 +579,8 @@ pub struct App { pub thumbs: crate::recent::Thumbs, /// Templates: their pictures, the user's list and the Save as Template dialog (ADR 0065). pub templates: crate::templates::Templates, + /// Saved commands (ADR 0097): the folder's list, the History panel's picks, their windows. + pub macros: crate::macros_ui::Macros, } /// How often (seconds) the system's contrast and light or dark setting are asked again (ADR 0064). @@ -797,6 +799,7 @@ impl App { drop: Default::default(), thumbs: Default::default(), templates: Default::default(), + macros: Default::default(), }; app.apply_prefs(ctx); app.decode_sounds(); @@ -805,6 +808,7 @@ impl App { app.status_err(e); } crate::plugins_ui::load_at_start(&mut app); + crate::macros_ui::rescan(&mut app); #[cfg(not(target_arch = "wasm32"))] crate::desktop_ui::at_start(&mut app); app @@ -901,8 +905,7 @@ impl App { ctx.set_zoom_factor(self.prefs.ui_scale); theme::apply_palette(ctx, self.prefs.palette(self.system_look)); crate::onion::refresh_colors(self); - self.keymap = keymap::Keymap::new(&self.prefs.shortcuts); - self.shortcuts = self.keymap.table(); + self.refresh_keymap(); let wants_system = [&self.prefs.ui_font, &self.prefs.data_font].iter().any(|f| matches!(f, prefs::FontChoice::System(_))); if wants_system && self.system_fonts.is_none() { self.scan_system_fonts(); @@ -963,6 +966,12 @@ impl App { /// Changes preferences: applies them live and saves them. /// Writes the preferences as they are (a setting changed in place, such as the volume). + /// The shortcut map again, from the preferences and the saved commands listed (ADR 0097). + pub fn refresh_keymap(&mut self) { + self.keymap = keymap::Keymap::new(&self.prefs.shortcuts); + self.shortcuts = self.keymap.table(); + } + pub fn save_prefs(&mut self) { if self.shot.is_none() && let Err(e) = self.prefs.save() @@ -1139,6 +1148,37 @@ impl App { } Some("palette") => self.palette = Some(dialogs::Palette { query: "key".into(), selected: 0 }), Some("shortcuts") => self.show_shortcuts = true, + Some("savecommand") | Some("managecommands") => { + // Saved commands (ADR 0097): three edits on the sample's selection, picked in the + // History panel with Save As Command open; or a few saved commands, managed. + self.tool = Tool::Select; + self.run("edit.select_all", json!({})); + self.run("modify.rotate_cw", json!({})); + self.run("element.set_color_effect", json!({"style": "alpha", "alpha": 60})); + self.run("element.translate", json!({"dx": 24, "dy": -12})); + if !self.panel_visible(crate::dock::Panel::History) { + self.toggle_panel(crate::dock::Panel::History); + } + let n = self.s.history_len(); + for i in n.saturating_sub(3)..n { + crate::macros_ui::pick(self, i, true, false); + } + if which == Some("savecommand") { + crate::macros_ui::open_save(self); + if let Some(d) = self.macros.save.as_mut() { + d.name = "Turn, Fade and Nudge".into(); // i18n-exempt: a sample name a user would type + } + } else if let Some(folder) = crate::macros_ui::folder(self) { + let f = folder.display().to_string(); + for (name, steps) in [("Turn, Fade and Nudge", json!([n - 3, n - 2, n - 1])), ("Quarter Turn", json!([n - 3])), ("Fade to 60 %", json!([n - 2]))] { + let _ = self.s.execute("macro.save", &json!({"folder": f, "name": name, "history": steps, "confirm": true})); + } + crate::macros_ui::clear_picks(self); + let id = crate::keymap::macro_id("Quarter Turn"); + self.prefs.shortcuts.insert(id, vec!["Ctrl+Alt+R".into()]); + crate::macros_ui::open_manage(self); + } + } Some("lastscene") => { let last = self.s.doc.scenes.len().saturating_sub(1); self.run("scene.select", json!({"scene": last})); @@ -2638,7 +2678,14 @@ impl App { /// The single entry point for user-initiated commands: asks first when the engine says the /// command needs confirmation (ADR 0004), otherwise runs it. - pub fn request(&mut self, id: &str, params: Value) { + pub fn request(&mut self, id: &str, mut params: Value) { + // A saved command from a file goes into the user's commands folder (ADR 0097). + if id == "macro.import" + && params.get("folder").is_none() + && let (Some(o), Some(f)) = (params.as_object_mut(), crate::macros_ui::folder(self)) + { + o.insert("folder".into(), json!(f.display().to_string())); + } if let Some(c) = self.s.confirmation(id, ¶ms) && (c.irreversible || !self.skip_confirm.contains(id)) { @@ -2843,6 +2890,7 @@ impl App { }); } "plugin.run" | "plugin.install" | "plugin.remove" | "plugin.reload" => crate::plugins_ui::status(self, id, v), + id if id.starts_with("macro.") => crate::macros_ui::done(self, id, v), "timeline.remove_frame" => { let n = v["removed"].as_u64().unwrap_or(1); self.status_ok(if n == 1 { tr!("Removed frame — {undo} to undo", undo = self.undo_key()).to_string() } else { trn!("Removed {n} frame — {undo} to undo", "Removed {n} frames — {undo} to undo", n, undo = self.undo_key()) }); @@ -2931,6 +2979,16 @@ impl App { self.show_plugins = true; return; } + if id == "macro.list" { + // Commands › Manage Saved Commands (ADR 0097; headless, the command lists them). + crate::macros_ui::open_manage(self); + return; + } + if id == "macro.save" { + // Save As Command, for the steps picked in the History panel. + crate::macros_ui::open_save(self); + return; + } if id == "layer.set_properties" { // Modify › Timeline › Layer Properties: the dialog for the active layer. crate::layer_props::open(self, None); @@ -2989,6 +3047,9 @@ impl App { "file.import_to_library" => Some((tr_noop!("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)"), "path", "sound.wav".to_string())), "file.import" => Some((tr_noop!("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)"), "path", "drawing.svg".to_string())), "plugin.install" => Some((tr_noop!("Install plug-in (.wasm file)"), "path", "plugin.wasm".to_string())), + // Saved commands (ADR 0097): run a file, or copy one into your commands. + "macro.run" => Some((tr_noop!("Run a saved command (a .json file)"), "path", "command.json".to_string())), + "macro.import" => Some((tr_noop!("Add a saved command (a .json file)"), "path", "command.json".to_string())), // A brush set (ADR 0068): your brushes as a small JSON file. "brush.preset_export" => Some((tr_noop!("Export your brushes (a brush set file)"), "path", "brushes.json".to_string())), "brush.preset_import" => Some((tr_noop!("Import brushes (a brush set file)"), "path", "brushes.json".to_string())), @@ -3001,7 +3062,7 @@ impl App { _ => None, }; if let Some((title, key, text)) = prompt { - let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "plugin.install" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import")); + let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "plugin.install" | "macro.run" | "macro.import" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import")); if is_file && platform::WEB && platform::reads_file(id) { // The browser's file picker (ADR 0036). The file arrives on a later frame // (`open_picked`); a save or export asks for the download's name below. @@ -3330,6 +3391,8 @@ impl App { "view.brush_smaller" => crate::brushtool::resize(self, false), "view.brush_larger" => crate::brushtool::resize(self, true), id if id.starts_with("tool.") => tool = keymap::tool_for(id).or(tool), + // A saved command's own key (ADR 0097). + id if keymap::macro_name(id).is_some() => crate::macros_ui::run_saved(self, keymap::macro_name(id).unwrap_or("")), _ => self.invoke(id), } } @@ -3768,6 +3831,7 @@ impl App { crate::plugin_export_ui::show(self, &ctx); crate::dock_float::floating(self, &ctx); crate::workspaces_window::show(self, &ctx); + crate::macros_ui::show(self, &ctx); crate::find_panel::show(self, &ctx); crate::brush_panel::show(self, &ctx); crate::publish_panel::show(self, &ctx); diff --git a/src/dialogs.rs b/src/dialogs.rs index 27b94fea..28ba5e11 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -834,6 +834,20 @@ fn take_key_press(ctx: &egui::Context) -> Option<(egui::Modifiers, Key)> { }) } +/// Opens the shortcut editor filtered to `filter` and waiting for a new key for `id` (Manage +/// Saved Commands' Shortcut…, ADR 0097). +pub(crate) fn shortcuts_for(app: &mut App, ctx: &egui::Context, filter: &str, id: &'static str) { + let state_id = egui::Id::new("shortcut_editor"); + let mut st: SheetState = ctx.data_mut(|d| d.get_temp(state_id).unwrap_or_default()); + st.filter = filter.to_string(); + st.notice = None; + st.steal = None; + ctx.data_mut(|d| d.insert_temp(state_id, st)); + app.show_shortcuts = true; + let replace = (!app.keymap.keys(id).is_empty()).then_some(0); + app.key_capture = Some(KeyCapture { id, replace }); +} + fn shortcut_sheet(app: &mut App, ctx: &egui::Context) { if !app.show_shortcuts { app.key_capture = None; diff --git a/src/keymap.rs b/src/keymap.rs index d5d2c48a..0a930bef 100644 --- a/src/keymap.rs +++ b/src/keymap.rs @@ -10,7 +10,8 @@ use crate::app::{Tool, VIEW_SHORTCUTS}; use anicraft_engine::{SHORTCUT_ALIASES, commands}; use egui::{Key, Modifiers}; -use std::collections::BTreeMap; +use std::cell::RefCell; +use std::collections::{BTreeMap, BTreeSet}; /// Keys handled before the shortcut map, which the editor will not assign, and what for /// (English: translated where it is shown). @@ -94,8 +95,56 @@ fn view_label(id: &str) -> &'static str { } } +/// The start of a saved command's action id (ADR 0097): `macro:`. +pub const MACRO_PREFIX: &str = "macro:"; + +/// Most distinct saved command names the map ever binds in one run (see [`intern`]). +const MAX_INTERNED: usize = 4096; + +thread_local! { + /// The saved commands that can carry a shortcut, as `(action id, name)`, in their order. + static MACROS: RefCell> = const { RefCell::new(Vec::new()) }; + static INTERNED: RefCell> = const { RefCell::new(BTreeSet::new()) }; +} + +/// `s` for the life of the program, each distinct string kept once. An action's id and label +/// are `&'static str` everywhere the map is used; saved commands are the only actions named at +/// run time, and a run meets a handful of their names, so keeping each one is the simple +/// choice. Past [`MAX_INTERNED`] names a new one can't carry a shortcut until the next start. +fn intern(s: &str) -> Option<&'static str> { + INTERNED.with(|set| { + let mut set = set.borrow_mut(); + if let Some(kept) = set.get(s) { + return Some(*kept); + } + if set.len() >= MAX_INTERNED { + return None; + } + let kept: &'static str = Box::leak(s.to_string().into_boxed_str()); + set.insert(kept); + Some(kept) + }) +} + +/// A saved command's action id. +pub fn macro_id(name: &str) -> String { + format!("{MACRO_PREFIX}{name}") +} + +/// The saved command an action id names. +pub fn macro_name(id: &str) -> Option<&str> { + id.strip_prefix(MACRO_PREFIX) +} + +/// The saved commands, in their order, as actions that can carry a shortcut (Manage Saved +/// Commands sets them whenever the list changes; rebuild the [`Keymap`] after). +pub fn set_macros<'a>(names: impl IntoIterator) { + let list: Vec<(&'static str, &'static str)> = names.into_iter().filter_map(|n| Some((intern(¯o_id(n))?, intern(n)?))).collect(); + MACROS.with(|m| *m.borrow_mut() = list); +} + /// Every action that can carry a shortcut: the menu commands, any command with a default key, -/// the tools and the view keys. +/// the tools, the view keys and the saved commands. pub fn actions() -> Vec { let mut v: Vec = commands() .into_iter() @@ -120,6 +169,7 @@ pub fn actions() -> Vec { group: tr_noop!("View"), defaults: VIEW_SHORTCUTS.iter().filter(|(_, i)| *i == id).map(|(k, _)| *k).collect(), })); + MACROS.with(|m| v.extend(m.borrow().iter().map(|&(id, label)| Action { id, label, group: tr_noop!("Commands"), defaults: Vec::new() }))); v } @@ -192,11 +242,17 @@ pub struct Keymap { impl Keymap { pub fn new(overrides: &BTreeMap>) -> Keymap { let actions = actions(); + // A chord bound twice (a saved command's key in a hand-edited preferences file) stays + // with the action listed first. + let mut taken: BTreeSet = BTreeSet::new(); let keys = actions .iter() - .map(|a| match overrides.get(a.id) { - Some(user) => user.iter().filter_map(|k| normalize(k)).collect(), - None => a.defaults.iter().filter_map(|k| normalize(k)).collect(), + .map(|a| { + let ks: Vec = match overrides.get(a.id) { + Some(user) => user.iter().filter_map(|k| normalize(k)).collect(), + None => a.defaults.iter().filter_map(|k| normalize(k)).collect(), + }; + ks.into_iter().filter(|k| taken.insert(k.clone())).collect() }) .collect(); Keymap { actions, keys } @@ -326,7 +382,9 @@ pub fn sanitize(overrides: BTreeMap>) -> BTreeMap> = BTreeMap::new(); for (id, keys) in overrides.into_iter().take(1_000) { - if !known.iter().any(|a| a.id == id) { + // A saved command's keys are kept while it isn't listed yet (they bind once it is). + let saved = macro_name(&id).is_some_and(|n| !n.is_empty() && n.chars().count() <= 64); + if !saved && !known.iter().any(|a| a.id == id) { continue; } let mut clean: Vec = Vec::new(); diff --git a/src/macros_ui.rs b/src/macros_ui.rs new file mode 100644 index 00000000..c580bdd7 --- /dev/null +++ b/src/macros_ui.rs @@ -0,0 +1,444 @@ +//! Saved commands in the desktop app (ADR 0097): Save As Command from the steps picked in the +//! History panel, the saved commands at the end of the Commands menu with their shortcuts, Run +//! Command… for a file, and Commands › Manage Saved Commands (run, rename, reorder, shortcut, +//! delete, add from a file). The `macro.*` commands do the work; the files live in the settings +//! folder (`platform::commands_dir`). + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::keymap; +use crate::theme::{T, Type, text}; +use anicraft_engine::cmds_macro::{self, Saved}; +use serde_json::{Value, json}; +use std::collections::BTreeSet; +use std::path::PathBuf; + +/// What the window keeps for saved commands between frames (view state, not saved). +#[derive(Default)] +pub struct Macros { + /// The saved commands, as last read from the folder, in their order. + pub list: Vec, + /// Files in the folder that aren't saved commands, with why. + pub problems: Vec<(String, String)>, + /// History steps picked for Save As Command (as `macro.history` numbers them). + pub picked: BTreeSet, + /// The step picked last (the anchor of a Shift+click range). + anchor: Option, + /// The history the picks belong to: (steps freed, steps listed). + picked_for: (usize, usize), + /// The Save As Command dialog, while it is open. + pub save: Option, + /// Commands › Manage Saved Commands. + pub manage: Manage, +} + +/// A picked step as Save As Command keeps it. +#[derive(Clone, Debug)] +pub struct StepView { + pub index: usize, + pub label: String, + /// Why it can't be kept (`None`: it can). + pub refused: Option, + /// What was rewritten so it replays elsewhere ("acts on the selection"). + pub note: Option, +} + +/// The Save As Command dialog. +pub struct SaveDialog { + pub name: String, + pub steps: Vec, + focus: bool, +} + +/// The Manage Saved Commands window. +#[derive(Default)] +pub struct Manage { + pub open: bool, + /// The command being renamed and the name typed so far. + renaming: Option<(String, String)>, + focus: bool, +} + +/// The folder the saved commands are in. Screenshot runs never touch the real one: they use a +/// temporary folder (unless `ANICRAFT_COMMANDS_DIR` names one). None in a browser. +pub fn folder(app: &App) -> Option { + if app.shot.is_some() && std::env::var_os("ANICRAFT_COMMANDS_DIR").is_none() && !crate::platform::WEB { + return Some(std::env::temp_dir().join(format!("anicraft-commands-shot-{}", std::process::id()))); + } + crate::platform::commands_dir() +} + +fn folder_str(app: &App) -> Option { + folder(app).map(|f| f.display().to_string()) +} + +/// Reads the folder again, and lets the shortcut map bind what is in it. +pub fn rescan(app: &mut App) { + let (list, problems) = folder(app).map(|f| cmds_macro::saved_commands(&f)).unwrap_or_default(); + app.macros.list = list; + app.macros.problems = problems; + keymap::set_macros(app.macros.list.iter().map(|c| c.name.as_str())); + app.refresh_keymap(); +} + +/// Runs the saved command called `name` (from the menu, a shortcut or the Manage window). +pub fn run_saved(app: &mut App, name: &str) { + let Some(folder) = folder_str(app) else { return }; + app.playing = false; + app.request("macro.run", json!({"folder": folder, "name": name})); +} + +/// Whether the steps picked so far still belong to this history; if not, they are let go. +fn sync_picks(app: &mut App) { + let h = app.s.history(); + let now = (h.evicted, h.undo_len() + h.redo_len()); + let was = app.macros.picked_for; + // New steps keep the numbers of the old ones; a freed step or a dropped redo moves them. + if now.0 != was.0 || now.1 < was.1 { + app.macros.picked.clear(); + app.macros.anchor = None; + } + app.macros.picked_for = now; +} + +/// Picks history step `i` for Save As Command: Ctrl toggles it, Shift picks the range from the +/// step picked last. +pub fn pick(app: &mut App, i: usize, toggle: bool, range: bool) { + sync_picks(app); + let m = &mut app.macros; + match (range, m.anchor) { + (true, Some(a)) => { + m.picked.extend(a.min(i)..=a.max(i)); + } + _ if toggle && m.picked.contains(&i) => { + m.picked.remove(&i); + } + _ => { + m.picked.insert(i); + } + } + m.anchor = Some(i); +} + +/// The picked steps, in order (after letting go of picks the history no longer has). +pub fn picked(app: &mut App) -> Vec { + sync_picks(app); + app.macros.picked.iter().copied().collect() +} + +pub fn clear_picks(app: &mut App) { + app.macros.picked.clear(); + app.macros.anchor = None; +} + +/// Opens Save As Command for the picked steps. +pub fn open_save(app: &mut App) { + if folder(app).is_none() { + app.status_err(tr!("Saved commands are kept in a folder on your computer: save them in the desktop app.")); + return; + } + let picked = picked(app); + if picked.is_empty() { + app.status_err(tr!("Pick the steps to save first: Ctrl+click them in the History panel (Shift+click picks a range).")); + return; + } + let listed = app.s.execute("macro.history", &json!({})).unwrap_or(Value::Null); + let rows = listed["steps"].as_array().cloned().unwrap_or_default(); + let steps: Vec = picked + .iter() + .filter_map(|&i| rows.get(i)) + .map(|r| StepView { + index: r["index"].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(0), + label: r["label"].as_str().unwrap_or("").to_string(), + refused: r["why"].as_str().map(str::to_string), + note: r["rewritten"].as_str().map(str::to_string), + }) + .collect(); + let n = app.macros.list.len() + 1; + app.macros.save = Some(SaveDialog { name: tr!("Command {n}", n = n), steps, focus: true }); +} + +/// A step's undo label in the interface language (the engine's English is the key). +fn step_label(label: &str) -> String { + crate::i18n::t_dyn(label).into_owned() +} + +fn save_window(app: &mut App, ctx: &egui::Context) { + let Some(d) = &mut app.macros.save else { return }; + let mut open = true; + let mut save = false; + let mut cancel = false; + let title = tr!("Save As Command"); + let shown = egui::Window::new(title).id(egui::Id::new("save_as_command")).open(&mut open).collapsible(false).resizable(false).pivot(egui::Align2::CENTER_CENTER).default_pos(ctx.content_rect().center()).show(ctx, |ui| { + ui.set_min_width(380.0); + ui.horizontal(|ui| { + ui.label(text(Type::Label, tr!("Name"))); + let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(280.0)).named(tr!("Saved command name")); + if d.focus { + r.request_focus(); + d.focus = false; + } + if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + save = true; + } + }); + ui.add_space(6.0); + ui.label(text(Type::Label, trn!("{n} step, run in order as one undo step:", "{n} steps, run in order as one undo step:", d.steps.len()))); + egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| { + for st in &d.steps { + ui.horizontal(|ui| { + ui.label(text(Type::Data, (st.index + 1).to_string()).color(T.text_dim)); + ui.label(text(Type::Body, step_label(&st.label))); + match (&st.refused, &st.note) { + (Some(why), _) => { + ui.label(text(Type::Caption, tr!("can't be kept: {why}", why = crate::i18n::t_dyn(why))).color(T.error)); + } + (None, Some(note)) => { + ui.label(text(Type::Caption, crate::i18n::t_dyn(note)).color(T.text_dim)); + } + (None, None) => {} + } + }); + } + }); + let refused = d.steps.iter().filter(|s| s.refused.is_some()).count(); + ui.add_space(4.0); + if refused > 0 { + ui.label(text(Type::Caption, trn!("Take the step that can't be kept out of the picks (Ctrl+click it) to save the others.", "Take the {n} steps that can't be kept out of the picks (Ctrl+click them) to save the others.", refused)).color(T.error)); + } else { + ui.label(text(Type::Caption, tr!("It runs on whatever is selected when you choose it in the Commands menu."))); + } + ui.add_space(6.0); + ui.horizontal(|ui| { + let ok = refused == 0 && !d.name.trim().is_empty(); + if ui.add_enabled(ok, egui::Button::new(tr!("Save"))).clicked() { + save = true; + } + if ui.button(tr!("Cancel")).clicked() { + cancel = true; + } + }); + }); + a11y::name_title_bar(&shown, title); + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + cancel = true; + } + if !open || cancel { + app.macros.save = None; + return; + } + let ready = app.macros.save.as_ref().filter(|d| save && !d.name.trim().is_empty() && d.steps.iter().all(|s| s.refused.is_none())); + if let Some(d) = ready { + let history: Vec = d.steps.iter().map(|s| s.index).collect(); + let name = d.name.trim().to_string(); + if let Some(folder) = folder_str(app) { + app.request("macro.save", json!({"folder": folder, "name": name, "history": history})); + } + } +} + +/// The saved commands at the end of the Commands menu, as Animate lists them. +pub fn menu_items(app: &mut App, ui: &mut egui::Ui) { + if folder(app).is_none() { + return; + } + ui.separator(); + if app.macros.list.is_empty() { + ui.label(text(Type::Caption, tr!("No saved commands yet: pick steps in the History panel and Save As Command"))); + return; + } + let names: Vec = app.macros.list.iter().map(|c| c.name.clone()).collect(); + for name in names { + let key = crate::platform::shortcut_label(app.keymap.primary(&keymap::macro_id(&name)).unwrap_or("")); + if ui.add(egui::Button::new(name.as_str()).shortcut_text(text(Type::Key, key))).clicked() { + ui.input_mut(|i| { + i.consume_key(egui::Modifiers::NONE, egui::Key::Enter); + i.consume_key(egui::Modifiers::NONE, egui::Key::Space); + }); + ui.close(); + run_saved(app, &name); + } + } +} + +/// Commands › Manage Saved Commands… +pub fn open_manage(app: &mut App) { + rescan(app); + app.macros.manage = Manage { open: true, ..Manage::default() }; +} + +/// Opens the shortcut editor on the saved command `name`, already waiting for its keys. +fn assign_shortcut(app: &mut App, ctx: &egui::Context, name: &str) { + let id = keymap::macro_id(name); + let Some(action) = app.keymap.actions.iter().find(|a| a.id == id).map(|a| a.id) else { return }; + crate::dialogs::shortcuts_for(app, ctx, name, action); +} + +enum Act { + Run(String), + Move(String, usize), + Rename(String, String), + Delete(String), + Shortcut(String), +} + +fn manage_window(app: &mut App, ctx: &egui::Context) { + if !app.macros.manage.open { + return; + } + let Some(dir) = folder(app) else { + app.macros.manage.open = false; + return; + }; + let mut open = true; + let mut acts: Vec = Vec::new(); + let title = tr!("Manage Saved Commands"); + let shown = egui::Window::new(title).id(egui::Id::new("manage_saved_commands")).open(&mut open).collapsible(false).resizable(false).default_width(760.0).show(ctx, |ui| { + ui.set_min_width(720.0); + let list = app.macros.list.clone(); + if list.is_empty() { + ui.label(text(Type::Label, tr!("No saved commands yet. Pick steps in the History panel (Ctrl+click), then Save As Command: they run again on the selection as one undo step."))); + } + let n = list.len(); + for (i, c) in list.iter().enumerate() { + ui.horizontal(|ui| { + ui.set_min_height(crate::theme::TARGET); + let mut renaming = app.macros.manage.renaming.take(); + if let Some((k, typed)) = &mut renaming + && *k == c.name + { + let r = ui.add(egui::TextEdit::singleline(typed).desired_width(220.0)).named(&tr!("New name for “{name}”", name = c.name)); + if app.macros.manage.focus { + r.request_focus(); + app.macros.manage.focus = false; + } + let enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if ui.button(tr!("Rename")).clicked() || enter { + acts.push(Act::Rename(c.name.clone(), typed.trim().to_string())); + } else if ui.button(tr!("Cancel")).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + renaming = None; + } + app.macros.manage.renaming = renaming; + return; + } + app.macros.manage.renaming = renaming; + // Fixed columns, so the buttons line up row under row. + let cell = |ui: &mut egui::Ui, w: f32, add: &mut dyn FnMut(&mut egui::Ui)| { + ui.allocate_ui_with_layout(egui::vec2(w, crate::theme::TARGET), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(w); + add(ui); + }); + }; + cell(ui, 210.0, &mut |ui| { + ui.add(egui::Label::new(text(Type::Body, &c.name)).truncate()); + }); + cell(ui, 64.0, &mut |ui| { + ui.label(text(Type::DataSmall, trn!("{n} step", "{n} steps", c.steps)).color(T.text_dim)); + }); + let key = app.keymap.primary(&keymap::macro_id(&c.name)).map(crate::platform::shortcut_label).unwrap_or_default(); + cell(ui, 96.0, &mut |ui| { + ui.add(egui::Label::new(text(Type::Key, key.as_str()).color(T.text_dim)).truncate()); + }); + if ui.button(tr!("Run")).named(&tr!("Run “{name}”", name = c.name)).on_hover_text(tr!("Run it on the selection (one undo step)")).clicked() { + acts.push(Act::Run(c.name.clone())); + } + let gap = crate::theme::TARGET + 4.0; + if i > 0 { + if crate::timeline::icon_button(ui, &tr!("Move “{name}” up", name = c.name), None, crate::icons::Icon::ChevronUp).clicked() { + acts.push(Act::Move(c.name.clone(), i - 1)); + } + } else { + ui.allocate_exact_size(egui::vec2(gap, crate::theme::TARGET), egui::Sense::hover()); + } + if i + 1 < n { + if crate::timeline::icon_button(ui, &tr!("Move “{name}” down", name = c.name), None, crate::icons::Icon::ChevronDown).clicked() { + acts.push(Act::Move(c.name.clone(), i + 1)); + } + } else { + ui.allocate_exact_size(egui::vec2(gap, crate::theme::TARGET), egui::Sense::hover()); + } + if ui.button(tr!("Shortcut…")).named(&tr!("Shortcut for “{name}”", name = c.name)).on_hover_text(tr!("Give it a key in Keyboard Shortcuts")).clicked() { + acts.push(Act::Shortcut(c.name.clone())); + } + if ui.button(tr!("Rename…")).named(&tr!("Rename “{name}”", name = c.name)).clicked() { + app.macros.manage.renaming = Some((c.name.clone(), c.name.clone())); + app.macros.manage.focus = true; + } + if ui.button(tr!("Delete…")).named(&tr!("Delete “{name}”", name = c.name)).on_hover_text(tr!("Delete this saved command's file (asks first)")).clicked() { + acts.push(Act::Delete(c.name.clone())); + } + }); + } + for (file, why) in &app.macros.problems { + ui.label(text(Type::Caption, tr!("{file} isn't a saved command: {why}", file = file, why = crate::i18n::t_dyn(why))).color(T.error)); + } + ui.separator(); + ui.horizontal(|ui| { + if ui.button(tr!("Add from File…")).on_hover_text(tr!("Copy a saved command someone shared into your commands")).clicked() { + app.invoke("macro.import"); + } + ui.label(text(Type::Path, dir.display().to_string()).color(T.text_faint)); + }); + ui.label(text(Type::Caption, tr!("Saved commands are small JSON files: share one by sending it; Commands › Run Command… runs a file without adding it."))); + }); + a11y::name_title_bar(&shown, title); + let folder = dir.display().to_string(); + for act in acts { + match act { + Act::Run(name) => run_saved(app, &name), + Act::Move(name, index) => app.request("macro.move", json!({"folder": folder, "name": name, "index": index})), + Act::Rename(name, to) => app.request("macro.rename", json!({"folder": folder, "name": name, "to": to})), + Act::Delete(name) => app.request("macro.delete", json!({"folder": folder, "name": name})), + Act::Shortcut(name) => assign_shortcut(app, ctx, &name), + } + } + if !open { + app.macros.manage = Manage::default(); + } +} + +pub fn show(app: &mut App, ctx: &egui::Context) { + save_window(app, ctx); + manage_window(app, ctx); +} + +/// Moves (or with `to` None, drops) the shortcut keys kept for the saved command `from`. +fn move_shortcut(app: &mut App, from: &str, to: Option<&str>) { + let Some(keys) = app.prefs.shortcuts.remove(&keymap::macro_id(from)) else { return }; + if let Some(to) = to { + app.prefs.shortcuts.insert(keymap::macro_id(to), keys); + } + app.save_prefs(); +} + +/// After a `macro.*` command ran: the list again, the status line, and a renamed or deleted +/// command's shortcut following it. +pub fn done(app: &mut App, id: &str, v: &Value) { + let name = v["name"].as_str().unwrap_or("").to_string(); + match id { + "macro.run" => { + let n = v["steps"].as_u64().unwrap_or(0); + app.status_ok(trn!("Ran “{name}” ({n} step) — {undo} to undo", "Ran “{name}” ({n} steps) — {undo} to undo", n, name = name, undo = app.undo_key())); + return; + } + "macro.save" => { + app.macros.save = None; + clear_picks(app); + app.status_ok(tr!("Saved “{name}”: find it at the end of the Commands menu", name = name)); + } + "macro.rename" => { + app.macros.manage.renaming = None; + if let Some(from) = v["from"].as_str() { + move_shortcut(app, from, Some(&name)); + } + } + "macro.delete" => { + let gone = v["deleted"].as_str().unwrap_or("").to_string(); + move_shortcut(app, &gone, None); + app.status_ok(tr!("Deleted “{name}”", name = gone)); + } + "macro.import" => app.status_ok(tr!("Added “{name}” to your commands", name = name)), + _ => {} + } + rescan(app); +} diff --git a/src/macros_ui_tests.rs b/src/macros_ui_tests.rs new file mode 100644 index 00000000..0c431153 --- /dev/null +++ b/src/macros_ui_tests.rs @@ -0,0 +1,115 @@ +//! Saved commands in the desktop app (ADR 0097): picking steps in the History panel, Save As +//! Command, a saved command's shortcut running it, and a rename or delete taking its keys +//! along. + +use crate::app::App; +use crate::keymap; +use anicraft_engine::Session; +use anicraft_engine::doc::sample; +use serde_json::json; + +/// A test app: a screenshot path, so the saved commands live in a temporary folder. +fn app(ctx: &egui::Context) -> App { + App::with_context(ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png"))) +} + +fn frame(ctx: &egui::Context, app: &mut App, events: Vec) { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), events, ..Default::default() }; + ctx.run_ui(raw, |ui| app.frame(ui)).textures_delta.clear(); +} + +#[test] +fn picked_steps_save_as_a_command_and_its_shortcut_runs_it() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + // (The only test here that writes to the folder.) + if let Some(f) = crate::macros_ui::folder(&app) { + let _ = std::fs::remove_dir_all(&f); + } + app.run("edit.select_all", json!({})); + app.run("modify.rotate_cw", json!({})); + app.run("element.set_color_effect", json!({"style": "alpha", "alpha": 50})); + let n = app.s.history_len(); + // Ctrl+click the two steps; a plain pick of a third, then Ctrl+click takes it out again. + crate::macros_ui::pick(&mut app, n - 2, true, false); + crate::macros_ui::pick(&mut app, n - 1, true, false); + assert_eq!(crate::macros_ui::picked(&mut app), [n - 2, n - 1]); + crate::macros_ui::open_save(&mut app); + let d = app.macros.save.as_mut().expect("the dialog"); + assert_eq!(d.steps.len(), 2); + assert!(d.steps.iter().all(|s| s.refused.is_none())); + d.name = "Spin and Fade".into(); + frame(&ctx, &mut app, vec![]); + let folder = crate::macros_ui::folder(&app).expect("a folder").display().to_string(); + app.request("macro.save", json!({"folder": folder, "name": "Spin and Fade", "history": [n - 2, n - 1]})); + assert!(app.macros.save.is_none(), "saved, the dialog closes"); + assert!(crate::macros_ui::picked(&mut app).is_empty()); + assert_eq!(app.macros.list.iter().map(|c| c.name.as_str()).collect::>(), ["Spin and Fade"]); + + // A key of its own, through the shortcut map. + let id = keymap::macro_id("Spin and Fade"); + app.prefs.shortcuts = keymap::assign(&app.prefs.shortcuts, &id, None, "Ctrl+Alt+R", false).expect("a free key"); + app.refresh_keymap(); + assert!(app.shortcuts.iter().any(|(_, k, a)| *k == egui::Key::R && *a == id)); + let steps = app.s.history_len(); + let before = app.s.selected_elements().first().map(|(_, e)| e.transform); + // (The dialog's name field gives the keyboard back once it is gone.) + for _ in 0..3 { + frame(&ctx, &mut app, vec![]); + } + let key = egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND | egui::Modifiers::ALT }; + frame(&ctx, &mut app, vec![key]); + assert_eq!(app.s.history_len(), steps + 1, "the key ran it as one step"); + assert_eq!(app.s.undo_label(), Some("Spin and Fade")); + assert_ne!(app.s.selected_elements().first().map(|(_, e)| e.transform), before); + + // A rename takes its key along; a delete (confirmed) drops it. + app.request("macro.rename", json!({"folder": folder, "name": "Spin and Fade", "to": "Twirl"})); + assert_eq!(app.keymap.keys(&keymap::macro_id("Twirl")), ["Ctrl+Alt+R"]); + assert!(!app.prefs.shortcuts.contains_key(&id)); + app.request("macro.delete", json!({"folder": folder, "name": "Twirl"})); + assert!(app.confirm.is_some(), "deleting a file asks first"); + app.confirm = None; + app.perform("macro.delete", json!({"folder": folder, "name": "Twirl", "confirm": true})); + assert!(app.macros.list.is_empty()); + assert!(app.prefs.shortcuts.keys().all(|k| keymap::macro_name(k).is_none())); + let _ = std::fs::remove_dir_all(&folder); +} + +#[test] +fn a_step_that_cant_be_kept_is_named_in_the_dialog() { + let ctx = egui::Context::default(); + let mut app = app(&ctx); + app.run("edit.select_all", json!({})); + app.run("edit.copy", json!({})); + app.run("edit.paste", json!({})); + let n = app.s.history_len(); + crate::macros_ui::pick(&mut app, n - 1, false, false); + crate::macros_ui::open_save(&mut app); + let d = app.macros.save.as_ref().expect("the dialog"); + assert!(d.steps[0].refused.as_deref().is_some_and(|w| w.contains("clipboard")), "{:?}", d.steps); + // The dialog draws, and Save stays off. + frame(&ctx, &mut app, vec![]); + assert!(app.macros.save.is_some()); +} + +#[test] +fn saved_commands_take_shortcuts_like_any_action() { + keymap::set_macros(["Spin"]); + let none = std::collections::BTreeMap::new(); + let o = keymap::assign(&none, "macro:Spin", None, "Ctrl+Alt+R", false).expect("free"); + let m = keymap::Keymap::new(&o); + assert_eq!(m.owner("Ctrl+Alt+R").map(|a| a.id), Some("macro:Spin")); + assert!(matches!(keymap::assign(&o, "macro:Spin", None, "Ctrl+Z", false), Err(keymap::Refusal::Taken { id: "edit.undo", .. }))); + // Kept while the folder hasn't been read yet, bound once it is. + keymap::set_macros([]); + let kept = keymap::sanitize(o.clone()); + assert!(kept.contains_key("macro:Spin")); + assert!(keymap::Keymap::new(&kept).keys("macro:Spin").is_empty()); + // A clash from a hand-edited file stays with the action listed first. + keymap::set_macros(["Spin"]); + let bad = std::collections::BTreeMap::from([("macro:Spin".to_string(), vec!["Ctrl+Z".to_string()])]); + let m = keymap::Keymap::new(&bad); + assert_eq!(m.owner("Ctrl+Z").map(|a| a.id), Some("edit.undo")); + assert!(m.keys("macro:Spin").is_empty()); +} diff --git a/src/main.rs b/src/main.rs index 8c62d086..e63f6b89 100644 --- a/src/main.rs +++ b/src/main.rs @@ -71,6 +71,9 @@ mod plugin_export_ui; mod plugin_fixture_tests; #[cfg(test)] mod plugin_ui_tests; +#[cfg(test)] +mod macros_ui_tests; +mod macros_ui; mod plugins_ui; mod prefs; mod recent; diff --git a/src/panels.rs b/src/panels.rs index 42213b6f..7089a079 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -576,29 +576,77 @@ pub(crate) fn align_panel(app: &mut App, ui: &mut egui::Ui) { } /// Undo history: past steps (click to go back), the current state, and redoable steps (dimmed). +/// Ctrl+click picks steps (Shift+click a range) for Save As Command, which keeps them as a +/// saved command in the Commands menu (ADR 0097); so does each step's context menu. pub(crate) fn history(app: &mut App, ui: &mut egui::Ui) { + let picked: std::collections::BTreeSet = crate::macros_ui::picked(app).into_iter().collect(); let hist = app.s.history(); let past: Vec = hist.undo_labels().map(str::to_string).collect(); let future: Vec = hist.redo_labels().map(str::to_string).collect(); let evicted = hist.evicted; let mut target = None; - egui::ScrollArea::vertical().id_salt("history").max_height(ui.available_height().max(60.0)).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + // (step, toggle, range) + let mut pick: Option<(usize, bool, bool)> = None; + let mut save = false; + let footer = crate::theme::TARGET + 8.0; + let tip = tr!("Click to go back to this step · Ctrl+click picks it for Save As Command, Shift+click a range"); + egui::ScrollArea::vertical().id_salt("history").max_height((ui.available_height() - footer).max(crate::theme::TARGET)).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { let base = if evicted > 0 { tr!("… older steps freed (memory budget)") } else { tr!("Opened document") }; - if ui.selectable_label(past.is_empty(), text(Type::Body, base).color(if evicted > 0 { T.text_faint } else { T.text_dim })).clicked() { + if ui.selectable_label(past.is_empty() && picked.is_empty(), text(Type::Body, base).color(if evicted > 0 { T.text_faint } else { T.text_dim })).clicked() { target = Some(0); } - for (i, label) in past.iter().enumerate() { + let rows = past.iter().map(|l| (l, false)).chain(future.iter().map(|l| (l, true))); + for (i, (label, undone)) in rows.enumerate() { let current = i + 1 == past.len(); - if ui.selectable_label(current, crate::i18n::t_dyn(label).into_owned()).clicked() { - target = Some(i + 1); + let on = picked.contains(&i); + let shown = crate::i18n::t_dyn(label).into_owned(); + // With steps picked, the picks are highlighted and the current step is marked. + let shown = if current && !picked.is_empty() { format!("› {shown}") } else { shown }; + let t = if undone { text(Type::Body, shown).color(T.text_faint).italics() } else { text(Type::Body, shown) }; + let r = ui.selectable_label(if picked.is_empty() { current } else { on }, t).on_hover_text(tip); + if r.clicked() { + let m = ui.input(|i| i.modifiers); + if m.command || m.shift { + pick = Some((i, m.command, m.shift)); + } else { + target = Some(i + 1); + } } + r.context_menu(|ui| { + if ui.button(if on { tr!("Unpick Step") } else { tr!("Pick for Save As Command") }).clicked() { + pick = Some((i, true, false)); + ui.close(); + } + if ui.button(tr!("Save As Command…")).clicked() { + if !on { + pick = Some((i, true, false)); + } + save = true; + ui.close(); + } + }); } - for (i, label) in future.iter().enumerate() { - if ui.selectable_label(false, text(Type::Body, crate::i18n::t_dyn(label)).color(T.text_faint).italics()).clicked() { - target = Some(past.len() + i + 1); + }); + ui.horizontal(|ui| { + ui.set_min_height(crate::theme::TARGET); + if picked.is_empty() { + ui.label(text(Type::Caption, tr!("Ctrl+click steps to save them as a command"))); + } else { + if ui.button(tr!("Save As Command…")).on_hover_text(tr!("Keep the picked steps as a command in the Commands menu, to run on any selection")).clicked() { + save = true; + } + ui.label(text(Type::Caption, trn!("{n} step picked", "{n} steps picked", picked.len()))); + if ui.small_button(tr!("Clear")).on_hover_text(tr!("Unpick every step")).clicked() { + crate::macros_ui::clear_picks(app); } } }); + if let Some((i, toggle, range)) = pick { + crate::macros_ui::pick(app, i, toggle, range); + } + if save { + crate::macros_ui::open_save(app); + } if let Some(t) = target && let Err(e) = app.s.travel_to(t) { diff --git a/src/platform.rs b/src/platform.rs index dc4d30a6..f75acc36 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -397,7 +397,7 @@ pub fn places() -> Vec<(&'static str, Option)> { return Vec::new(); } #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] - let mut v = vec![(tr_noop!("Preferences"), config_dir()), (tr_noop!("Autosave"), recovery_dir()), (tr_noop!("Logs"), log_dir()), (tr_noop!("Plug-ins"), plugins_dir()), (tr_noop!("Templates"), templates_dir())]; + let mut v = vec![(tr_noop!("Preferences"), config_dir()), (tr_noop!("Autosave"), recovery_dir()), (tr_noop!("Logs"), log_dir()), (tr_noop!("Plug-ins"), plugins_dir()), (tr_noop!("Templates"), templates_dir()), (tr_noop!("Saved commands"), commands_dir())]; #[cfg(not(target_arch = "wasm32"))] v.push((tr_noop!("User guide"), Some(guide_dir()))); v @@ -532,6 +532,19 @@ pub fn templates_dir() -> Option { } } +/// Where saved commands live (ADR 0097): `Commands` in the settings folder, one small JSON file +/// each. `ANICRAFT_COMMANDS_DIR` points it elsewhere (tests, screenshots). None in a browser, +/// which has no folders to keep them in. +pub fn commands_dir() -> Option { + if WEB { + return None; + } + match std::env::var_os("ANICRAFT_COMMANDS_DIR").filter(|v| !v.is_empty()) { + Some(d) => Some(PathBuf::from(d)), + None => config_dir().map(|d| d.join("Commands")), // i18n-exempt: a folder name + } +} + /// Where installed plug-ins live: a `plugins` folder in the settings folder (ADR 0017). pub fn plugins_dir() -> Option { config_dir().map(|d| d.join("plugins")) @@ -829,6 +842,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { // Opening also imports .fla archives and .xfl packages. "file.open" => (tr_noop!("Documents"), &["anicraft", "fla", "xfl"]), "plugin.install" => (tr_noop!("WebAssembly plug-in"), &["wasm"]), + "macro.run" | "macro.import" => (tr_noop!("Saved command"), &["json"]), "brush.preset_export" | "brush.preset_import" => (tr_noop!("Brush set"), &["json"]), "filter.preset_export" | "filter.preset_import" => (tr_noop!("Filter preset file"), &["json"]), "swatch.export" => (tr_noop!("Swatch file"), &["json"]), @@ -839,7 +853,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { /// Commands that read a file the user picks (the others write one, or a folder of them). pub fn reads_file(cmd: &str) -> bool { - matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import") + matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import" | "macro.run" | "macro.import") } /// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal), with diff --git a/src/plugins_ui.rs b/src/plugins_ui.rs index 0a29f62c..0f10c504 100644 --- a/src/plugins_ui.rs +++ b/src/plugins_ui.rs @@ -141,6 +141,8 @@ pub fn menu(app: &mut App, ui: &mut egui::Ui, cmds: &[CommandSpec], item: impl F for spec in cmds.iter().filter(|c| c.menu == "Commands") { item(app, ui, spec); } + // Saved commands last, as Animate lists them (ADR 0097). + crate::macros_ui::menu_items(app, ui); } fn hex_rgb(s: &str) -> [u8; 3] { From 9fdc619090e151e2afa6a57259a0e3461b71b984 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:56:16 -0700 Subject: [PATCH 057/570] docs: ADR 0097, the guide's saved commands chapter (M6) --- docs/adr/0097-command-macros.md | 118 ++++++++++++++++++++++++++++++ docs/guide/coming-from-animate.md | 2 +- docs/guide/index.md | 7 +- docs/guide/saved-commands.md | 80 ++++++++++++++++++++ docs/guide/workspace.md | 4 + 5 files changed, 207 insertions(+), 4 deletions(-) create mode 100644 docs/adr/0097-command-macros.md create mode 100644 docs/guide/saved-commands.md diff --git a/docs/adr/0097-command-macros.md b/docs/adr/0097-command-macros.md new file mode 100644 index 00000000..0a12a0b3 --- /dev/null +++ b/docs/adr/0097-command-macros.md @@ -0,0 +1,118 @@ +# ADR 0097: Command macros (saved commands) + +* Status: accepted (2026-11-14) +* Relates to: roadmap M6 (command macros), ADR 0001 (undo over persistent snapshots), ADR 0004 + (destructive actions), ADR 0017 (WebAssembly plug-ins and `plugin_may_call`), ADR 0065 + (templates: files in the settings folder the shell passes in), ADR 0073 (groups refuse + timeline commands), ADR 0016 (auto-keying motion tweens) + +## Context + +Animate users repeat the same few edits all day (rotate, fade, nudge, add a keyframe, set an +ease) and expect to keep them: in Animate's History panel they select steps and choose **Save As +Command**; the command then appears at the end of the **Commands** menu, can get a keyboard +shortcut, and **Manage Saved Commands** renames and deletes them. **Run Command…** runs a +command file someone sent. Behaviour was learnt from Adobe's public help pages for the History +panel and the Commands menu and by observation; no Adobe code, file format or asset was used +(Animate stores JSFL scripts; ours are JSON lists of registry commands). + +Everything in AniCraft is already a registry command, so a macro is naturally "these command ids +with these params, in order". The questions were: where the steps come from, what a step that +names this document's things (element and layer ids) means elsewhere, what a macro may call, +how a run stays one undo step and transactional, where the files live, and how macros get +shortcuts from a shortcut map whose actions are all known at build time. + +## Decision + +1. **History records the commands of each step.** `history::Snapshot` gains + `commands: Option>`, the `(id, params)` of every top-level mutating command + that changed the document since the previous step: one for a plain edit, all of them for a + gesture (a drag), the marquee's provisional cut and the edit that used it together. Undo and + redo carry them with the label. A live preview's revert drops what it reverted; undo, redo, + healing a cut and opening a document drop what wasn't recorded. Consecutive plain + `element.translate {dx, dy}` add up into one, so a drag of 600 moves is one step. A step keeps + at most 4096 commands and 1 MiB of params (`None` past that: "too many to keep"), and the + bytes count against the undo budget. Nested commands (a plug-in's, a macro's) are not + recorded on their own: `macro.run` records its steps (`Session::record_as`), so a run can be + saved again with other steps; `plugin.run` records itself and therefore can't be kept. + +2. **Steps are rewritten to act on the selection, or refused with the step named.** Save As + Command never stores ids of this document's things. For each recorded param in `TARGETS` + (`layer(s)`, `element(s)`, `id(s)`, `shape`, `path`, `symbol`): it is dropped when the + command's params doc marks it optional (`key?`) and, but for layers, says its default is the + selection; the step then acts on the selection or the active layer. Any other target, and any + param in `FIXED` (`bitmap`, `sound`, `folder`, `bone`, `parent`, `items`, and a bone's + `from`/`to`), refuses the step: "step 4 “Move Points” can't be kept: it works on particular + objects of this document". The params docs are the contract the registry already keeps for + every command (the guide's command reference is generated from them); a test pins the + behaviour on representative commands. Selections and the playhead are not steps (selection + commands don't change the document), so a macro runs on whatever is selected, as in Animate. + +3. **A macro may call what a plug-in may, and never `macro.*`.** `macro_may_call` is + `plugin_may_call` plus the `macro` namespace refused. So macros never open or write files, + use the clipboard, undo, change preferences or run plug-ins or other macros (no recursion), + and plug-ins may not call any `macro.*` command (reading files and running macros is outside + the sandbox). The rule is checked when a file is read and again before each step runs. + +4. **A run is one undo step and transactional.** `macro.run` is a mutating command whose steps + run through `execute_nested` (checked and atomic, no history of their own). At the first + failing step it returns "“Turn and Fade” stopped at step 3 of 3 (Taller row): … Nothing was + changed." and `Session::execute` puts the document, selection and playhead back. The step is + labelled with the macro's name. `execute_nested` now also refuses timeline commands inside an + open group (as `execute` does, ADR 0073) and finishes each command's motion-tween auto-key on + its own, so a step in a macro keys a tween exactly as the command alone does (plug-in runs + benefit too). + +5. **Files: one small JSON file per macro in the settings folder.** `Commands/.json` = + `{"format": "anicraft-command", "version": 1, "steps": [{"cmd", "params", "label"}]}`. The + file's name is the macro's name (no name inside to go stale when a file is renamed or shared); + a bare JSON array of `{cmd, params}` (an `anicraft-cli run` script) reads too, and `command` + is accepted for `cmd` (the MCP spelling). Reading is bounded: 1 MiB, 1000 steps, known + commands only, object params, labels cut to 200 characters without control characters; a + newer version is refused with a clear message. The order of the Commands menu is + `Commands/.order.json` (a dot name no macro can have); files not in it follow by name. Names + follow the template rules (no path characters, no Windows device names). As with templates + (ADR 0065) the shell passes the folder (`platform::commands_dir`, `ANICRAFT_COMMANDS_DIR` + for tests); screenshot runs use a temporary folder; the browser build has none yet. + +6. **Commands.** `macro.run {name + folder | path | steps}` (Commands › Run Command…, asks for a + file), `macro.list {folder}` (Commands › Manage Saved Commands…), `macro.history` (every + history step as Save As Command keeps it: `keep`, `why`, `rewritten`), `macro.save {folder, + name, history | steps}`, `macro.rename`, `macro.move`, `macro.delete` and `macro.import`. + Replacing a file asks first and deleting always does (ADR 0004: undo can't bring a file back), + for every front end. Everything works headless: `anicraft-cli exec doc macro.run '{"path": + …}'`, `anicraft-cli run doc macro.json` (it reads either format) and MCP's `anicraft_run`. + +7. **Shortcuts through the existing map.** A macro is an action `macro:` in the "Commands" + group of Keyboard Shortcuts, bound, reset and checked for clashes like any other; Manage Saved + Commands' **Shortcut…** opens the editor on it, already waiting for the keys. Actions are + `&'static str` throughout the map and the editor, so macro names are interned once each + (bounded at 4096 distinct names a run) rather than reworking the shortcut system for owned + strings. Bindings live in the preferences under the action id and survive a start before the + folder is read; a rename moves them, a delete drops them; a chord bound twice by a hand-edited + file stays with the action listed first. + +8. **Desktop flow.** In the History panel Ctrl+click picks steps and Shift+click a range (a plain + click still travels); a step's context menu picks it or saves it. **Save As Command…** (the + panel's footer, or the context menu) shows the picked steps with what was rewritten and why a + step can't be kept, and asks for a name; Save is disabled until every step can be kept. Saved + macros appear at the end of the Commands menu with their keys. Manage Saved Commands lists + them with Run, ↑/↓ (reorder), Shortcut…, Rename…, Delete… and Add from File…. + +## Consequences + +* Every undo step costs a few more bytes (its commands' JSON), counted in the undo budget. +* A step whose params name document things the command can't do without (moving particular + path points, painting bone weights, placing a particular Library item) can't be saved; the + message says which step and why. Steps that ran as plug-ins can't be saved either. +* The rewrite relies on params docs following the `key?` and "default: the selected …" + conventions; a new command that names an element without saying so is refused, never + replayed wrongly. +* Interning keeps each macro name for the life of the process (bytes per name). + +## Not yet + +Replaying picked steps without saving them (Animate's Replay), a slider for travelling history +separately from picking, macros in the browser build (no folder) and the command palette, +editing a macro's steps or params in the app, recording selection changes as steps, and +macros that ask for a value when they run. diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 0134c835..ff2b43e7 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -27,7 +27,7 @@ Animator and Designer, plus your own saved workspaces and Reset. | Movie Explorer (**Alt+F3**) | Same key; a tab next to the Library (**Window › Movie Explorer**). | | Output | The Output panel inside Test Movie, and **Window › Output**, which keeps the last run's lines. | | Align | The Align panel on the right, and **Modify › Align**. | -| History | The History panel on the right. | +| History | The History panel on the right. Ctrl+click steps, then Save As Command… ([saved commands](saved-commands.md)). | | Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, overflow and Linear RGB, like the Color panel. **Window › Swatches** keeps the document's colours and gradients (click applies to the active stroke or fill, drag to reorder, import and export swatch files and GIMP `.gpl` palettes; not Adobe `.aco`/`.ase`/`.clr`). | | Transform and Info | Position, scale and rotation rows in Properties, and the Free Transform tool. | | Scene | The scene menu at the top left of the stage, **Insert › Scene** and **Modify › Scene**. | diff --git a/docs/guide/index.md b/docs/guide/index.md index deebc197..92040f26 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -34,12 +34,13 @@ the panels, tools and shortcuts you know to AniCraft's, and lists what works dif 13. [Preferences, shortcuts, accessibility and languages](preferences-shortcuts-accessibility.md). 14. [Plug-ins](plugins.md): add commands safely. -15. [Working headless](working-headless.md): the command line and AI assistants, for pipelines. +15. [Saved commands](saved-commands.md): keep steps from the History panel and run them again on any selection. +16. [Working headless](working-headless.md): the command line and AI assistants, for pipelines. ## Help -16. [Troubleshooting and FAQ](troubleshooting-and-faq.md). -17. [Coming from Animate](coming-from-animate.md). +17. [Troubleshooting and FAQ](troubleshooting-and-faq.md). +18. [Coming from Animate](coming-from-animate.md). ## Reference diff --git a/docs/guide/saved-commands.md b/docs/guide/saved-commands.md new file mode 100644 index 00000000..32a98228 --- /dev/null +++ b/docs/guide/saved-commands.md @@ -0,0 +1,80 @@ +# Saved commands + +Do the same few edits over and over? Keep them as a **saved command**: pick the steps in the +History panel, save them with a name, and run them again on any selection from the **Commands** +menu or with a key of your own. A saved command runs as **one undo step**, so a single Ctrl+Z +takes it all back. This works as Save As Command does in Animate. + +## Saving steps as a command + +1. Make the edits once on something selected (say, rotate it, fade it to 40 % and move it). +2. In the **History** panel (Window › History), **Ctrl+click** each step you want to keep. + **Shift+click** picks every step between the last one you picked and this one. A plain click + still goes back to that step, as before. You can also right-click a step and choose + **Pick for Save As Command**. +3. Click **Save As Command…** at the bottom of the panel (or right-click a step and choose it + there). +4. Give it a name and click **Save**. + +The dialog lists the picked steps in order. Some steps name a particular layer or object of this +document; where the command can work on the selection (or the active layer) instead, that's what +the saved command does, and the dialog says so ("acts on the selection"). A step that only makes +sense in this document, such as moving particular path points, placing a particular Library +item or using the clipboard, can't be kept: the dialog says which step and why, and **Save** +stays off until you Ctrl+click that step to take it out of the picks. + +Selecting things and moving the playhead aren't steps, so a saved command always works on what +is selected when you run it. + +## Running a saved command + +Your saved commands are at the end of the **Commands** menu, with their keys. Choose one and it +runs on the selection. If a step can't run (nothing is selected that it needs, say, or the layer +is locked), the command stops there, **nothing is changed**, and the status line names the step +that stopped it. + +**Commands › Run Command…** runs a saved command file without adding it to your list, for +example one a colleague sent you. + +## Managing saved commands + +**Commands › Manage Saved Commands…** lists your commands in their menu order. For each one: + +* **Run** runs it on the selection. +* **↑** and **↓** move it up or down the Commands menu. +* **Shortcut…** opens Keyboard Shortcuts on it, waiting for the keys you press. You can also find + it there yourself, under Commands. Keys you give a saved command follow it when you rename it. +* **Rename…** renames it. +* **Delete…** deletes it, after asking (undo can't bring a file back). + +**Add from File…** copies a saved command file into your commands. + +## Sharing saved commands + +Each saved command is a small JSON file in the `Commands` folder of your settings folder +(Preferences › About shows where). Send the file to share it; whoever receives it uses +**Run Command…** or **Add from File…**. The file's name is the command's name. + +Saved commands can do what [plug-ins](plugins.md) may do: change the document. They can't open +or save files, use the clipboard, change your preferences, run plug-ins or run other saved +commands, so a file from someone else can't do any of that either. Files that aren't saved +commands, or that ask for something they may not do, are refused with the reason. + +## On the command line and for AI assistants + +The same commands work [headless](working-headless.md): + +```sh +anicraft-cli run scene.anicraft "Turn and Fade.json" --save out.anicraft +anicraft-cli exec scene.anicraft macro.run '{"path": "Turn and Fade.json"}' +``` + +`anicraft-cli run` takes either a saved command or a plain list of `{cmd, params}`. Assistants +using the MCP server call `macro.run` through `anicraft_run`. `macro.history`, `macro.save`, +`macro.list`, `macro.rename`, `macro.move`, `macro.delete` and `macro.import` are in the +[command reference](reference/commands.md). + +## What isn't there yet + +Replaying picked steps without saving them, editing a saved command's steps in the app, saved +commands that ask for a value when they run, and saved commands in the browser version. diff --git a/docs/guide/workspace.md b/docs/guide/workspace.md index dca9e266..b5f9a18c 100644 --- a/docs/guide/workspace.md +++ b/docs/guide/workspace.md @@ -301,6 +301,10 @@ drag is always a single step. The **History** panel at the bottom of the dock li by name. Click any step to jump back to it, and click a later (dimmed) one to go forward again. +To keep steps you repeat, **Ctrl+click** them in the History panel and choose **Save As +Command…**: they come back at the end of the Commands menu, to run on any selection as one step. +See [Saved commands](saved-commands.md). + Undo history is kept in memory while the document is open. It isn't saved with the file. ## Right-click menus From f9bb09c4081c2760713e544cb7381104f55a0919 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:56:32 -0700 Subject: [PATCH 058/570] docs: roadmap and changelog for command macros (M6) --- CHANGELOG.md | 13 +++++++++++++ docs/roadmap.md | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9760d1e7..fc16fe84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +* **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 + selected as **one undo step**. Steps that name a layer or object of this document act on the + active layer or the selection instead; a step that can't be kept (the clipboard, particular + path points or Library items) is named with the reason. + * A run that fails at a step changes nothing and says which step stopped it. + * **Commands › Manage Saved Commands…**: run, reorder, rename, delete, give a **shortcut** (the + Keyboard Shortcuts editor, under Commands) and add one from a file. **Commands › Run + Command…** runs a saved command file. + * Saved commands are small JSON files in the settings folder's `Commands`, easy to share. They + may do only what a plug-in may (no files, clipboard or preferences), and plug-ins can't run + them. `anicraft-cli run` takes them; `macro.*` commands work headless and over MCP. * **Sound output polish** (ADR 0095, M5). * The playhead follows the sound being **heard**: the device's latency is taken off and slow frames are dropped rather than drifting (within a frame over an hour of play in tests). diff --git a/docs/roadmap.md b/docs/roadmap.md index 722af8cf..3e4438d7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -39,7 +39,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. | -| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | +| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); ~~command macros~~ ✅ first slice (ADR 0097: every undo step records its commands; History › Save As Command with steps rewritten to act on the selection or refused with the step named; saved commands at the end of the Commands menu with shortcuts; Manage Saved Commands; Run Command…; one transactional undo step; small JSON files in the settings folder; `macro.*` headless, CLI and MCP; macros call only what plug-ins may. Not yet: Replay Steps without saving, editing a macro's steps, macros that ask for values, the browser build and the command palette). **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: instances and shapes in one armature, reshaping at a posed frame); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); ~~AppImage desktop integration, portable mode, store readiness checks~~ ✅ (ADR 0094); next: store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groups in one dock, minimum sizes per panel, panel shortcut keys). | @@ -60,7 +60,7 @@ titled with its milestone. | M3 | GPU stage: GPU binning inside masks and groups, filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032, GPU binning and hairlines ✅ ADR 0048) | CPU oracle, tiled stage, GPU stage slices 1–4 | | M4 | Text from Animate files | XFL import, text engine (M5 first slice) | | M5 | Audio layers: import, waveform, playback sync | timeline, layers | -| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | +| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~command macros~~ ✅ first slice (ADR 0097); next: growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | | M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068), ~~tilt, texture, profiles in the merge~~ ✅ (ADR 0093); next: reading pen tilt from the toolkit, art brushes | strokes, Pen and Pencil, width profiles, timeline evaluation | | M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~portable mode and AppImage desktop integration~~ ✅ (ADR 0094), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~dockable panels and workspaces~~ ✅ first and second slices (ADR 0075, ADR 0087); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe | From cd7a9c0dd8ee20e1d1b53b8f93c0626d91de9dd1 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:56:46 -0700 Subject: [PATCH 059/570] docs: ADR 0097 takes its number; saved commands in the MCP and plug-in docs (M6) --- docs/adr/README.md | 1 - docs/mcp.md | 5 +++++ docs/plugins.md | 6 ++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/adr/README.md b/docs/adr/README.md index 2f429b1e..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0097 | (this track, M6) | Command macros (saved commands) | diff --git a/docs/mcp.md b/docs/mcp.md index ce1a3be1..b2590b37 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -43,6 +43,11 @@ with every release, and `anicraft_commands` lets it find what it needs. Frames i 0-based, as everywhere in the engine (the CLI's own `--frame` flags are 1-based, as in the timeline). +Saved commands (ADR 0097) run through `anicraft_run` too: `macro.run` with `{"path": …}` (a +saved command's file) or `{"steps": [{"cmd", "params"}]}` runs the steps as one undo step, and +unlike `anicraft_run_script` a failing step leaves the document as it was. `macro.history` and +`macro.save` turn the session's undo steps into a saved command. + ## Safety * Everything runs through the engine's commands, so params are checked and every edit can be diff --git a/docs/plugins.md b/docs/plugins.md index 353dd626..11289b42 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -44,6 +44,12 @@ anicraft-cli exec --sample plugin.run '{"id":"org.anicraft.star-field","params": --plugins examples/plugins/dist --save stars.anicraft ``` +## Saved commands share the rule + +A saved command (ADR 0097, History › Save As Command) may call exactly the commands a plug-in +may (`plugin_may_call`), and no `macro.*` command. Plug-ins may not call any `macro.*` command +either, so the two can never call each other. + ## The sandbox The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssembly interpreter From 9e2c64309135ecfcb8ba3dd54a4f97d30d3df996 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 00:59:12 -0700 Subject: [PATCH 060/570] fix(app): saved commands: History footer wraps in a narrow dock, plural and sample names for the catalogs (M6) --- src/app.rs | 4 +++- src/macros_ui.rs | 2 +- src/panels.rs | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/app.rs b/src/app.rs index 70002f13..916d8697 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1170,10 +1170,12 @@ impl App { } } else if let Some(folder) = crate::macros_ui::folder(self) { let f = folder.display().to_string(); - for (name, steps) in [("Turn, Fade and Nudge", json!([n - 3, n - 2, n - 1])), ("Quarter Turn", json!([n - 3])), ("Fade to 60 %", json!([n - 2]))] { + // i18n-exempt: sample names a user would type + for (name, steps) in [("Turn, Fade and Nudge", json!([n.saturating_sub(3), n.saturating_sub(2), n.saturating_sub(1)])), ("Quarter Turn", json!([n.saturating_sub(3)])), ("Fade to 60 %", json!([n.saturating_sub(2)]))] { let _ = self.s.execute("macro.save", &json!({"folder": f, "name": name, "history": steps, "confirm": true})); } crate::macros_ui::clear_picks(self); + // i18n-exempt: a sample name let id = crate::keymap::macro_id("Quarter Turn"); self.prefs.shortcuts.insert(id, vec!["Ctrl+Alt+R".into()]); crate::macros_ui::open_manage(self); diff --git a/src/macros_ui.rs b/src/macros_ui.rs index c580bdd7..83cc52ad 100644 --- a/src/macros_ui.rs +++ b/src/macros_ui.rs @@ -204,7 +204,7 @@ fn save_window(app: &mut App, ctx: &egui::Context) { let refused = d.steps.iter().filter(|s| s.refused.is_some()).count(); ui.add_space(4.0); if refused > 0 { - ui.label(text(Type::Caption, trn!("Take the step that can't be kept out of the picks (Ctrl+click it) to save the others.", "Take the {n} steps that can't be kept out of the picks (Ctrl+click them) to save the others.", refused)).color(T.error)); + ui.label(text(Type::Caption, trn!("Take the {n} step that can't be kept out of the picks (Ctrl+click it) to save the others.", "Take the {n} steps that can't be kept out of the picks (Ctrl+click them) to save the others.", refused)).color(T.error)); } else { ui.label(text(Type::Caption, tr!("It runs on whatever is selected when you choose it in the Commands menu."))); } diff --git a/src/panels.rs b/src/panels.rs index 7089a079..8d9d8c2b 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -627,10 +627,10 @@ pub(crate) fn history(app: &mut App, ui: &mut egui::Ui) { }); } }); - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { ui.set_min_height(crate::theme::TARGET); if picked.is_empty() { - ui.label(text(Type::Caption, tr!("Ctrl+click steps to save them as a command"))); + ui.add(egui::Label::new(text(Type::Caption, tr!("Ctrl+click steps to save them as a command"))).wrap()); } else { if ui.button(tr!("Save As Command…")).on_hover_text(tr!("Keep the picked steps as a command in the Commands menu, to run on any selection")).clicked() { save = true; From 8bf45991ac22cf6b11c198044b4c0d2f99cc2f76 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 04:07:12 -0700 Subject: [PATCH 061/570] perf(engine): registry lookups built once; macro.history checks steps without copying them (M6) find_command rebuilt the whole registry (~360 specs) on every call, and macro.history cloned every recorded command's params to list a step. panic_hunt_every_command (which runs macro.history about 600 times per session over up to 10,000 steps): over 40 min before, 144 s after (debug, Windows, this machine). The CLI test's failing file now selects first. --- crates/cli/src/lib.rs | 4 +- crates/engine/src/cmds_macro.rs | 72 ++++++++++++++++++++++----------- crates/engine/src/lib.rs | 15 ++++++- 3 files changed, 65 insertions(+), 26 deletions(-) diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index d9f21d60..90099c02 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -721,9 +721,9 @@ mod tests { let v: Value = serde_json::from_str(&out).unwrap(); assert_eq!((v["name"].as_str(), v["steps"].as_u64()), (Some("Spin"), Some(2)), "{out}"); // A failing step names itself and leaves nothing behind. - std::fs::write(&file, r#"{"steps": [{"cmd": "modify.rotate_cw"}, {"cmd": "layer.set_height", "params": {"height": 7}}]}"#).unwrap(); + std::fs::write(&file, r#"{"steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}, {"cmd": "layer.set_height", "params": {"height": 7}}]}"#).unwrap(); let e = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap_err(); - assert!(e.contains("stopped at step 2 of 2"), "{e}"); + assert!(e.contains("stopped at step 3 of 3"), "{e}"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/src/cmds_macro.rs b/crates/engine/src/cmds_macro.rs index dce54ad7..82cafb66 100644 --- a/crates/engine/src/cmds_macro.rs +++ b/crates/engine/src/cmds_macro.rs @@ -305,33 +305,37 @@ fn defaults_to_selection(doc: &str, key: &str) -> bool { }) } +/// Whether a recorded command can be kept: the params it would drop (they name this +/// document's layers or objects and the command can act on the selection or active layer +/// instead), or why it can't be kept. Reads only: listing a long history costs no copies. +fn check(cmd: &str, params: &Value) -> std::result::Result, String> { + macro_may_call(cmd)?; + let spec = crate::find_command(cmd).ok_or_else(|| format!("'{cmd}' is not a command any more"))?; + let mut dropped = Vec::new(); + for (k, v) in params.as_object().into_iter().flatten() { + let fixed = FIXED.contains(&k.as_str()) || (cmd.starts_with("bone.") && matches!(k.as_str(), "from" | "to")) || (cmd == "library.move" && k == "to"); + let target = TARGETS.iter().find(|t| **t == k.as_str()); + match target { + _ if v.is_null() => {} + Some(t) if !fixed && defaults_to_selection(spec.params, t) => dropped.push(*t), + None if !fixed => {} + _ => return Err(format!("it works on {} of this document", noun(k))), + } + } + Ok(dropped) +} + /// A recorded command as a saved command keeps it: its params without what names this /// document's layers and objects (and which of those went), or why it can't be kept. pub fn portable(cmd: &str, params: &Value) -> std::result::Result<(Value, Vec), String> { - macro_may_call(cmd)?; - let spec = crate::find_command(cmd).ok_or_else(|| format!("'{cmd}' is not a command any more"))?; - let Some(o) = params.as_object() else { return Ok((Value::Object(Map::new()), Vec::new())) }; - let mut out = Map::new(); - let mut dropped = Vec::new(); - for (k, v) in o { - let fixed = FIXED.contains(&k.as_str()) || (cmd.starts_with("bone.") && matches!(k.as_str(), "from" | "to")) || (cmd == "library.move" && k == "to"); - if v.is_null() || !(fixed || TARGETS.contains(&k.as_str())) { - out.insert(k.clone(), v.clone()); - } else if !fixed && defaults_to_selection(spec.params, k) { - dropped.push(k.clone()); - } else { - return Err(format!("it works on {} of this document", noun(k))); - } - } - Ok((Value::Object(out), dropped)) + let dropped = check(cmd, params)?; + let out: Map = params.as_object().into_iter().flatten().filter(|(k, _)| !dropped.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + Ok((Value::Object(out), dropped.into_iter().map(str::to_string).collect())) } /// An undo step as a saved command keeps it: its steps and the params dropped, or why not. fn keep_step(label: &str, cmds: Option<&[Recorded]>) -> std::result::Result<(Vec, Vec), String> { - let cmds = cmds.ok_or("it ran too many commands to keep (a very long drag?)")?; - if cmds.is_empty() { - return Err("it has nothing to run again".into()); - } + let cmds = usable(cmds)?; let mut steps = Vec::with_capacity(cmds.len()); let mut dropped = Vec::new(); for r in cmds { @@ -346,6 +350,28 @@ fn keep_step(label: &str, cmds: Option<&[Recorded]>) -> std::result::Result<(Vec Ok((steps, dropped)) } +fn usable(cmds: Option<&[Recorded]>) -> std::result::Result<&[Recorded], String> { + let cmds = cmds.ok_or("it ran too many commands to keep (a very long drag?)")?; + if cmds.is_empty() { + return Err("it has nothing to run again".into()); + } + Ok(cmds) +} + +/// [`keep_step`] without building the steps: how many commands, and the params dropped. +fn check_step(cmds: Option<&[Recorded]>) -> std::result::Result<(usize, Vec), String> { + let cmds = usable(cmds)?; + let mut dropped: Vec = Vec::new(); + for r in cmds { + for g in check(&r.cmd, &r.params)? { + if !dropped.iter().any(|d| d == g) { + dropped.push(g.to_string()); + } + } + } + Ok((cmds.len(), dropped)) +} + /// What dropped params mean for the step, in a sentence. fn rewritten_note(dropped: &[String]) -> Option { let layers = dropped.iter().any(|d| d.starts_with("layer")); @@ -366,10 +392,10 @@ fn history(s: &mut Session, _: &Value) -> Result { .enumerate() .map(|(i, (label, cmds))| { let mut v = json!({"index": i, "label": label, "undone": i >= done}); - match keep_step(label, cmds) { - Ok((steps, dropped)) => { + match check_step(cmds) { + Ok((n, dropped)) => { v["keep"] = json!(true); - v["commands"] = json!(steps.len()); + v["commands"] = json!(n); if let Some(note) = rewritten_note(&dropped) { v["rewritten"] = json!(note); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 748bdaa8..87991c30 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -197,7 +197,20 @@ pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[ ]; pub fn find_command(id: &str) -> Option { - commands().into_iter().find(|c| c.id == id) + // Built once: every command run looks itself up, and a saved command checks each of its + // steps (ADR 0097), so this must not rebuild the registry per call. + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX + .get_or_init(|| { + let mut m = std::collections::HashMap::new(); + for c in commands() { + // The first of a repeated id wins, as a search in registry order finds it. + m.entry(c.id).or_insert(c); + } + m + }) + .get(id) + .copied() } pub use history::{Recorded, Snapshot, StateId}; From 55c311583e52e6af3b717effec51dfa44b2bc82e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 04:39:38 -0700 Subject: [PATCH 062/570] test(app): saved commands: the Manage window, Commands menu, reorder, import and Save As Command draw and work (M6) --- src/macros_ui.rs | 2 +- src/macros_ui_tests.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/macros_ui.rs b/src/macros_ui.rs index 83cc52ad..f28219ae 100644 --- a/src/macros_ui.rs +++ b/src/macros_ui.rs @@ -55,7 +55,7 @@ pub struct SaveDialog { pub struct Manage { pub open: bool, /// The command being renamed and the name typed so far. - renaming: Option<(String, String)>, + pub(crate) renaming: Option<(String, String)>, focus: bool, } diff --git a/src/macros_ui_tests.rs b/src/macros_ui_tests.rs index 0c431153..67e5992f 100644 --- a/src/macros_ui_tests.rs +++ b/src/macros_ui_tests.rs @@ -73,6 +73,40 @@ fn picked_steps_save_as_a_command_and_its_shortcut_runs_it() { app.perform("macro.delete", json!({"folder": folder, "name": "Twirl", "confirm": true})); assert!(app.macros.list.is_empty()); assert!(app.prefs.shortcuts.keys().all(|k| keymap::macro_name(k).is_none())); + + // The windows and the menu draw, and their buttons work (same folder: this test owns it). + app.open_panel(Some("managecommands")); + assert!(app.macros.manage.open); + assert_eq!(app.macros.list.len(), 3, "the sample commands"); + for _ in 0..3 { + frame(&ctx, &mut app, vec![]); + } + let cmds = anicraft_engine::commands(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::menus::menu_contents(&mut app, ui, "Commands", &cmds)); + out.textures_delta.clear(); + // Reorder and rename through the same requests the buttons make. + let first = app.macros.list[0].name.clone(); + app.request("macro.move", json!({"folder": folder, "name": first, "index": 2})); + assert_eq!(app.macros.list[2].name, first); + app.macros.manage.renaming = Some((first.clone(), "Renamed".into())); + frame(&ctx, &mut app, vec![]); + crate::macros_ui::run_saved(&mut app, "Quarter Turn"); + assert_eq!(app.s.undo_label(), Some("Quarter Turn")); + // A file shared from elsewhere comes in through Add from File (the folder is filled in). + let shared = std::env::temp_dir().join(format!("anicraft-shared-{}.json", std::process::id())); + std::fs::write(&shared, r#"[{"cmd": "modify.rotate_ccw"}]"#).unwrap(); + app.request("macro.import", json!({"path": shared.display().to_string()})); + assert!(app.macros.list.iter().any(|c| c.name.starts_with("anicraft-shared"))); + let _ = std::fs::remove_file(&shared); + app.macros.manage.open = false; + // History with steps picked, and Save As Command over it. + app.open_panel(Some("savecommand")); + assert!(app.macros.save.is_some()); + for _ in 0..3 { + frame(&ctx, &mut app, vec![]); + } + crate::macros_ui::clear_picks(&mut app); + crate::macros_ui::open_save(&mut app); let _ = std::fs::remove_dir_all(&folder); } From 6bf256d85a9b3af7ba93e94d9b35804d9a026789 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 14 Nov 2026 04:51:26 -0700 Subject: [PATCH 063/570] test(app): test apps get no saved commands folder unless a test gives one (M6) The shell tests' sample commands shared a temporary folder with every test app in the process, so the pseudo-locale test met their names (user text) in the Commands menu. --- src/macros_ui.rs | 7 +++++++ src/macros_ui_tests.rs | 9 +++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/macros_ui.rs b/src/macros_ui.rs index f28219ae..3630a4fb 100644 --- a/src/macros_ui.rs +++ b/src/macros_ui.rs @@ -30,6 +30,10 @@ pub struct Macros { pub save: Option, /// Commands › Manage Saved Commands. pub manage: Manage, + /// Tests: this app's own folder. Test apps have none otherwise, so tests running side by + /// side never see each other's saved commands. + #[cfg(test)] + pub(crate) test_folder: Option, } /// A picked step as Save As Command keeps it. @@ -62,6 +66,9 @@ pub struct Manage { /// The folder the saved commands are in. Screenshot runs never touch the real one: they use a /// temporary folder (unless `ANICRAFT_COMMANDS_DIR` names one). None in a browser. pub fn folder(app: &App) -> Option { + #[cfg(test)] + return app.macros.test_folder.clone(); + #[cfg_attr(test, allow(unreachable_code))] if app.shot.is_some() && std::env::var_os("ANICRAFT_COMMANDS_DIR").is_none() && !crate::platform::WEB { return Some(std::env::temp_dir().join(format!("anicraft-commands-shot-{}", std::process::id()))); } diff --git a/src/macros_ui_tests.rs b/src/macros_ui_tests.rs index 67e5992f..afd807e4 100644 --- a/src/macros_ui_tests.rs +++ b/src/macros_ui_tests.rs @@ -22,10 +22,10 @@ fn frame(ctx: &egui::Context, app: &mut App, events: Vec) { fn picked_steps_save_as_a_command_and_its_shortcut_runs_it() { let ctx = egui::Context::default(); let mut app = app(&ctx); - // (The only test here that writes to the folder.) - if let Some(f) = crate::macros_ui::folder(&app) { - let _ = std::fs::remove_dir_all(&f); - } + // A folder of its own. + let dir = std::env::temp_dir().join(format!("anicraft-macros-ui-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + app.macros.test_folder = Some(dir); app.run("edit.select_all", json!({})); app.run("modify.rotate_cw", json!({})); app.run("element.set_color_effect", json!({"style": "alpha", "alpha": 50})); @@ -114,6 +114,7 @@ fn picked_steps_save_as_a_command_and_its_shortcut_runs_it() { fn a_step_that_cant_be_kept_is_named_in_the_dialog() { let ctx = egui::Context::default(); let mut app = app(&ctx); + app.macros.test_folder = Some(std::env::temp_dir().join(format!("anicraft-macros-ui-refused-{}", std::process::id()))); app.run("edit.select_all", json!({})); app.run("edit.copy", json!({})); app.run("edit.paste", json!({})); From db0d797e4c40616f6eff15d08ca9d1d9b8f1d603 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:45:55 +0100 Subject: [PATCH 064/570] Release: AniCraft v0.3.0 on main (#349) Co-authored-by: FredApps --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e4635038..893385b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -231,7 +231,7 @@ dependencies = [ [[package]] name = "anicraft" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-audio", "anicraft-doc", @@ -262,7 +262,7 @@ dependencies = [ [[package]] name = "anicraft-actions" -version = "0.2.1" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -270,14 +270,14 @@ dependencies = [ [[package]] name = "anicraft-audio" -version = "0.2.1" +version = "0.3.0" dependencies = [ "craft-audio", ] [[package]] name = "anicraft-cli" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-engine", @@ -290,7 +290,7 @@ dependencies = [ [[package]] name = "anicraft-doc" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-actions", "anicraft-audio", @@ -302,7 +302,7 @@ dependencies = [ [[package]] name = "anicraft-engine" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -328,7 +328,7 @@ dependencies = [ [[package]] name = "anicraft-geom" -version = "0.2.1" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -336,7 +336,7 @@ dependencies = [ [[package]] name = "anicraft-gpu" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -352,14 +352,14 @@ dependencies = [ [[package]] name = "anicraft-guide" -version = "0.2.1" +version = "0.3.0" dependencies = [ "pulldown-cmark", ] [[package]] name = "anicraft-plugins" -version = "0.2.1" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -370,7 +370,7 @@ dependencies = [ [[package]] name = "anicraft-render" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -383,7 +383,7 @@ dependencies = [ [[package]] name = "anicraft-svg" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -394,7 +394,7 @@ dependencies = [ [[package]] name = "anicraft-text" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-geom", "fontdb", @@ -404,7 +404,7 @@ dependencies = [ [[package]] name = "anicraft-xfl" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -418,7 +418,7 @@ dependencies = [ [[package]] name = "anicraft-xml" -version = "0.2.1" +version = "0.3.0" dependencies = [ "craft-xml", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index b98dd538..f65b98f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ default-members = [".", "crates/*"] [workspace.package] # 0.1.0 is the early alpha (release stage in src/app.rs, RELEASE_STAGE); see CHANGELOG.md # and docs/release.md. -version = "0.2.1" +version = "0.3.0" edition = "2024" license = "MIT OR Apache-2.0" # An application, not a library: not published to crates.io. From 5f5b5b3db6f9104fd3a87e7b5f937f7cc9468afc Mon Sep 17 00:00:00 2001 From: Juan Larrazabal Date: Sat, 14 Nov 2026 13:02:05 -0800 Subject: [PATCH 065/570] fix(engine): put a group's registration at the centre of its artwork (ADR 0073) A new group was stored with an identity transform, so the registration mark sat at the corner of the stage. It is now the centre of what was grouped. Members are stored relative to that point and the artwork stays where it was. Combine Objects uses the same centre when several colours become a group. --- CHANGELOG.md | 3 ++ crates/engine/src/cmds_group.rs | 47 ++++++++++++++++--- crates/engine/src/group_tests.rs | 36 +++++++++++--- ...combine-objects-and-selection-modifiers.md | 7 ++- docs/guide/reference/commands.md | 2 +- 5 files changed, 79 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4449c7e7..5cec578a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +* **Groups** (ADR 0073). + * A new group's registration point is the centre of what was grouped. The artwork stays + where it was. Edit the group to move the point. * **Sound output polish** (ADR 0095, M5). * The playhead follows the sound being **heard**: the device's latency is taken off and slow frames are dropped rather than drifting (within a frame over an hour of play in tests). diff --git a/crates/engine/src/cmds_group.rs b/crates/engine/src/cmds_group.rs index a77f893d..40fec49e 100644 --- a/crates/engine/src/cmds_group.rs +++ b/crates/engine/src/cmds_group.rs @@ -12,7 +12,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, LayerId, MAX_GROUP_DEPTH, Shape}; use anicraft_geom::planar::{self, Item}; -use anicraft_geom::{Affine, FillRule, Path}; +use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; use serde_json::{Value, json}; use std::collections::HashSet; use std::sync::Arc; @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Group", "Modify", Some("Ctrl+G"), - "{} puts the selected elements on each layer into one group there (ADR 0073), where the topmost of them was, and selects it → {group, members} (one layer) or {layers: [..]}. Members keep their places exactly: the group's transform starts as the identity. Raw shapes inside merge only with each other; double-click the group (symbol.edit) to edit it in place", + "{} puts the selected elements on each layer into one group there (ADR 0073), where the topmost of them was, and selects it → {group, members} (one layer) or {layers: [..]}. Members keep their places exactly. The group's registration point is the centre of what was grouped, and members are stored relative to it. Raw shapes inside merge only with each other; double-click the group (symbol.edit) to edit it in place", true, (|s, p| s.each_layer(true, |s| group(s, p))) as crate::RunFn, ), @@ -75,6 +75,31 @@ pub(crate) fn open_groups(s: &Session) -> usize { s.editing.iter().rev().take_while(|l| l.open.is_group()).count() } +/// Centre of `members` in this timeline's space. Empty or non-finite bounds stay at the origin. +fn members_center(doc: &anicraft_doc::Document, members: &[Arc]) -> Vec2 { + let mut r = Rect::EMPTY; + for e in members { + r = r.union(&e.bounds(doc)); + } + let c = r.center(); + if r.is_empty() || !c.is_finite() { Vec2::ZERO } else { c } +} + +/// Group transform at `center`, with `members` stored relative to it. The group's transform +/// times each member's is that member's old transform, so nothing moves. +fn recenter(center: Vec2, members: Vec>) -> (Affine, Vec>) { + let to_local = Affine::translate(-center.x, -center.y); + let members = members + .into_iter() + .map(|e| { + let mut e = Arc::unwrap_or_clone(e); + e.transform = to_local.mul(&e.transform); + Arc::new(e) + }) + .collect(); + (Affine::translate(center.x, center.y), members) +} + fn group(s: &mut Session, _: &Value) -> Result { let sel = s.selection.on(s.layer); if sel.is_empty() { @@ -83,8 +108,10 @@ fn group(s: &mut Session, _: &Value) -> Result { let layer_id = LayerId(s.doc.alloc_id()); let id = ElementId(s.doc.alloc_id()); let around = open_groups(s); - let kf = s.editable_keyframe()?; - let picked: Vec> = kf.elements.iter().filter(|e| sel.contains(&e.id)).cloned().collect(); + let picked: Vec> = { + let kf = s.editable_keyframe()?; + kf.elements.iter().filter(|e| sel.contains(&e.id)).cloned().collect() + }; if picked.is_empty() { return Err(EngineError::State("the selection is not on this keyframe".into())); } @@ -95,12 +122,16 @@ fn group(s: &mut Session, _: &Value) -> Result { if around + deepest + 1 > MAX_GROUP_DEPTH { return Err(EngineError::State(format!("groups nest at most {MAX_GROUP_DEPTH} deep"))); } + // Registration at the centre of this layer's members. Their transforms are relative to it. + let center = members_center(&s.doc, &picked); + let (transform, picked) = recenter(center, picked); + let n = picked.len(); + let kf = s.editable_keyframe()?; // Where the topmost member was, among what stays. let top = kf.elements.iter().rposition(|e| sel.contains(&e.id)).unwrap_or(0); let below = kf.elements.iter().take(top).filter(|e| !sel.contains(&e.id)).count(); kf.elements.retain(|e| !sel.contains(&e.id)); - let n = picked.len(); - let g = Element { id, name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::group(layer_id, picked) }; + let g = Element { id, name: String::new(), transform, color: ColorEffect::None, kind: ElementKind::group(layer_id, picked) }; let at = below.min(kf.elements.len()); kf.elements.insert(at, Arc::new(g)); s.select_only([id]); @@ -259,7 +290,9 @@ fn result_of(s: &mut Session, pieces: Vec>) -> Option { return Some(object(&mut s.doc, &joined(outline.iter()), Some(fill), None, color)); } let layer = LayerId(s.doc.alloc_id()); - Some(Element { id: ElementId(s.doc.alloc_id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::group(layer, pieces) }) + let center = members_center(&s.doc, &pieces); + let (transform, pieces) = recenter(center, pieces); + Some(Element { id: ElementId(s.doc.alloc_id()), name: String::new(), transform, color: ColorEffect::None, kind: ElementKind::group(layer, pieces) }) } } } diff --git a/crates/engine/src/group_tests.rs b/crates/engine/src/group_tests.rs index bf1221fb..aece6a7d 100644 --- a/crates/engine/src/group_tests.rs +++ b/crates/engine/src/group_tests.rs @@ -36,6 +36,21 @@ fn three() -> (Session, [ElementId; 3]) { (s, [a, b, c]) } +#[test] +fn a_groups_registration_is_the_centre_of_what_was_grouped() { + let (mut s, ids) = three(); + let before = picture(&s); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + let center = s.selection_bounds().center(); + run(&mut s, "modify.group", json!({})); + let at = top(&s)[0].transform.translation(); + assert!(at.distance(center) < 0.5, "registration {at:?}, centre of the artwork {center:?}"); + assert!(at.x > 1.0 && at.y > 1.0, "not the corner of the stage: {at:?}"); + assert_eq!(picture(&s), before, "grouping changes nothing drawn"); + run(&mut s, "modify.ungroup", json!({})); + assert_eq!(picture(&s), before, "ungrouping changes nothing drawn"); +} + #[test] fn group_and_ungroup_keep_every_members_place_exactly() { let (mut s, ids) = three(); @@ -91,14 +106,17 @@ fn a_group_opens_in_place_and_edits_there_with_every_tool() { let (mut s, ids) = three(); run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); let g = id_of(&run(&mut s, "modify.group", json!({})), "group"); + let reg = top(&s)[0].transform.translation(); run(&mut s, "modify.transform", json!({"a": 1, "b": 0, "c": 0, "d": 1, "e": 100, "f": 50})); + // The translation is applied on top of the registration, which is the artwork's centre. + let placed = reg + Vec2::new(100.0, 50.0); let steps = s.history_len(); let v = run(&mut s, "symbol.edit", json!({"id": g.0})); assert_eq!(v["editing"][0]["group"], json!(g.0), "{v}"); assert!(s.editing_group() && s.editing_symbol().is_none()); assert_eq!(s.history_len(), steps, "opening is not an edit"); let view = s.edit_view().unwrap_or_else(|| panic!("open")); - assert!(view.in_place && view.origin.distance(Vec2::new(100.0, 50.0)) < 1e-4, "{view:?}"); + assert!(view.in_place && view.origin.distance(placed) < 1e-3, "{view:?} registration {reg:?}"); // Inside: the members, in the group's space. assert_eq!(top(&s).len(), 3); run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "fill": "#123456"})); @@ -116,9 +134,10 @@ fn a_group_opens_in_place_and_edits_there_with_every_tool() { let members = top(&s)[0].kind.group_members(); assert_eq!(members.len(), 4); let new = members.last().cloned().unwrap_or_else(|| panic!("member")); - // The new rectangle sits at (100, 50) + its place inside, on the stage. - let b = s.element_bounds(g); - assert!(b.min.x <= 100.5 && b.min.y <= 50.5, "{b:?}"); + // The 10×10 rect was drawn at the group's local origin, so its own centre is 5 px from the registration. + let world = top(&s)[0].transform.mul(&new.transform).translation(); + let want = placed + Vec2::new(5.0, 5.0); + assert!(world.distance(want) < 1e-3, "new rect at {world:?}, want {want:?}"); assert!(matches!(new.kind, ElementKind::Shape(_))); // Undo goes back inside, where the change was made. run(&mut s, "edit.undo", json!({})); @@ -144,9 +163,11 @@ fn raw_shapes_in_a_group_merge_only_with_each_other() { assert_eq!(m.len(), 1); let ElementKind::Shape(sh) = &m[0].kind else { panic!("shape") }; assert!((even_odd_area(&sh.path, &m[0].transform) - 10_000.0).abs() < 1.0); - // The group sits above the raw drawing, as objects do... and inside, a raw square merges. + // The group sits above the raw drawing, as objects do. Inside, the square occupies local + // −50..50 (its registration is the centre). A raw square from local (0, −50) covers stage + // 50..150, 0..100 and joins it. run(&mut s, "symbol.edit", json!({"id": g.0})); - run(&mut s, "draw.rect", json!({"x": 50, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 0, "y": -50, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); let fills = top(&s); assert_eq!(fills.len(), 1, "one red fill: the two squares joined"); run(&mut s, "symbol.exit", json!({})); @@ -242,6 +263,9 @@ fn combine_objects_areas_are_exact() { assert_eq!(v["created"].as_array().map(Vec::len), Some(1)); assert!(matches!(top(&s)[0].kind, ElementKind::Group { .. })); assert!(near(&areas(&s), &[17_500.0]), "{:?}", areas(&s)); + // Two squares, 0..100 and 50..150: the group's registration is the centre of that union. + let at = top(&s)[0].transform.translation(); + assert!(at.distance(Vec2::new(75.0, 75.0)) < 1.0, "combine group registration {at:?}"); // Intersect: the overlap, in the top's colour. let mut s = Session::new(anicraft_doc::Document::default()); squares(&mut s); diff --git a/docs/adr/0073-groups-combine-objects-and-selection-modifiers.md b/docs/adr/0073-groups-combine-objects-and-selection-modifiers.md index 65804277..64974b4c 100644 --- a/docs/adr/0073-groups-combine-objects-and-selection-modifiers.md +++ b/docs/adr/0073-groups-combine-objects-and-selection-modifiers.md @@ -55,8 +55,9 @@ nothing was copied. 3. **Commands** (namespace `modify`, already allowed to plug-ins): * `modify.group` (Modify › Group, **Ctrl+G**): the selected elements on each layer become one - group there, at the topmost one's place in the stacking, its transform the identity, so - every member keeps its world transform bit for bit (tested). + group there, at the topmost one's place in the stacking. The group's registration point is + the centre of what was grouped, and each member is stored relative to that point, so the + artwork stays where it was (tested). Editing the group in place moves the registration. * `modify.ungroup` (Modify › Ungroup, **Ctrl+Shift+G**; Break Apart on a group does the same with fresh ids): members go back where the group was, each with `group · member` as its transform and the colour effects nested; they keep their ids unless a copy of the group was @@ -107,6 +108,8 @@ nothing was copied. * Animate users find Group, Ungroup and Combine Objects where they expect them, with the same keys; Animate files keep their groups. +* A group's registration point starts at the centre of its artwork, not the corner of the stage. + Edit the group to put that point somewhere else. The artwork does not jump when the group is made. * Measured on 288 raw shapes (12 × 12 outlined, rounded squares; optimised debug build): | Operation | Time | diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 63035678..87af1afd 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -199,7 +199,7 @@ This page is generated from the command registry, so it always matches the versi - **Break Apart** `modify.break_apart` · **Ctrl+B** (macOS **⌘B**) · changes the document Parameters: `{} the selected symbol instances become their contents, text becomes shapes, and drawing objects become raw shapes that merge with the raw shapes they touch` - **Group** `modify.group` · **Ctrl+G** (macOS **⌘G**) · changes the document - Parameters: `{} puts the selected elements on each layer into one group there (ADR 0073), where the topmost of them was, and selects it → {group, members} (one layer) or {layers: [..]}. Members keep their places exactly: the group's transform starts as the identity. Raw shapes inside merge only with each other; double-click the group (symbol.edit) to edit it in place` + Parameters: `{} puts the selected elements on each layer into one group there (ADR 0073), where the topmost of them was, and selects it → {group, members} (one layer) or {layers: [..]}. Members keep their places exactly. The group's registration point is the centre of what was grouped, and members are stored relative to it. Raw shapes inside merge only with each other; double-click the group (symbol.edit) to edit it in place` - **Ungroup** `modify.ungroup` · **Ctrl+Shift+G** (macOS **⇧⌘G**) · changes the document Parameters: `{} puts each selected group's members back on its layer where it was, each placed and coloured as the group showed it, and selects them; raw shapes among them merge with the drawing there → {members}` - **Union** `modify.union` · Modify › Combine Objects · changes the document From 9a00475491caf7406fd3a5fc969f43d1d1cd162f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 21:10:04 +0000 Subject: [PATCH 066/570] Use shared XFL document schema importer --- Cargo.lock | 6 +- Cargo.toml | 4 +- crates/xfl/src/import.rs | 130 ++++++++++++++++++++++++++------------- crates/xml/src/lib.rs | 53 ++++++++++++++-- 4 files changed, 142 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e4635038..e0e90ad5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1318,8 +1318,9 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87#f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" dependencies = [ + "craft-xml", "miniz_oxide 0.8.9", "thiserror 2.0.21", ] @@ -1327,9 +1328,10 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87#f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index b98dd538..aade1b20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 2596022c..bc484c53 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -41,6 +41,15 @@ struct RawHint { end: Option, } +struct PendingSymbol { + id: SymbolId, + name: String, + kind: SymbolKind, + linkage: Option, + item: X, + timeline: Option, +} + #[derive(Debug, thiserror::Error)] pub enum XflError { #[error("{0}")] @@ -237,7 +246,7 @@ struct Builder<'a> { /// refer to any symbol). ids: HashMap, /// Parsed symbol files waiting to be built, with their script class. - pending: Vec<(SymbolId, String, SymbolKind, Option, X)>, + pending: Vec, /// The language the document's frame scripts are written in (from its publish settings). language: Language, /// Library item name → bitmap id, for the bitmaps that could be read. @@ -632,64 +641,67 @@ impl<'a> Builder<'a> { } } - fn timeline(&mut self, tl: &X) -> Timeline { + fn timeline(&mut self, tl: &X, schema: &craft_xfl::document::TimelineModel) -> Timeline { let mut layers = Vec::new(); // Layers by their position in the file's layer list: `parentLayerIndex` points at a // layer's folder or mask. Links that don't fit AniCraft's rules are dropped by // `repair_masks` below. let mut by_index: Vec = Vec::new(); - for l in tl.list("layers").iter().filter(|l| l.name == "DOMLayer").take(MAX_LAYERS) { - let kind = match l.attr("layerType") { - Some("folder") => LayerKind::Folder, - Some("guide") => LayerKind::Guide, - Some("mask") => LayerKind::Mask, - _ => LayerKind::Normal, + for (l, schema_layer) in tl.list("layers").iter().filter(|l| l.name == "DOMLayer").take(MAX_LAYERS).zip(&schema.layers) { + let kind = match schema_layer.layer_type { + craft_xfl::document::LayerType::Folder => LayerKind::Folder, + craft_xfl::document::LayerType::Guide => LayerKind::Guide, + craft_xfl::document::LayerType::Mask => LayerKind::Mask, + craft_xfl::document::LayerType::Normal | craft_xfl::document::LayerType::Other => LayerKind::Normal, }; let id = LayerId(self.doc.alloc_id()); by_index.push(id); let mut layer = Layer::new(id, l.attr("name").unwrap_or("Layer")); layer.kind = kind; - layer.parent = l.u32("parentLayerIndex").and_then(|i| by_index.get(i as usize).copied()).filter(|p| *p != id); + layer.parent = schema_layer.parent_layer_index.and_then(|i| by_index.get(i as usize).copied()).filter(|p| *p != id); if kind == LayerKind::Folder { // A folder holds layers, never frames. layer.keyframes.clear(); - layer.visible = l.bool("visible").unwrap_or(true); - layer.locked = l.bool("locked").unwrap_or(false); + layer.visible = schema_layer.visible.unwrap_or(true); + layer.locked = schema_layer.locked.unwrap_or(false); layer.color = color(l, "color", "__none"); layers.push(Arc::new(layer)); continue; } - layer.visible = l.bool("visible").unwrap_or(true); - layer.locked = l.bool("locked").unwrap_or(false); - layer.outline = l.bool("outline").unwrap_or(false); + layer.visible = schema_layer.visible.unwrap_or(true); + layer.locked = schema_layer.locked.unwrap_or(false); + layer.outline = schema_layer.outline.unwrap_or(false); layer.color = color(l, "color", "__none"); // Layer Properties' height, 100 / 200 / 300 % (ADR 0061), as a multiple of a row. - layer.height_rows = l.u32("heightMultiplier").map_or(1, |h| h.clamp(1, u32::from(anicraft_doc::MAX_LAYER_HEIGHT)) as u8); + layer.height_rows = schema_layer.height_multiplier.map_or(1, |h| h.clamp(1, u32::from(anicraft_doc::MAX_LAYER_HEIGHT)) as u8); let mut keys = Vec::new(); let mut raw_hints: HashMap> = HashMap::new(); - for f in l.list("frames").iter().filter(|f| f.name == "DOMFrame") { - let start = f.u32("index").unwrap_or(0).min(MAX_FRAME); - let duration = f.u32("duration").unwrap_or(1).clamp(1, MAX_FRAME); + for (f, schema_frame) in l.list("frames").iter().filter(|f| f.name == "DOMFrame").zip(&schema_layer.frames) { + let start = schema_frame.index.unwrap_or(0).min(MAX_FRAME); + let duration = schema_frame.duration.unwrap_or(1).clamp(1, MAX_FRAME); let mut k = Keyframe::new(start, duration); // A frame's name is a label (or an anchor, a label too); a comment is a note // to the animator that nothing can go to, which AniCraft has no place for yet. - if f.attr("labelType").map(str::trim) == Some("comment") { + if schema_frame.is_comment { self.report.skip("frame comments"); } else { k.label = f.attr("name").unwrap_or("").chars().take(256).collect(); } - match f.attr("tweenType") { - Some(t @ ("motion" | "shape")) => { - let kind = if t == "shape" { TweenKind::Shape } else { TweenKind::Classic }; + match schema_frame.tween_type { + craft_xfl::document::TweenType::Motion | craft_xfl::document::TweenType::Shape => { + let kind = + if schema_frame.tween_type == craft_xfl::document::TweenType::Shape { TweenKind::Shape } else { TweenKind::Classic }; let orient = f.bool("motionTweenOrientToPath").unwrap_or(false); - if kind == TweenKind::Classic && f.attr("motionTweenRotate").is_some_and(|r| matches!(r.trim(), "clockwise" | "counter-clockwise")) { + if kind == TweenKind::Classic + && f.attr("motionTweenRotate").is_some_and(|r| matches!(r.trim(), "clockwise" | "counter-clockwise")) + { self.report.skip("tween spins (turned the shortest way)"); } let (easing, groups) = self.easing(f); k.tween = Some(Tween { easing, kind, orient, groups }); } - Some("motion object") => self.report.skip("motion tweens (kept as keyframes)"), - _ => {} + craft_xfl::document::TweenType::MotionObject => self.report.skip("motion tweens (kept as keyframes)"), + craft_xfl::document::TweenType::Other => {} } // Shape hints sit on both keyframes of a shape tween; they are paired up below. if let Some(h) = f.child("shapeHints").filter(|h| !h.children.is_empty()) { @@ -1137,13 +1149,28 @@ impl<'a> Builder<'a> { } // A damaged symbol file is left out (its instances with it), not the whole // document (#226). - let item = match (self.read)(&format!("LIBRARY/{href}")).map(|b| b.map(|b| xml::parse(&b))) { - Ok(Some(Ok(item))) => item, + let bytes = match (self.read)(&format!("LIBRARY/{href}")) { + Ok(Some(bytes)) => bytes, Ok(None) => { self.report.skip("missing library files"); continue; } - Err(_) | Ok(Some(Err(_))) => { + Err(_) => { + self.report.skip("library files that couldn't be read"); + continue; + } + }; + let parsed = match craft_xfl::document::Document::parse(&bytes) { + Ok(parsed) => parsed, + Err(_) => { + self.report.skip("library files that couldn't be read"); + continue; + } + }; + let (model, xml_root) = parsed.into_parts(craft_xfl::document::ModelLimits { max_timelines: 0, max_layers_per_timeline: MAX_LAYERS }); + let item = match xml::from_craft_xml_owned(xml_root) { + Ok(item) => item, + Err(_) => { self.report.skip("library files that couldn't be read"); continue; } @@ -1162,7 +1189,7 @@ impl<'a> Builder<'a> { let id = SymbolId(self.doc.alloc_id()); let linkage = self.linkage(&item); self.ids.insert(name.clone(), id); - self.pending.push((id, name, kind, linkage, item)); + self.pending.push(PendingSymbol { id, name, kind, linkage, item, timeline: model.symbol_timeline }); } Ok(()) } @@ -1233,9 +1260,9 @@ impl<'a> Builder<'a> { } fn build_symbols(&mut self) { - for (id, name, kind, linkage, item) in std::mem::take(&mut self.pending) { - let timeline = match item.child("timeline").and_then(|t| t.child("DOMTimeline")) { - Some(tl) => self.timeline(tl), + for PendingSymbol { id, name, kind, linkage, item, timeline: schema_timeline } in std::mem::take(&mut self.pending) { + let timeline = match item.child("timeline").and_then(|t| t.child("DOMTimeline")).zip(schema_timeline.as_ref()) { + Some((tl, schema)) => self.timeline(tl, schema), None => Timeline { layers: vec![Arc::new(Layer::new(LayerId(self.doc.alloc_id()), "Layer 1"))] }, }; let short = name.rsplit('/').next().unwrap_or(&name).to_string(); @@ -1280,11 +1307,26 @@ pub fn import_with_fonts(read: &Reader<'_>, fonts: &Fonts) -> Result<(Document, fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Document, Report), XflError> { let bytes = read("DOMDocument.xml")?.ok_or_else(|| XflError::NotXfl("no DOMDocument.xml".into()))?; - let root = xml::parse(&bytes)?; + let parsed = craft_xfl::document::Document::parse(&bytes).map_err(xml::from_craft_error)?; + let (schema, xml_root) = + parsed.into_parts(craft_xfl::document::ModelLimits { max_timelines: anicraft_doc::MAX_SCENES, max_layers_per_timeline: MAX_LAYERS }); + let root = xml::from_craft_xml_owned(xml_root)?; if root.name != "DOMDocument" { return Err(XflError::NotXfl(format!("the root element is <{}>", root.name))); } - let mut b = Builder { doc: Document::default(), read, ids: HashMap::new(), pending: Vec::new(), language: Language::ActionScript3, bitmaps: HashMap::new(), sounds: HashMap::new(), videos: HashMap::new(), report: Report::default(), fonts, faces: HashMap::new() }; + let mut b = Builder { + doc: Document::default(), + read, + ids: HashMap::new(), + pending: Vec::new(), + language: Language::ActionScript3, + bitmaps: HashMap::new(), + sounds: HashMap::new(), + videos: HashMap::new(), + report: Report::default(), + fonts, + faces: HashMap::new(), + }; b.publish_settings()?; // Only symbols keep a script class yet. for _ in root.list("media").iter().filter(|m| m.attr("linkageClassName").is_some_and(|c| !c.trim().is_empty())) { @@ -1292,12 +1334,13 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do } b.doc.library.clear(); b.doc.scenes.clear(); + let stage = schema.stage; b.doc.stage = Stage { - width: root.f32("width").unwrap_or(550.0).clamp(1.0, 8192.0) as u32, - height: root.f32("height").unwrap_or(400.0).clamp(1.0, 8192.0) as u32, - fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0), + width: stage.width.unwrap_or(550.0).clamp(1.0, 8192.0) as u32, + height: stage.height.unwrap_or(400.0).clamp(1.0, 8192.0) as u32, + fps: stage.frame_rate.unwrap_or(24.0).clamp(1.0, 120.0), // Animate leaves the default, white, out of the file (#163). - background: if root.attr("backgroundColor").is_some() { color(&root, "backgroundColor", "__none") } else { Rgba::WHITE }, + background: if stage.has_background_color { color(&root, "backgroundColor", "__none") } else { Rgba::WHITE }, }; b.register_folders(&root); b.register_bitmaps(&root)?; @@ -1307,9 +1350,10 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do b.build_symbols(); // Every DOMTimeline is a scene, in order. let scenes: Vec<&X> = root.list("timelines").iter().filter(|t| t.name == "DOMTimeline").take(anicraft_doc::MAX_SCENES).collect(); - for (i, tl) in scenes.iter().enumerate() { - let name: String = tl.attr("name").filter(|n| !n.trim().is_empty()).map_or_else(|| format!("Scene {}", i + 1), |n| n.chars().take(256).collect()); - let timeline = b.timeline(tl); + for (i, (tl, schema_timeline)) in scenes.iter().zip(&schema.timelines).enumerate() { + let name: String = + tl.attr("name").filter(|n| !n.trim().is_empty()).map_or_else(|| format!("Scene {}", i + 1), |n| n.chars().take(256).collect()); + let timeline = b.timeline(tl, schema_timeline); b.doc.scenes.push(Arc::new(Scene { name, timeline, guides: Vec::new() })); } if !b.doc.library_tree.folders.is_empty() { @@ -1345,7 +1389,9 @@ fn fla_from(data: &[u8], fonts: Option<&Fonts>) -> Result<(Document, Report), Xf return Err(XflError::NotXfl("the file is too large".into())); } if data.starts_with(&OLE_MAGIC) { - return Err(XflError::NotXfl("this .fla was saved by Flash CS4 or earlier, in a format AniCraft can't read: open it in Animate and save it again".into())); + return Err(XflError::NotXfl( + "this .fla was saved by Flash CS4 or earlier, in a format AniCraft can't read: open it in Animate and save it again".into(), + )); } let archive = crate::zip::Archive::open(data)?; let root = package_root(&archive)?; diff --git a/crates/xml/src/lib.rs b/crates/xml/src/lib.rs index 3d3d5d92..f9b0ff99 100644 --- a/crates/xml/src/lib.rs +++ b/crates/xml/src/lib.rs @@ -79,7 +79,9 @@ fn options() -> craft_xml::Options<'static> { } } -fn map_error(error: craft_xml::Error) -> XmlError { +/// Keeps AniCraft's historical diagnostics when a shared parser entry point returns a +/// `craft-xml` error directly. +pub fn from_craft_error(error: craft_xml::Error) -> XmlError { match error { craft_xml::Error::TooLarge(_) => XmlError::TooLarge, craft_xml::Error::TooDeep(_) => XmlError::TooDeep, @@ -140,16 +142,57 @@ fn convert(source: &craft_xml::El, mixed: &[&str], used: &mut usize) -> Result Result { + use craft_xml::Node; + + charge_item(used)?; + let craft_xml::El { name, attrs, children } = source; + let is_mixed = mixed.contains(&local(&name)); + let has_elements = children.iter().any(|node| matches!(node, Node::El(_))); + let mut element = Element { name, ..Element::default() }; + for (name, value) in attrs { + element.attrs.insert(name, value); + } + for node in children { + match node { + Node::El(child) => element.children.push(convert_owned(child, mixed, used)?), + Node::Text(text) | Node::CData(text) => { + element.text.push_str(&text); + if is_mixed { + charge_item(used)?; + element.children.push(text_node(&text)); + } + } + Node::Pi { .. } | Node::Comment(_) => {} + } + } + if !is_mixed && has_elements && element.text.trim().is_empty() { + element.text.clear(); + } + Ok(element) +} + +/// Converts the shared XML tree into AniCraft's compatibility tree without reparsing bytes. +pub fn from_craft_xml(source: &craft_xml::El) -> Result { + let mut used = 0; + convert(source, &[], &mut used) +} + +/// Converts and consumes the shared XML tree without retaining a second copy during conversion. +pub fn from_craft_xml_owned(source: craft_xml::El) -> Result { + let mut used = 0; + convert_owned(source, &[], &mut used) +} + /// Parses a document and returns its root element. pub fn parse(src: &[u8]) -> Result { - let root = options().parse(src).map_err(map_error)?; - let mut used = 0; - convert(&root, &[], &mut used) + let root = options().parse(src).map_err(from_craft_error)?; + from_craft_xml(&root) } /// Parses a document whose `mixed` elements keep character stretches among their children. pub fn parse_mixed(src: &[u8], mixed: &[&str]) -> Result { - let root = options().parse(src).map_err(map_error)?; + let root = options().parse(src).map_err(from_craft_error)?; let mut used = 0; convert(&root, mixed, &mut used) } From 4f07f0924ee09dfba6b044810e1fe3b537b16275 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 21:18:51 +0000 Subject: [PATCH 067/570] Use shared XFL publish settings model --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 13 +++++-------- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0e90ad5..fdd4f810 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1318,7 +1318,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87#f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" +source = "git+https://github.com/storytold/craft-libs?rev=2942da9a3569a809cee50bb7d6c3632793fd994a#2942da9a3569a809cee50bb7d6c3632793fd994a" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87#f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" +source = "git+https://github.com/storytold/craft-libs?rev=2942da9a3569a809cee50bb7d6c3632793fd994a#2942da9a3569a809cee50bb7d6c3632793fd994a" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index aade1b20..2b900958 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "f215740d1dab55ef8aa1a0fa69bf30bbdffb1a87" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "2942da9a3569a809cee50bb7d6c3632793fd994a" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2942da9a3569a809cee50bb7d6c3632793fd994a" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index bc484c53..64560785 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -1239,18 +1239,15 @@ impl<'a> Builder<'a> { fn publish_settings(&mut self) -> Result<(), XflError> { // Optional: settings that can't be read leave the defaults (#226). let Ok(Some(bytes)) = (self.read)("PublishSettings.xml") else { return Ok(()) }; - let Ok(root) = xml::parse(&bytes) else { return Ok(()) }; - let profiles: Vec<&X> = root.children.iter().filter(|c| c.name == "flash_profile").collect(); - let profile = profiles.iter().find(|p| p.bool("current") == Some(true)).or(profiles.first()).copied().unwrap_or(&root); - let flash = profile.child("PublishFlashProperties").unwrap_or(profile); - let text = |name: &str| flash.child(name).map(|e| e.text.trim().to_string()).filter(|t| !t.is_empty()); - self.language = match text("ActionScriptVersion").as_deref() { + let Ok(document) = craft_xfl::document::Document::parse(&bytes) else { return Ok(()) }; + let settings = document.publish_settings(); + self.language = match settings.action_script_version.as_deref() { Some("1" | "2") => Language::ActionScript1or2, _ => Language::ActionScript3, }; - if let Some(class) = text("DocumentClass") { + if let Some(class) = settings.document_class { if anicraft_doc::actions::valid_class_name(&class) { - self.doc.document_class = class; + self.doc.document_class = class.to_string(); self.report.keep("document class"); } else { self.report.skip("document classes that aren't class names (left out)"); From 47510fb16c5e2aca564117039d50072967f9c8e0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 21:25:45 +0000 Subject: [PATCH 068/570] Use shared XFL package root selection --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 13 ++++--------- crates/xfl/src/lib.rs | 2 +- 4 files changed, 9 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fdd4f810..93beb35e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1318,7 +1318,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2942da9a3569a809cee50bb7d6c3632793fd994a#2942da9a3569a809cee50bb7d6c3632793fd994a" +source = "git+https://github.com/storytold/craft-libs?rev=4801a54e3c6082af7063e9f451da50b2db22a6e2#4801a54e3c6082af7063e9f451da50b2db22a6e2" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2942da9a3569a809cee50bb7d6c3632793fd994a#2942da9a3569a809cee50bb7d6c3632793fd994a" +source = "git+https://github.com/storytold/craft-libs?rev=4801a54e3c6082af7063e9f451da50b2db22a6e2#4801a54e3c6082af7063e9f451da50b2db22a6e2" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 2b900958..b0977270 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "2942da9a3569a809cee50bb7d6c3632793fd994a" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2942da9a3569a809cee50bb7d6c3632793fd994a" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "4801a54e3c6082af7063e9f451da50b2db22a6e2" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4801a54e3c6082af7063e9f451da50b2db22a6e2" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 64560785..ac77519e 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -1401,15 +1401,10 @@ fn fla_from(data: &[u8], fonts: Option<&Fonts>) -> Result<(Document, Report), Xf /// `__MACOSX` folder some zip tools add beside it is ignored. An archive holding several /// documents in top folders is refused with their names rather than one picked. fn package_root(archive: &crate::zip::Archive<'_>) -> Result { - if archive.names().any(|n| n == "DOMDocument.xml") { - return Ok(String::new()); - } - let mut tops: Vec<&str> = archive.names().filter_map(|n| n.strip_suffix("/DOMDocument.xml")).filter(|top| !top.contains('/') && *top != "__MACOSX").collect(); - tops.sort_unstable(); - match tops.as_slice() { - [] => Ok(String::new()), - [top] => Ok(format!("{top}/")), - many => { + match archive.xfl_package_root() { + crate::zip::XflPackageRoot::Document | crate::zip::XflPackageRoot::Missing => Ok(String::new()), + crate::zip::XflPackageRoot::Folder(top) => Ok(format!("{top}/")), + crate::zip::XflPackageRoot::Multiple(many) => { let names: Vec = many.iter().take(5).map(|t| t.chars().take(80).collect()).collect(); let more = if many.len() > 5 { format!(" and {} more", many.len() - 5) } else { String::new() }; Err(XflError::NotXfl(format!("the archive holds {} Animate documents ({}{more}): unzip it and open one of them", many.len(), names.join(", ")))) diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index 81a4ba18..1a2b119c 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -14,7 +14,7 @@ pub mod video; pub use anicraft_xml as xml; /// XFL/FLA ZIP package reader, shared with other consumers through `craft-xfl`. pub mod zip { - pub use craft_xfl::{Archive, MAX_DEPTH, MAX_ENTRIES, MAX_ENTRY, MAX_RATIO, MAX_TOTAL, ZipError, crc32}; + pub use craft_xfl::{Archive, MAX_DEPTH, MAX_ENTRIES, MAX_ENTRY, MAX_RATIO, MAX_TOTAL, XflPackageRoot, ZipError, crc32}; #[cfg(test)] pub(crate) use crate::pack; From 74c235627613412cd3ae6855655d7e6148cd10ce Mon Sep 17 00:00:00 2001 From: Juan Larrazabal Date: Sat, 14 Nov 2026 13:28:38 -0800 Subject: [PATCH 069/570] feat(colour): fill and stroke alpha (ADR 0097) The colour picker keeps an alpha on a solid fill and on a stroke, and each gradient stop keeps its own. A brush stroke that is not fully opaque stays its own shape, and the pen-down preview is already that alpha. --- CHANGELOG.md | 8 + crates/engine/src/brush_tests.rs | 62 ++++++++ crates/engine/src/cmds_brush.rs | 31 +++- crates/engine/src/cmds_draw.rs | 4 +- crates/engine/src/cmds_paint.rs | 2 +- docs/adr/0097-fill-alpha.md | 43 ++++++ docs/adr/README.md | 1 + docs/guide/coming-from-animate.md | 2 +- docs/guide/reference/commands.md | 8 +- docs/roadmap.md | 2 +- src/brushtool.rs | 235 +++++++++++++++++++++++++++++- src/colour.rs | 29 +++- src/colour_panel.rs | 46 +++++- src/panels.rs | 59 ++++---- 14 files changed, 470 insertions(+), 62 deletions(-) create mode 100644 docs/adr/0097-fill-alpha.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4449c7e7..6345c476 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +* **Fill and stroke alpha** (ADR 0097). + * The colour picker sets an alpha on a solid fill and on a stroke, from clear to opaque. + A clear fill is still a fill. No fill is the type None. + * Each stop of a linear or radial gradient keeps its own alpha, so a ramp can fade. The + stop's marker shows that alpha. + * A brush stroke that is not fully opaque stays its own shape, so the colour behind it + shows through and crossings darken. Opaque strokes still join. Group bundles the + separate strokes. The ink is drawn at that alpha while the pen is down. * **Sound output polish** (ADR 0095, M5). * The playhead follows the sound being **heard**: the device's latency is taken off and slow frames are dropped rather than drifting (within a frame over an hour of play in tests). diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index a75f16c1..002b65a3 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -142,6 +142,68 @@ fn paint_normal_covers_and_merges_with_raw_shapes() { assert_eq!(reds, 1, "brush strokes of one colour join"); } +#[test] +fn a_wash_stays_its_own_shape_and_composites() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": BLUE, "stroke": null})); + let r = run(&mut s, "draw.brush", json!({"points": stroke(50.0, 150.0, 350.0, 150.0), "size": 20, "color": "#ff000080"})); + assert_eq!(r["merged"], false, "a wash is not cut into the drawing"); + let blue = shapes(&s).iter().filter(|(sh, _)| fill_of(sh) == Some(Rgba::hex(0x0000ff))).count(); + assert_eq!(blue, 1, "the rectangle behind the wash is still one shape"); + let drawn = shapes(&s); + let wash = drawn.iter().find(|(sh, _)| fill_of(sh).is_some_and(|c| c.r > 0.9 && c.a < 1.0)).expect("the wash"); + let wash_a = fill_of(&wash.0).expect("solid wash").a; + assert!(!wash.0.merge && (wash_a - 128.0 / 255.0).abs() < 0.01, "{wash_a}"); + // A second wash of the same colour crosses it and stays separate, so the overlap darkens. + run(&mut s, "draw.brush", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20, "color": "#ff000080"})); + let washes = shapes(&s).iter().filter(|(sh, _)| fill_of(sh).is_some_and(|c| c.a < 1.0)).count(); + assert_eq!(washes, 2, "washes of one colour do not join"); + let px = |x, y| anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().pixel(x, y).unwrap(); + let one = px(120, 150); + let two = px(200, 150); + let bare = px(150, 120); + assert!(bare[2] > 0.9 && bare[0] < 0.1, "blue only: {bare:?}"); + assert!(one[0] > 0.35 && one[0] < 0.65 && one[2] > 0.35 && one[2] < 0.65, "one wash over blue: {one:?}"); + assert!(two[0] > one[0] + 0.1 && two[2] < one[2] - 0.1, "two washes darken: {one:?} {two:?}"); +} + +#[test] +fn pressure_opacity_and_a_clear_gradient_stay_separate() { + let mut s = blank(false); + let pts: Vec = (0..=20).map(|i| json!([i as f32 * 10.0, 80.0, 0.25])).collect(); + let r = run(&mut s, "draw.brush", json!({"points": pts, "size": 16, "color": RED, "pressure_opacity": true, "pressure_size": false})); + assert_eq!(r["merged"], false); + let drawn = shapes(&s); + let (sh, _) = drawn.last().expect("the stroke"); + let a = fill_of(sh).expect("a solid").a; + assert!(!sh.merge && (a - 0.25).abs() < 0.02, "average pressure is the alpha: {a}"); + + let mut g = blank(false); + run(&mut g, "draw.rect", json!({"x": 40, "y": 40, "w": 80, "h": 40, "fill": BLUE, "stroke": null})); + run(&mut g, "paint.set_fill", json!({"type": "linear", "selection": false, "stops": [{"offset": 0, "color": "#ff0000ff"}, {"offset": 1, "color": "#ff000000"}]})); + let r = run(&mut g, "draw.brush", json!({"points": stroke(20.0, 60.0, 140.0, 60.0), "size": 12})); + assert_eq!(r["merged"], false); + assert_eq!(shapes(&g).iter().filter(|(sh, _)| fill_of(sh) == Some(Rgba::hex(0x0000ff))).count(), 1, "the rectangle is not cut"); + assert!(shapes(&g).iter().any(|(sh, _)| matches!(sh.fill, Some(Paint::Linear { .. })) && !sh.merge)); + + // An opaque gradient still joins the drawing. + let mut o = blank(false); + run(&mut o, "draw.rect", json!({"x": 40, "y": 40, "w": 80, "h": 40, "fill": BLUE, "stroke": null})); + run(&mut o, "paint.set_fill", json!({"type": "linear", "selection": false, "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#00ff00"}]})); + let r = run(&mut o, "draw.brush", json!({"points": stroke(20.0, 60.0, 140.0, 60.0), "size": 12})); + assert_eq!(r["merged"], true); +} + +#[test] +fn a_translucent_paint_brush_line_does_not_merge() { + let mut s = blank(false); + let r = run(&mut s, "draw.brush", json!({"points": stroke(10.0, 10.0, 80.0, 10.0), "size": 8, "as_stroke": true, "color": "#ff000080"})); + assert_ne!(r["merged"], true); + let (sh, _) = &shapes(&s)[0]; + let a = sh.stroke.as_ref().map(|st| st.color.a).unwrap_or(1.0); + assert!(!sh.merge && (a - 128.0 / 255.0).abs() < 0.01, "{a}"); +} + #[test] fn paint_behind_only_fills_empty_areas() { for object in [false, true] { diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index 0eb593e3..36c01802 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -1,6 +1,7 @@ //! The Brush tool's command (ADR 0033): a stroke of the brush paints a filled shape, the area its -//! tip sweeps, in the fill colour. Off Object Drawing it is a raw shape that merges with the -//! drawing (ADR 0031), placed by the paint mode. +//! tip sweeps, in the fill colour. Off Object Drawing an opaque stroke merges with the drawing +//! (ADR 0031), placed by the paint mode. A fill that is not fully opaque stays its own shape and +//! composites over what is behind it (ADR 0097). use crate::brush_library::{BUILTIN, BrushLibrary, BrushPreset, MAX_FILE_BYTES, MAX_USER_PRESETS, builtin, builtin_hint, clean_name}; use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param}; @@ -20,7 +21,7 @@ pub fn specs() -> Vec { c( "draw.brush", "Brush Stroke", - "{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}", + "{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object? (default the Object Drawing setting; a fill that is not fully opaque is its own shape, so it composites over what is behind it)}", true, draw_brush as crate::RunFn, ), @@ -225,6 +226,17 @@ pub fn pressure_opacity(b: &BrushPreset, pts: &[Sample]) -> f32 { (pts.iter().map(|x| b.curve.map(x.pressure)).sum::() / pts.len() as f32).clamp(0.05, 1.0) } +/// A fill that is not fully opaque has to stay its own shape. Merge drawing replaces what the +/// new shape covers, so a wash would hide the colour behind it, and two washes of one colour +/// would join instead of darkening where they cross (ADR 0097). +fn paint_stacks(p: &Paint) -> bool { + match p { + Paint::Solid(c) => c.a < 1.0, + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => stops.iter().any(|s| s.color.a < 1.0), + Paint::Bitmap { .. } => false, + } +} + fn draw_brush(s: &mut Session, p: &Value) -> Result { let pts = bounded_samples(p)?; let b = brush_param(s, p)?; @@ -296,18 +308,20 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { Some(_) if p.get("color").is_none_or(Value::is_null) && color.a >= 1.0 => s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()), _ => Paint::Solid(color), }; + // Opaque ink joins the drawing. A wash stays its own shape and composites (ADR 0097). + let own = object || paint_stacks(&fill); let id = ElementId(s.doc.alloc_id()); let el = Element { id, name: String::new(), transform: Affine::translate(c.x, c.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !own, warp: None }), }; if s.editable_keyframe()?.elements.len() >= 100_000 { return Err(EngineError::State("too many elements on this keyframe".into())); } - if object { + if own { let kf = s.editable_keyframe()?; match order { // Behind everything on the layer. @@ -356,7 +370,8 @@ const PROFILE_TOLERANCE: f32 = 0.015; /// The Paint Brush (ADR 0068): the smoothed centre line as a stroke of the brush's size in the /// stroke colour, its width profile following the pressure and tapers, so the Width tool edits -/// it afterwards. A stroke of one width is a plain line and merges like the Pencil's. +/// it afterwards. A stroke of one width is a plain line and merges like the Pencil's. A line +/// that is not fully opaque stays its own shape (ADR 0097). fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32, tol: f32, color: Rgba, object: bool) -> Result { let (path, factors) = centre_stroke(pts, &b.shaping(), smoothing, tol * 0.25, PROFILE_SAMPLES); if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { @@ -366,7 +381,9 @@ fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32 let profile = WidthProfile::new(kept.iter().map(|(t, f)| WidthPoint::new(*t, *f, *f)).collect()); let stroke = Stroke::new(color, b.size).with_profile(profile); let c = path.bounds().center(); - let mut v = add_shape(s, "paint_brush", path.transformed(&Affine::translate(-c.x, -c.y)), c, None, Some(stroke), object)?; + // A translucent line stays its own shape too, so it composites instead of replacing. + let own = object || color.a < 1.0; + let mut v = add_shape(s, "paint_brush", path.transformed(&Affine::translate(-c.x, -c.y)), c, None, Some(stroke), own)?; v["width_points"] = json!(kept.len()); Ok(v) } diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 74095142..c390d954 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -27,8 +27,8 @@ pub fn specs() -> Vec { c("element.pick", "Select at Point", "", None, "{x, y, add?: bool, view?: stage|camera} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer; with `view: camera` the point is on the movie's picture as the camera shows it (each layer through its depth)", false, pick), c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel", true, translate), c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), - c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), - c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), + c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | \"#rrggbbaa\" | null} (the alpha is the fill's own; 00 is a clear fill, not the same as null)", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), + c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | \"#rrggbbaa\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera has no opacity (no Alpha style, alpha multiplier or offset)", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))), c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))), diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index 411447a6..1643089d 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Fill", "", None, - "{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: \"#rrggbb\" | \"#rrggbbaa\"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}", + "{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid, \"#rrggbb\" or \"#rrggbbaa\"), stops?: [{offset: 0..1, color: \"#rrggbb\" | \"#rrggbbaa\"}, ..] (2 to 15; each stop has its own alpha), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}", true, set_fill, ), diff --git a/docs/adr/0097-fill-alpha.md b/docs/adr/0097-fill-alpha.md new file mode 100644 index 00000000..ba5dc5ab --- /dev/null +++ b/docs/adr/0097-fill-alpha.md @@ -0,0 +1,43 @@ +# ADR 0097: Fill alpha + +* Status: proposed +* Relates to: ADR 0074 (the fill picker and gradients), ADR 0078 (swatches) + +## Context + +In Flash, the colour you picked for a fill was not only a hue. The mixer had an alpha, and a +light wash was how people built glass, smoke, shadows and fades without a second shape. A +gradient did the same per stop: one end of a ramp could be the colour and the other end +nothing, or two stops could be the same colour at two different strengths. That is a different +thing from no fill. No fill means the shape has no interior. A clear fill is still there. You +can select it, erase it, and use it as an alpha mask. + +The document already stores that alpha on a solid colour and on every gradient stop, and the +renderer already paints it. The solid fill picker threw it away and hid the Alpha control. A +gradient stop kept its alpha in the file, and the picker could edit it, but the stop's marker +was always drawn opaque, so a fade did not show on the handles. + +## Decision + +1. **A solid fill and a stroke carry alpha.** The colour picker (Tools squares, the Colour + panel, Properties) shows a labeled Alpha row: a slider and a percent, 0% clear, 100% + opaque. Hex may be `#rrggbb` or `#rrggbbaa`. Choosing a swatch keeps the alpha you had. + None is still no fill, not a clear one. +2. **Each gradient stop keeps its own alpha.** The ramp blends them, including through + Linear RGB (the alpha is not gamma-corrected). The stop's marker is drawn at that alpha, + and its name says the percent. +3. **A brush stroke that is not fully opaque stays its own shape, and you see that alpha + while the pen is down.** Merge drawing would cut away the colour underneath, so a wash + could not show what is behind it, and two washes of one colour would join instead of + darkening where they cross. Opaque ink still joins. Modify › Group bundles the separate + strokes. The ink drawn before the pen lifts is already that alpha, as one coverage, so + lifting does not change it. Pressure that drives opacity uses the stroke's average, the + same average the finished stroke keeps. + +## Consequences + +* An older file with no alpha byte stays opaque. +* A saved solid that omitted alpha still reads as opaque. +* Alpha 0 is a fill the hit test and the eraser can still find. Removing the fill is None. +* A wash does not join the raw drawing. Group still bundles those strokes. An opaque stroke + joins as before. diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..11e2e191 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0097 | (outside contribution) | Fill alpha | diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 0134c835..438a0edd 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -28,7 +28,7 @@ Animator and Designer, plus your own saved workspaces and Reset. | Output | The Output panel inside Test Movie, and **Window › Output**, which keeps the last run's lines. | | Align | The Align panel on the right, and **Modify › Align**. | | History | The History panel on the right. | -| Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, overflow and Linear RGB, like the Color panel. **Window › Swatches** keeps the document's colours and gradients (click applies to the active stroke or fill, drag to reorder, import and export swatch files and GIMP `.gpl` palettes; not Adobe `.aco`/`.ase`/`.clr`). | +| Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer, a hex field and an alpha. A solid fill's alpha is its own (0% is a clear fill, which is not the same as no fill). The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, each with its own alpha, overflow and Linear RGB, like the Color panel. **Window › Swatches** keeps the document's colours and gradients (click applies to the active stroke or fill, drag to reorder, import and export swatch files and GIMP `.gpl` palettes; not Adobe `.aco`/`.ase`/`.clr`). | | Transform and Info | Position, scale and rotation rows in Properties, and the Free Transform tool. | | Scene | The scene menu at the top left of the stage, **Insert › Scene** and **Modify › Scene**. | | Find and Replace | **Edit › Find and Replace** (**Ctrl+F**). | diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 63035678..cbbfc2e3 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -496,9 +496,9 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Transform** `element.set_transform` · changes the document Parameters: `{x?, y?, sx?, sy?, rotation? (degrees)}` - **Fill Colour** `element.set_fill` · changes the document - Parameters: `{color: "#rrggbb" | null}` + Parameters: `{color: "#rrggbb" | "#rrggbbaa" | null} (the alpha is the fill's own; 00 is a clear fill, not the same as null)` - **Stroke** `element.set_stroke` · changes the document - Parameters: `{color?: "#rrggbb" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}` + Parameters: `{color?: "#rrggbb" | "#rrggbbaa" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}` - **Alpha** `element.set_alpha` · changes the document Parameters: `{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)` - **Colour Effect** `element.set_color_effect` · changes the document @@ -598,7 +598,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Movie Explorer** `explorer.tree` Parameters: `{scope?: document (default) | scene, show?: {text?, symbols?, scripts?, media?, frames? (layers and keyframes)} (each default true), definitions?: bool (the Library's symbols; default true), expanded?: [row keys] (default: the top rows), all?: bool (everything open), filter?: text (rows whose names hold it, and the rows above them), offset?, limit? (default 1000, at most 10000)} → {rows: [{key, depth, kind, type?, name, extra, frame?, children, open, go: find.goto params}], total, truncated}` - **Brush Stroke** `draw.brush` · changes the document - Parameters: `{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}` + Parameters: `{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object? (default the Object Drawing setting; a fill that is not fully opaque is its own shape, so it composites over what is behind it)}` - **Brush Presets** `brush.preset_list` Parameters: `{} the built-in brushes and yours, with their settings` - **Save Brush** `brush.preset_save` @@ -650,7 +650,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Apply Style** `paint.apply_style` · changes the document Parameters: `{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)` - **Fill** `paint.set_fill` · changes the document - Parameters: ``{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: "#rrggbb" | "#rrggbbaa"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}`` + Parameters: ``{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid, "#rrggbb" or "#rrggbbaa"), stops?: [{offset: 0..1, color: "#rrggbb" | "#rrggbbaa"}, ..] (2 to 15; each stop has its own alpha), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}`` - **Gradient Transform** `paint.transform_fill` · changes the document Parameters: `{element?: id (default: the selected shapes with a gradient or bitmap fill), frame?: [a, b, c, d, e, f] (the fill's frame in the space being edited: the box -1..1 onto a linear gradient's span, a radial gradient's ring or one copy of a bitmap), or changes made in this order: scale_x?, scale_y?, scale? (along the frame's own axes), skew_x?, skew_y? (degrees, along its axes), rotate? (degrees, about its centre), move?: [dx, dy], center?: [x, y]; focal?: -0.98..0.98 (radial)} moves, turns, scales or skews where a gradient or bitmap fill lies, as the Gradient Transform tool (F) does → {changed, frames: [[a, b, c, d, e, f], ..]}` - **Lock Fill** `paint.lock_fill` diff --git a/docs/roadmap.md b/docs/roadmap.md index 64a84a17..00cf0733 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -11,7 +11,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). **Mid-session failures** (ADR 0092): a broken GPU stage hands the stage to the CPU at once with a status-bar notice and a log line, and is retried with a bounded backoff; driver errors on the window's device are logged instead of panicking (the #255 `Surface::configure` panic), and a lost window device autosaves and reopens the window on a safer way. Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Painted weights and reshaping** (ADR 0090): the Bind tool's **Paint Weights** brush (Add, Subtract, Smooth; size with `[`/`]`, strength; soft falloff) paints a bone's share onto the points under it, shown live as a heat map (blue none to red all) on the outline and points; weights stay normalised per point (the other bones share the rest, a point's only bone gives way to its nearest other bones), painted points are hand-bound, one undo step per stroke (1.15 ms for 32 dabs over 20,000 points); a focused point's weights as numbers in Properties › Bone (keyboard); Subselection edits a bound shape's outline at the rest pose (move, add, delete, smooth/corner) keeping the binding: moved points keep their weights, new points blend their neighbours', deleted points drop theirs, the rest pose exact; `bone.paint_weights`, `bone.set_weight`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084 and 0090), reshaping at a posed frame, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | -| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | +| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field, an alpha (a solid fill's own, and a different one on each gradient stop) and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format ` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | diff --git a/src/brushtool.rs b/src/brushtool.rs index 9a3c85dd..2a537c62 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -343,6 +343,37 @@ fn hull(mut pts: Vec) -> Vec { /// Most preview pieces drawn per frame (a long stroke skips samples in the preview only). const MAX_PREVIEW: usize = 4000; +/// Longest side of the live-alpha coverage image, in pixels. A stroke larger than this is +/// drawn softer rather than uploading a full-screen texture every move. +const MASK_MAX: usize = 2048; + +/// The alpha the finished stroke will have: the fill (or the stroke colour) times, when +/// pressure drives opacity, the average mapped pressure so far. That average is what the +/// command stores for the whole stroke (ADR 0068). +fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option)]) -> f32 { + let paint_a = if paint_a.is_finite() { paint_a.clamp(0.0, 1.0) } else { 1.0 }; + if !o.pressure_opacity || samples.is_empty() { + return paint_a; + } + // The same stand-in `points` sends for a sample that is still waiting on a reading. + let Some(first) = samples.iter().find_map(|(_, p)| *p) else { return paint_a }; + let mut prev = first; + let mut seen = false; + let mut sum = 0.0f32; + for (_, p) in samples { + let p = if let Some(p) = *p { + seen = true; + prev = p; + p + } else if !seen { + first + } else { + prev + }; + sum += o.curve.map(p); + } + paint_a * (sum / samples.len() as f32).clamp(0.05, 1.0) +} /// The paint as it goes (each pair of samples is the hull of the tip at both, so the union is /// what the stroke covers before smoothing), and the tip under the pointer. @@ -354,9 +385,16 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option= 255.0 { + let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint }); + draw_sweep(painter, xf, &tip, &app.brush_samples, color); + } else { + draw_sweep_alpha(painter, xf, &tip, &app.brush_samples, paint, alpha); + } } if let Some(h) = hover { // The tip's size and shape at the pointer, as Animate shows it. @@ -387,6 +425,173 @@ pub fn draw_sweep(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[ } } +/// The tip's outline at each step, in screen points (the union is the stroke's coverage). +fn sweep_hulls(xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)]) -> Vec> { + if samples.is_empty() { + return Vec::new(); + } + let unit = o.unit_outline(); + let screen = |at: Vec2, pressure: Option| -> Vec { + let m = o.tip_to_stage(at, o.factor(pressure)); + unit.iter().map(|u| xf.to_screen(m.apply(*u))).collect() + }; + let step = samples.len().div_ceil(MAX_PREVIEW).max(1); + let picked: Vec<&(Vec2, Option)> = samples.iter().step_by(step).chain(samples.last()).collect(); + let mut hulls = Vec::new(); + let mut push = |pts: Vec| { + let h = hull(pts); + if h.len() >= 3 { + hulls.push(h); + } + }; + if let [only] = picked.as_slice() { + push(screen(only.0, only.1)); + } + for pair in picked.windows(2) { + let &[a, b] = pair else { continue }; + let mut pts = screen(a.0, a.1); + pts.extend(screen(b.0, b.1)); + push(pts); + } + hulls +} + +/// The same sweep as one coverage image, tinted at `alpha`. Overlapping pieces keep the +/// greater coverage, so a crossing in one stroke stays one alpha. +fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)], paint: anicraft_engine::doc::Rgba, alpha: f32) { + if alpha <= 0.0 { + return; + } + let hulls = sweep_hulls(xf, o, samples); + if hulls.is_empty() { + return; + } + let mut bounds = egui::Rect::NOTHING; + for hull in &hulls { + for p in hull { + bounds.extend_with(*p); + } + } + let view = bounds.expand(1.0).intersect(painter.clip_rect()); + if !view.is_positive() || !view.width().is_finite() || !view.height().is_finite() { + return; + } + let ppp = painter.pixels_per_point(); + let mut scale = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; + let long = view.width().max(view.height()) * scale; + if long > MASK_MAX as f32 && long.is_finite() { + scale *= MASK_MAX as f32 / long; + } + let w = (view.width() * scale).round(); + let h = (view.height() * scale).round(); + if !w.is_finite() || !h.is_finite() || w < 1.0 || h < 1.0 { + return; + } + let w = (w as usize).clamp(1, MASK_MAX); + let h = (h as usize).clamp(1, MASK_MAX); + let cov = coverage(&hulls, view.min, scale, w, h); + let mut pixels = Vec::with_capacity(w.saturating_mul(h)); + for c in cov { + let a = (c.clamp(0.0, 1.0) * 255.0).round() as u8; + pixels.push(egui::Color32::from_white_alpha(a)); + } + let image = egui::ColorImage::new([w, h], pixels); + let tex = sweep_texture(painter.ctx(), image); + let tint = to_color32(anicraft_engine::doc::Rgba { a: alpha, ..paint }); + painter.image(tex.id(), view, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint); +} + +/// One reused texture for the live wash, so a stroke does not leak a texture every frame. +fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage) -> egui::TextureHandle { + let id = egui::Id::new("anicraft.brush.sweep"); + let options = egui::TextureOptions::LINEAR; + if let Some(mut tex) = ctx.data(|d| d.get_temp::(id)) { + tex.set(image, options); + tex + } else { + let tex = ctx.load_texture("brush-sweep", image, options); + ctx.data_mut(|d| d.insert_temp(id, tex.clone())); + tex + } +} + +/// Coverage in `0..=1`, one value per pixel. A pixel covered more than once keeps the greater +/// value, so the stroke is one alpha. +fn coverage(hulls: &[Vec], origin: Pos2, scale: f32, w: usize, h: usize) -> Vec { + let mut cov = vec![0.0f32; w.saturating_mul(h)]; + let view = egui::Rect::from_min_size(origin, egui::vec2(w as f32 / scale, h as f32 / scale)); + for hull in hulls { + if hull.len() < 3 || !hull_hits(hull, view) { + continue; + } + fill_convex(&mut cov, w, h, hull, origin, scale); + } + cov +} + +fn hull_hits(poly: &[Pos2], view: egui::Rect) -> bool { + let mut b = egui::Rect::NOTHING; + for p in poly { + if p.x.is_finite() && p.y.is_finite() { + b.extend_with(*p); + } + } + b.intersects(view) +} + +/// Scan-converts one convex polygon into `cov` (pixel rows are the image, y down). +fn fill_convex(cov: &mut [f32], w: usize, h: usize, poly: &[Pos2], origin: Pos2, scale: f32) { + let pts: Vec<(f32, f32)> = poly.iter().filter(|p| p.x.is_finite() && p.y.is_finite()).map(|p| ((p.x - origin.x) * scale, (p.y - origin.y) * scale)).collect(); + if pts.len() < 3 || !scale.is_finite() || scale <= 0.0 { + return; + } + let (mut top, mut bot) = (f32::MAX, f32::MIN); + for (_, y) in &pts { + top = top.min(*y); + bot = bot.max(*y); + } + if !top.is_finite() || !bot.is_finite() { + return; + } + let iy0 = (top.floor() as i32).max(0); + let iy1 = (bot.ceil() as i32).min(h as i32); + let n = pts.len(); + for iy in iy0..iy1 { + let y = iy as f32 + 0.5; + let mut left = f32::MAX; + let mut right = f32::MIN; + for i in 0..n { + let (x0, y0) = pts[i]; + let (x1, y1) = pts[(i + 1) % n]; + // The scanline crosses the edge. A vertex on the scanline counts once. + if !((y0 <= y && y1 > y) || (y1 <= y && y0 > y)) { + continue; + } + let t = (y - y0) / (y1 - y0); + let x = x0 + (x1 - x0) * t; + if !x.is_finite() { + continue; + } + left = left.min(x); + right = right.max(x); + } + // No crossing, or a crossing thinner than a pixel. Non-finite x was skipped above. + if right <= left { + continue; + } + let ix0 = (left.floor() as i32).max(0); + let ix1 = (right.ceil() as i32).min(w as i32); + for ix in ix0..ix1 { + let x0 = ix as f32; + let span = (right.min(x0 + 1.0) - left.max(x0)).clamp(0.0, 1.0); + let Some(slot) = cov.get_mut(iy as usize * w + ix as usize) else { continue }; + if span > *slot { + *slot = span; + } + } + } +} + /// The tip's outline at stage point `at`. pub fn draw_tip(painter: &egui::Painter, xf: Xf, o: &BrushOptions, at: Vec2) { let m = o.tip_to_stage(at, 1.0); @@ -449,4 +654,28 @@ mod tests { let h = hull(vec![Pos2::new(0.0, 0.0), Pos2::new(1.0, 0.0), Pos2::new(0.5, 0.2), Pos2::new(1.0, 1.0), Pos2::new(0.0, 1.0), Pos2::new(0.0, 0.0)]); assert_eq!(h.len(), 4, "{h:?}"); } + + #[test] + fn the_preview_alpha_is_the_fill_times_the_pressure_average() { + let mut o = BrushOptions::default(); + let samples = [(Vec2::ZERO, Some(0.25)), (Vec2::new(10.0, 0.0), Some(0.25))]; + assert!((intended_alpha(&o, 0.5, &samples) - 0.5).abs() < 1e-5, "pressure off leaves the fill"); + o.pressure_opacity = true; + assert!((intended_alpha(&o, 1.0, &samples) - 0.25).abs() < 1e-3, "the average so far"); + assert!((intended_alpha(&o, 0.5, &samples) - 0.125).abs() < 1e-3, "fill alpha times that average"); + let light = [(Vec2::ZERO, Some(0.0))]; + assert!((intended_alpha(&o, 1.0, &light) - 0.05).abs() < 1e-3, "the same floor as the command"); + } + + #[test] + fn a_wash_preview_is_one_coverage_where_the_pieces_overlap() { + let square = |x: f32, y: f32| vec![Pos2::new(x, y), Pos2::new(x + 10.0, y), Pos2::new(x + 10.0, y + 10.0), Pos2::new(x, y + 10.0)]; + let cov = coverage(&[square(0.0, 0.0), square(4.0, 4.0)], Pos2::ZERO, 1.0, 16, 16); + let at = |x: usize, y: usize| cov[y * 16 + x]; + assert!(at(2, 2) > 0.99, "inside the first square"); + assert!(at(12, 2) < 0.01, "outside both"); + assert!(at(6, 6) > 0.99 && at(6, 6) <= 1.0, "the overlap stays one coverage, not two: {}", at(6, 6)); + let edge = coverage(&[vec![Pos2::new(0.5, 0.0), Pos2::new(10.0, 0.0), Pos2::new(10.0, 10.0), Pos2::new(0.5, 10.0)]], Pos2::ZERO, 1.0, 12, 12); + assert!((edge[5 * 12] - 0.5).abs() < 0.05, "the cut pixel is a partial: {}", edge[5 * 12]); + } } diff --git a/src/colour.rs b/src/colour.rs index 5f322867..287d8f9b 100644 --- a/src/colour.rs +++ b/src/colour.rs @@ -1,6 +1,7 @@ //! Colour swatches and the colour picker (#201, #246, #248), as Animate's swatch popup: a click //! on a swatch opens the web-safe palette with the colours used lately below it, a hex field, -//! and the full mixer (hue, saturation and value, alpha) one click away. +//! and, when the colour has opacity, an Alpha row (0 % clear, 100 % opaque). The mixer +//! (hue, saturation and value) is one click away. //! //! The 216 web-safe colours are the open standard cube (each channel 00, 33, 66, 99, CC or FF), //! laid out as the usual six-by-six blocks: red steps across the blocks, green down a block and @@ -230,15 +231,31 @@ pub(crate) fn picker(ui: &mut egui::Ui, popup: Id, c: &mut [u8; 4], alpha: bool, remember(ui.ctx(), popup, [h[0], h[1], h[2]]); changed = true; } - if alpha { + }); + // Its own row, with the word on it. A bare percent beside the hex does not read as opacity. + if alpha { + ui.add_space(4.0); + ui.horizontal(|ui| { + let tip = tr!("Alpha: 0 % is clear, 100 % opaque"); + ui.label(tr!("Alpha")).on_hover_text(tip); let mut pct = f32::from(c[3]) / 255.0 * 100.0; - let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).suffix(" %").max_decimals(0))).named(tr!("Alpha")); - if r.on_hover_text(tr!("Alpha: 0 % is clear, 100 % opaque")).changed() { + ui.spacing_mut().slider_width = 148.0; + // The theme's slider rail is the popup's own colour, so the bar would vanish into it. + let name = tr!("Alpha"); + let bar = ui.scope(|ui| { + let v = ui.visuals_mut(); + v.widgets.inactive.bg_fill = T.hover; + v.selection.bg_fill = T.accent; + ui.add(egui::Slider::new(&mut pct, 0.0..=100.0).show_value(false)) + }).inner.named(name); + let num = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).range(0.0..=100.0).suffix(" %").max_decimals(0).speed(0.5))).named(name); + let r = bar.union(num); + if r.on_hover_text(tip).changed() { c[3] = (pct.clamp(0.0, 100.0) / 100.0 * 255.0).round() as u8; changed = true; } - } - }); + }); + } changed } diff --git a/src/colour_panel.rs b/src/colour_panel.rs index 1b84d5e9..3fdd60bc 100644 --- a/src/colour_panel.rs +++ b/src/colour_panel.rs @@ -26,8 +26,8 @@ const BAR_WIDTH: f32 = 270.0; /// What the fill picker asks for. #[derive(Clone, Debug, PartialEq)] pub enum FillEdit { - /// A solid colour (opaque). - Solid([u8; 3]), + /// A solid colour, unmultiplied, alpha in the last byte. 0 is a clear fill, not "no fill". + Solid([u8; 4]), /// No fill (true), or a fill again (false). None(bool), /// `paint.set_fill` params, with its undo label; `live` while a drag or typing goes on (one @@ -162,7 +162,7 @@ pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, paint: Option<&Pai fn kinds() -> [(&'static str, &'static str, &'static str); 5] { [ ("none", tr!("None"), tr!("No fill")), - ("solid", tr!("Solid"), tr!("Solid colour")), + ("solid", tr!("Solid"), tr!("A solid colour, from clear to opaque")), ("linear", tr!("Linear"), tr!("Linear gradient: colours along a line")), ("radial", tr!("Radial"), tr!("Radial gradient: colours out from a centre")), ("bitmap", tr!("Bitmap"), tr!("Bitmap fill: a Library image, tiled")), @@ -200,7 +200,7 @@ pub fn fill_picker(ui: &mut egui::Ui, popup: Id, paint: Option<&Paint>, bitmaps: "solid" => match paint { // A fill again: the colour it shows. None => FillEdit::None(false), - Some(p) => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "solid", "color": hex(p.primary_color().with_alpha(1.0))}) }, + Some(p) => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "solid", "color": hex(p.primary_color())}) }, }, "bitmap" => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "bitmap", "bitmap": bitmaps.first().map_or(0, |b| b.0)}) }, other => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": other}) }, @@ -213,7 +213,7 @@ pub fn fill_picker(ui: &mut egui::Ui, popup: Id, paint: Option<&Paint>, bitmaps: } Some(Paint::Solid(c)) => { let mut px = bytes(*c); - crate::colour::picker(ui, popup, &mut px, false, None).then_some(FillEdit::Solid([px[0], px[1], px[2]])) + crate::colour::picker(ui, popup, &mut px, true, None).then_some(FillEdit::Solid(px)) } Some(Paint::Linear { stops, spread, linear_rgb, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, None), Some(Paint::Radial { stops, spread, linear_rgb, focal, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, Some(*focal)), @@ -405,7 +405,8 @@ fn stop_bar(ui: &mut egui::Ui, popup: Id, stops: &mut Vec) -> Opti let hit = Rect::from_center_size(pos2(x, track.center().y), vec2(12.0, 14.0)); let r = ui.interact(hit, popup.with(("fill_stop_marker", i)), Sense::click_and_drag()); let at = format!("{:.0}", off * 100.0); - a11y::control(ui, &r, WidgetType::Button, &tr!("Colour stop {stop} of {count} at {at}%", stop = i + 1, count = count, at = at), Some(i == sel)); + let alpha = stops.get(i).map(|s| format!("{:.0}", s.color.sanitized().a * 100.0)).unwrap_or_else(|| "100".into()); + a11y::control(ui, &r, WidgetType::Button, &tr!("Colour stop {stop} of {count} at {at}%, alpha {alpha}%", stop = i + 1, count = count, at = at, alpha = alpha), Some(i == sel)); if r.clicked() || r.drag_started() || r.gained_focus() { sel = i; } @@ -445,7 +446,9 @@ fn stop_bar(ui: &mut egui::Ui, popup: Id, stops: &mut Vec) -> Opti let tip = pos2(x, track.top()); let body = [tip, pos2(x + 6.0, track.top() + 6.0), pos2(x + 6.0, track.bottom()), pos2(x - 6.0, track.bottom()), pos2(x - 6.0, track.top() + 6.0)]; let edge = if i == sel { T.accent } else if r.hovered() { T.text } else { T.control_edge }; - let fill = to_color32(st.color.with_alpha(if torn { 0.3 } else { 1.0 })); + // The marker shows that stop's own alpha, so a fade along the ramp is visible on the handles. + let shown = st.color.sanitized(); + let fill = to_color32(shown.with_alpha(shown.a * if torn { 0.35 } else { 1.0 })); ui.painter().add(egui::Shape::convex_polygon(body.to_vec(), fill, Stroke::new(if i == sel { 2.0 } else { 1.0 }, edge))); } ui.data_mut(|d| match tearing { @@ -599,7 +602,7 @@ mod tests { assert!(matches!(app.s.style.fill_paint, Some(Paint::Linear { .. }))); // Solid and None are the caller's: apply_set leaves them alone. let before = app.s.doc.clone(); - apply_set(&mut app, &FillEdit::Solid([1, 2, 3]), true); + apply_set(&mut app, &FillEdit::Solid([1, 2, 3, 255]), true); apply_set(&mut app, &FillEdit::None(true), true); assert!(app.s.doc == before); // The whole window draws with the Tools square's picker open on the selection's gradient, @@ -613,4 +616,31 @@ mod tests { assert_eq!(stops_json(&[stop(0.0, 0xff0000)])[0]["color"], "#ff0000"); assert_eq!(from_bytes(bytes(Rgba::new(1.0, 0.0, 0.0, 0.5))).a, 128.0 / 255.0); } + + /// A solid fill keeps the alpha it was given, a gradient keeps a different alpha on each + /// stop, and the open fill picker names an Alpha control for either. + #[test] + fn a_fill_keeps_its_alpha_and_the_picker_names_it() { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(PathBuf::from("unused.png"))); + app.run("draw.rect", json!({"x": 10, "y": 10, "w": 40, "h": 30, "fill": "#ff000080", "stroke": null})); + let Paint::Solid(c) = current(&app).0 else { panic!("a solid fill"); }; + assert!((c.a - 128.0 / 255.0).abs() < 1e-3, "{c:?}"); + app.run("paint.set_fill", json!({"type": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff00"}]})); + let paint = current(&app).0; + let stops = paint.stops().expect("a gradient"); + assert!((stops[0].color.a - 1.0).abs() < 1e-3 && stops[1].color.a < 1e-3, "{stops:?}"); + app.run("paint.set_fill", json!({"type": "solid", "color": "#3d8bfd80"})); + app.tool = Tool::Select; + app.open_fill_swatch = true; + let mut labels = String::new(); + for _ in 0..4 { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + labels = out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().filter_map(|(_, n)| n.label().map(str::to_string)).collect::>().join("\n")).unwrap_or_default(); + } + assert!(labels.contains("Alpha"), "the fill picker has no Alpha control:\n{labels}"); + } } diff --git a/src/panels.rs b/src/panels.rs index ea88621d..bf55766e 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -174,7 +174,7 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { for (fill, resp) in [(true, fill_resp), (false, stroke_resp)] { let name = if fill { tr!("Fill colour") } else { tr!("Stroke colour") }; a11y::control(ui, &resp, WidgetType::ColorButton, name, None); - let resp = resp.on_hover_text(if fill { tr!("Fill colour: click to pick the colour shapes are filled with") } else { tr!("Stroke colour: click to pick the colour of lines and outlines") }); + let resp = resp.on_hover_text(if fill { tr!("Fill colour: click to pick the colour and how clear it is. Each stop of a gradient has its own.") } else { tr!("Stroke colour: click to pick the colour and how clear it is") }); // As in Animate, the square clicked last is the one swatches set (ADR 0078). if resp.clicked() { app.colour_target = if fill { crate::swatches_panel::ColourTarget::Fill } else { crate::swatches_panel::ColourTarget::Stroke }; @@ -193,7 +193,7 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { let shown = (selected || st.use_fill).then_some(paint); match crate::colour_panel::popup_for(ui, &resp, resp.id.with("colour_popup"), shown.as_ref(), &crate::colour_panel::bitmaps(app)) { Some(crate::colour_panel::FillEdit::Solid(p)) => { - c = [p[0], p[1], p[2], 255]; + c = p; none = false; true } @@ -209,12 +209,12 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { None => false, } } else { - crate::colour::popup_for(ui, &resp, resp.id.with("colour_popup"), &mut c, false, Some(&mut none)) + crate::colour::popup_for(ui, &resp, resp.id.with("colour_popup"), &mut c, true, Some(&mut none)) }; if picked { // No Colour toggled says which; a colour picked turns the colour back on. let none = none != was && none; - let pick = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0); + let pick = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0); let style = &mut app.s.style; if fill { style.use_fill = !none; @@ -230,7 +230,7 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) { // Selected shapes take it too (one undo step for a drag in the mixer). let shapes = app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, ElementKind::Shape(_))); if shapes { - let colour = if none { Value::Null } else { json!(hex([c[0], c[1], c[2]])) }; + let colour = if none { Value::Null } else { json!(crate::colour::to_hex(c, true)) }; let (label, id, p) = if fill { (tr_noop!("Fill colour"), "element.set_fill", json!({"color": colour})) } else { (tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": colour})) }; live(app, label, id, p); } @@ -249,8 +249,9 @@ fn fill_kind_label(p: Option<&Paint>) -> Option<&'static str> { } fn rgba(c: Rgba) -> [u8; 4] { - let [r, g, b] = rgb(c); - [r, g, b, 255] + let c = c.sanitized(); + let b = |v: f32| (v * 255.0).round() as u8; + [b(c.r), b(c.g), b(c.b), b(c.a)] } // ----- edit bar & status ------------------------------------------------------------------ @@ -480,25 +481,25 @@ fn row_prose(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui)) { /// White as in Animate. pub(crate) fn colour_panel(app: &mut App, ui: &mut egui::Ui) { let mut st = app.s.style.clone(); - let to_rgba = |c: [u8; 3]| Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0); - let (mut stroke, mut fill) = (rgb(st.stroke), rgb(st.fill)); + let to_rgba = |c: [u8; 4]| Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0); + let (mut stroke, mut fill) = (rgba(st.stroke), rgba(st.fill)); let (mut stroke_changed, mut fill_changed) = (false, false); let mut target = app.colour_target; row(ui, tr!("Stroke"), |ui| { - let r = crate::colour::button(ui, &mut stroke).named(tr!("Stroke colour")); + let r = crate::colour::button_alpha(ui, &mut stroke).named(tr!("Stroke colour")); if r.clicked() { target = crate::swatches_panel::ColourTarget::Stroke; } stroke_changed = r.changed(); - ui.label(text(Type::Data, hex(stroke)).color(T.text_dim)); + ui.label(text(Type::Data, crate::colour::to_hex(stroke, true)).color(T.text_dim)); }); row(ui, tr!("Fill"), |ui| { - let r = crate::colour::button(ui, &mut fill).named(tr!("Fill colour")); + let r = crate::colour::button_alpha(ui, &mut fill).named(tr!("Fill colour")); if r.clicked() { target = crate::swatches_panel::ColourTarget::Fill; } fill_changed = r.changed(); - ui.label(text(Type::Data, hex(fill)).color(T.text_dim)); + ui.label(text(Type::Data, crate::colour::to_hex(fill, true)).color(T.text_dim)); }); let mut undo = tr_noop!("Colour"); ui.horizontal_wrapped(|ui| { @@ -507,7 +508,7 @@ pub(crate) fn colour_panel(app: &mut App, ui: &mut egui::Ui) { (stroke_changed, fill_changed, undo) = (true, true, tr_noop!("Swap Colours")); } if ui.button(tr!("Black and White")).on_hover_text(tr!("A black stroke and a white fill")).clicked() { - (stroke, fill) = ([0, 0, 0], [255, 255, 255]); + (stroke, fill) = ([0, 0, 0, 255], [255, 255, 255, 255]); (stroke_changed, fill_changed, undo) = (true, true, tr_noop!("Black and White")); } }); @@ -526,10 +527,10 @@ pub(crate) fn colour_panel(app: &mut App, ui: &mut egui::Ui) { app.s.style = st; if !app.s.selection.is_empty() { if stroke_changed { - live(app, undo, "element.set_stroke", json!({"color": hex(stroke)})); + live(app, undo, "element.set_stroke", json!({"color": crate::colour::to_hex(stroke, true)})); } if fill_changed { - live(app, undo, "element.set_fill", json!({"color": hex(fill)})); + live(app, undo, "element.set_fill", json!({"color": crate::colour::to_hex(fill, true)})); } } } @@ -1022,22 +1023,22 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E let fill = sh.fill.as_ref().map(Paint::primary_color); let bitmaps = crate::colour_panel::bitmaps(app); row(ui, tr!("Fill"), |ui| { - let c = rgb(fill.unwrap_or(Rgba::WHITE)); + let c = fill.unwrap_or(Rgba::WHITE); // The one colour picker, with the fill's type (ADR 0074): a gradient shows as its // ramp here and is edited in the picker. let (r, edit) = crate::colour_panel::swatch(ui, sh.fill.as_ref(), &bitmaps); - r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill")); + r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour and how clear it is, or a gradient or bitmap fill")); match edit { - Some(crate::colour_panel::FillEdit::Solid(p)) => live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": hex(p)})), + Some(crate::colour_panel::FillEdit::Solid(p)) => live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": crate::colour::to_hex(p, true)})), Some(crate::colour_panel::FillEdit::None(n)) => { - app.run("element.set_fill", if n { json!({"color": null}) } else { json!({"color": hex(c)}) }); + app.run("element.set_fill", if n { json!({"color": null}) } else { json!({"color": crate::colour::to_hex(rgba(c), true)}) }); } Some(edit) => crate::colour_panel::apply_set(app, &edit, true), None => {} } let mut on = fill.is_some(); if crate::theme::checkbox(ui, &mut on, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off")).changed() { - app.run("element.set_fill", if on { json!({"color": hex(c)}) } else { json!({"color": null}) }); + app.run("element.set_fill", if on { json!({"color": crate::colour::to_hex(rgba(c), true)}) } else { json!({"color": null}) }); } if let Some(what) = fill_kind_label(sh.fill.as_ref()) { ui.label(text(Type::Caption, what)); @@ -1047,11 +1048,11 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E if let Some(Paint::Bitmap { bitmap, .. }) = &sh.fill { bitmap_row(app, ui, *bitmap, m.bitmap); } - let mut sc = rgb(sh.stroke.as_ref().map_or(app.s.style.stroke, |s| s.color)); + let mut sc = rgba(sh.stroke.as_ref().map_or(app.s.style.stroke, |s| s.color)); let mut sw = sh.stroke.as_ref().map_or(0.0, |s| s.width); row(ui, tr!("Stroke"), |ui| { - if crate::colour::button(ui, &mut sc).named(tr!("Stroke colour")).changed() { - live(app, tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": hex(sc)})); + if crate::colour::button_alpha(ui, &mut sc).named(tr!("Stroke colour")).on_hover_text(tr!("Stroke colour: click to pick the colour and how clear it is")).changed() { + live(app, tr_noop!("Stroke colour"), "element.set_stroke", json!({"color": crate::colour::to_hex(sc, true)})); } if ui.add(egui::DragValue::new(&mut sw).suffix(" px").speed(0.1).range(0.0..=200.0).max_decimals(1)).named(tr!("Stroke width")).changed() { live(app, tr_noop!("Stroke width"), "element.set_stroke", json!({"width": sw})); @@ -2567,10 +2568,10 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { // colour picker with the fill's type (ADR 0074). let paint = st.fill_paint(); let (r, edit) = crate::colour_panel::swatch(ui, (st.use_fill || fills).then_some(&paint), &bitmaps); - r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill")); + r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour and how clear it is, or a gradient or bitmap fill")); match edit { Some(crate::colour_panel::FillEdit::Solid(p)) => { - st.set_fill_color(Rgba::new(f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0, 1.0)); + st.set_fill_color(Rgba::new(f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0, f32::from(p[3]) / 255.0)); st.use_fill = true; } Some(crate::colour_panel::FillEdit::None(n)) => st.use_fill = !n || fills, @@ -2593,9 +2594,9 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { } if !fills { row(ui, tr!("Stroke"), |ui| { - let mut c = rgb(st.stroke); - if crate::colour::button(ui, &mut c).named(tr!("Stroke colour")).changed() { - st.stroke = Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0); + let mut c = rgba(st.stroke); + if crate::colour::button_alpha(ui, &mut c).named(tr!("Stroke colour")).on_hover_text(tr!("Stroke colour: click to pick the colour and how clear it is")).changed() { + st.stroke = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0); } if !ink { crate::theme::checkbox(ui, &mut st.use_stroke, "").named(tr!("Stroke")).on_hover_text(tr!("Stroke on/off")); From 924d571f50ac8585269129828c3fd22f134b97df Mon Sep 17 00:00:00 2001 From: Juan Larrazabal Date: Sat, 14 Nov 2026 13:29:18 -0800 Subject: [PATCH 070/570] docs: reserve ADR 0097 as pull request 354 --- docs/adr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/README.md b/docs/adr/README.md index 11e2e191..e80f8ece 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0097 | (outside contribution) | Fill alpha | +| 0097 | #354 (outside contribution) | Fill alpha | From 23cbead12cfdc811635afff6b1d757522e17211b Mon Sep 17 00:00:00 2001 From: Untoldent Date: Sat, 14 Nov 2026 16:44:20 -0500 Subject: [PATCH 071/570] Select existing names in rename dialogs Select the current name on opening Rename Layer, Rename Scene, and Layer Properties. Add regression tests for each workflow. --- src/app.rs | 107 +++++++++++++++++++++++++++++++++++++++++++++ src/layer_props.rs | 58 +++++++++++++++++++++++- 2 files changed, 164 insertions(+), 1 deletion(-) diff --git a/src/app.rs b/src/app.rs index 21fa6d6a..cd91995e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -3218,6 +3218,18 @@ impl App { let r = ui.add(egui::TextEdit::singleline(&mut p.text).desired_width(f32::INFINITY)).named(title); if p.focus { r.request_focus(); + + if matches!(p.cmd, "layer.rename" | "scene.rename") + && let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) + { + let start = egui::text::CCursor::new(0); + let end = egui::text::CCursor::new(p.text.chars().count()); + + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(start, end))); + + state.store(ui.ctx(), r.id); + } + p.focus = false; } if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { @@ -3651,4 +3663,99 @@ mod prompt_enter_tests { assert!(app.prompt.is_none(), "Enter closes the rename prompt"); assert_eq!(app.s.active_layer().unwrap().name, "Renamed"); } + + #[test] + fn opening_rename_layer_selects_entire_name() { + let ctx = egui::Context::default(); + + // Start with a genuine new AniCraft document. + let document = anicraft_engine::doc::Document::default(); + let session = anicraft_engine::Session::new(document); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + + // Check the initial document. + let original = app.s.active_layer().expect("A new document should have an active layer").name.clone(); + + assert_eq!(original, "Layer 1"); + + // Invoke AniCraft's REAL Rename Layer command. + app.invoke("layer.rename"); + + // Verify that the command created the correct prompt. + let prompt = app.prompt.as_ref().expect("Rename Layer should open a prompt"); + + assert_eq!(prompt.cmd, "layer.rename"); + assert_eq!(prompt.text, original); + assert!(prompt.focus); + + // Simulate three frames of the dialog. + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), ..Default::default() }; + + ctx.run_ui(input, |_| app.prompt_window(&ctx)).textures_delta.clear(); + } + + // Find the text field that received keyboard focus. + let id = ctx.memory(|m| m.focused()).expect("The name field should have focus"); + + // Inspect the actual text selection. + let state = egui::TextEdit::load_state(&ctx, id).expect("The text field should have editing state"); + + let selection = state.cursor.char_range().expect("The name field should have a selection"); + + let a = selection.primary.index; + let b = selection.secondary.index; + + // The entire original name must be selected. + assert_eq!(a.min(b), egui::text::CharIndex(0)); + assert_eq!(a.max(b), egui::text::CharIndex(original.chars().count())); + } + + #[test] + fn opening_rename_scene_selects_entire_name() { + let ctx = egui::Context::default(); + + // Create a real new AniCraft document. + let document = anicraft_engine::doc::Document::default(); + let session = anicraft_engine::Session::new(document); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + + // Get the actual name of the current scene. + let original = app.s.doc.scenes.get(app.s.scene).expect("A new document should have a scene").name.clone(); + + assert!(!original.is_empty()); + + // Invoke the real Rename Scene command. + app.invoke("scene.rename"); + + // Verify that AniCraft created the correct prompt. + let prompt = app.prompt.as_ref().expect("Rename Scene should open a prompt"); + + assert_eq!(prompt.cmd, "scene.rename"); + assert_eq!(prompt.text, original); + assert!(prompt.focus); + + // Simulate three frames of the dialog. + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), ..Default::default() }; + + ctx.run_ui(input, |_| app.prompt_window(&ctx)).textures_delta.clear(); + } + + // Get the focused text field's editing state. + let id = ctx.memory(|m| m.focused()).expect("The scene name field should have focus"); + + let state = egui::TextEdit::load_state(&ctx, id).expect("The text field should have editing state"); + + let selection = state.cursor.char_range().expect("The scene name should have a selection"); + + let a = selection.primary.index; + let b = selection.secondary.index; + + // The entire original scene name must be selected. + assert_eq!(a.min(b), egui::text::CharIndex(0)); + assert_eq!(a.max(b), egui::text::CharIndex(original.chars().count())); + } } diff --git a/src/layer_props.rs b/src/layer_props.rs index bc00103c..fb4afb49 100644 --- a/src/layer_props.rs +++ b/src/layer_props.rs @@ -104,6 +104,16 @@ pub fn window(app: &mut App, ctx: &egui::Context) { let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Layer name")); if d.focus { r.request_focus(); + + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { + let start = egui::text::CCursor::new(0); + let end = egui::text::CCursor::new(d.name.chars().count()); + + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(start, end))); + + state.store(ui.ctx(), r.id); + } + d.focus = false; } if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { @@ -274,4 +284,50 @@ mod tests { app.invoke("layer.set_properties"); assert!(app.layer_props.is_some()); } -} + + #[test] + fn opening_layer_properties_selects_entire_name() { + let ctx = egui::Context::default(); + + // Start with a real new AniCraft document. + let document = anicraft_engine::doc::Document::default(); + let session = Session::new(document); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + + // Get the name of the active layer. + let original = app.s.timeline().layer(app.s.layer).expect("A new document should have an active layer").name.clone(); + + assert!(!original.is_empty()); + + // Invoke the real Layer Properties command. + app.invoke("layer.set_properties"); + + // Confirm AniCraft populated the dialog correctly. + let dialog = app.layer_props.as_ref().expect("Layer Properties should open"); + + assert_eq!(dialog.name, original); + assert!(dialog.focus); + + // Simulate three frames of the Layer Properties window. + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), ..Default::default() }; + + ctx.run_ui(input, |_| window(&mut app, &ctx)).textures_delta.clear(); + } + + // Find the focused text field. + let id = ctx.memory(|m| m.focused()).expect("The layer name field should have focus"); + + let state = egui::TextEdit::load_state(&ctx, id).expect("The name field should have editing state"); + + let selection = state.cursor.char_range().expect("The layer name should have a selection"); + + let a = selection.primary.index; + let b = selection.secondary.index; + + // The entire existing name must be selected. + assert_eq!(a.min(b), egui::text::CharIndex(0)); + assert_eq!(a.max(b), egui::text::CharIndex(original.chars().count())); + } +} \ No newline at end of file From 7863c5d9ce944c3aa3a217882ab06ba3adbd2862 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 22:42:03 +0000 Subject: [PATCH 072/570] Handle prefixed XFL names in the AniCraft adapter --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 4 ++-- crates/xfl/src/tests.rs | 21 +++++++++++++++++++++ crates/xml/src/lib.rs | 26 ++++++++++++++++++++++++++ 5 files changed, 53 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 93beb35e..95eee2a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1318,7 +1318,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4801a54e3c6082af7063e9f451da50b2db22a6e2#4801a54e3c6082af7063e9f451da50b2db22a6e2" +source = "git+https://github.com/storytold/craft-libs?rev=9a33bc229a18d02677d192e85a1ba3de8558c668#9a33bc229a18d02677d192e85a1ba3de8558c668" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4801a54e3c6082af7063e9f451da50b2db22a6e2#4801a54e3c6082af7063e9f451da50b2db22a6e2" +source = "git+https://github.com/storytold/craft-libs?rev=9a33bc229a18d02677d192e85a1ba3de8558c668#9a33bc229a18d02677d192e85a1ba3de8558c668" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index b0977270..f51aa530 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "4801a54e3c6082af7063e9f451da50b2db22a6e2" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4801a54e3c6082af7063e9f451da50b2db22a6e2" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "9a33bc229a18d02677d192e85a1ba3de8558c668" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "9a33bc229a18d02677d192e85a1ba3de8558c668" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index ac77519e..c9a10da9 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -1168,7 +1168,7 @@ impl<'a> Builder<'a> { } }; let (model, xml_root) = parsed.into_parts(craft_xfl::document::ModelLimits { max_timelines: 0, max_layers_per_timeline: MAX_LAYERS }); - let item = match xml::from_craft_xml_owned(xml_root) { + let item = match xml::from_craft_xml_owned_local_names(xml_root) { Ok(item) => item, Err(_) => { self.report.skip("library files that couldn't be read"); @@ -1307,7 +1307,7 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do let parsed = craft_xfl::document::Document::parse(&bytes).map_err(xml::from_craft_error)?; let (schema, xml_root) = parsed.into_parts(craft_xfl::document::ModelLimits { max_timelines: anicraft_doc::MAX_SCENES, max_layers_per_timeline: MAX_LAYERS }); - let root = xml::from_craft_xml_owned(xml_root)?; + let root = xml::from_craft_xml_owned_local_names(xml_root)?; if root.name != "DOMDocument" { return Err(XflError::NotXfl(format!("the root element is <{}>", root.name))); } diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 77576bd2..67c73580 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -123,6 +123,27 @@ fn stage_layers_frames_and_tweens() { assert_eq!(doc.timeline(1).layers.len(), 1, "an empty scene gets a layer to draw on"); } +#[test] +fn prefixed_xfl_names_survive_shared_parse_and_domain_mapping() { + let doc = r##" + + + + + + "##; + let (document, _) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap(); + assert_eq!(document.scenes[0].name, "Prefixed Scene"); + let layer = &document.timeline(0).layers[0]; + assert_eq!(layer.name, "Prefixed Layer"); + assert_eq!(layer.keyframes.len(), 1); + assert_eq!( + (layer.keyframes[0].start, layer.keyframes[0].duration, layer.keyframes[0].label.as_str()), + (0, 3, "key") + ); + assert_eq!(layer.keyframes[0].elements.len(), 1, "prefixed geometry reaches the app model"); +} + #[test] fn mask_layers_mask_the_layers_that_point_at_them() { // A mask inside a folder: `parentLayerIndex` counts every layer in the file, folders too. diff --git a/crates/xml/src/lib.rs b/crates/xml/src/lib.rs index f9b0ff99..20fe62ab 100644 --- a/crates/xml/src/lib.rs +++ b/crates/xml/src/lib.rs @@ -184,6 +184,21 @@ pub fn from_craft_xml_owned(source: craft_xml::El) -> Result convert_owned(source, &[], &mut used) } +fn normalize_element_names(element: &mut Element) { + element.name = local(&element.name).to_string(); + for child in &mut element.children { + normalize_element_names(child); + } +} + +/// Converts an owned shared XML tree and drops element-name prefixes for formats whose +/// vocabulary is defined by local element names, such as XFL. Attribute names are preserved. +pub fn from_craft_xml_owned_local_names(source: craft_xml::El) -> Result { + let mut element = from_craft_xml_owned(source)?; + normalize_element_names(&mut element); + Ok(element) +} + /// Parses a document and returns its root element. pub fn parse(src: &[u8]) -> Result { let root = options().parse(src).map_err(from_craft_error)?; @@ -218,6 +233,17 @@ mod tests { assert_eq!(root.children[1].text, ""); } + #[test] + fn xfl_compatibility_conversion_uses_element_local_names_and_preserves_attributes() { + let root = craft_xml::Options::default() + .parse(b"") + .unwrap(); + let root = from_craft_xml_owned_local_names(root).unwrap(); + assert_eq!(root.name, "DOMDocument"); + assert_eq!(root.attr("x:version"), Some("1")); + assert_eq!(root.list("timelines")[0].name, "DOMTimeline"); + } + #[test] fn malformed_nesting_and_old_resource_limits_remain_errors() { for malformed in [b"".as_slice(), b"".as_slice()] { From 8472e045a49c0754c5d3f1420182db1ea6cd6c5a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 23:19:18 +0000 Subject: [PATCH 073/570] Pin AniCraft XFL reader to merged shared release --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 95eee2a4..7ecc9c2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1318,7 +1318,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9a33bc229a18d02677d192e85a1ba3de8558c668#9a33bc229a18d02677d192e85a1ba3de8558c668" +source = "git+https://github.com/storytold/craft-libs?rev=136b29dd76923d7d95d88ef48d5bd7c8da5576d8#136b29dd76923d7d95d88ef48d5bd7c8da5576d8" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9a33bc229a18d02677d192e85a1ba3de8558c668#9a33bc229a18d02677d192e85a1ba3de8558c668" +source = "git+https://github.com/storytold/craft-libs?rev=136b29dd76923d7d95d88ef48d5bd7c8da5576d8#136b29dd76923d7d95d88ef48d5bd7c8da5576d8" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index f51aa530..fa370c73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "9a33bc229a18d02677d192e85a1ba3de8558c668" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "9a33bc229a18d02677d192e85a1ba3de8558c668" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "136b29dd76923d7d95d88ef48d5bd7c8da5576d8" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "136b29dd76923d7d95d88ef48d5bd7c8da5576d8" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From ba3835342f8606c6758e737a400303c4b1ce0da0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 00:16:28 +0000 Subject: [PATCH 074/570] Use shared XFL shape and media schema --- Cargo.lock | 5 +- Cargo.toml | 4 +- crates/xfl/src/import.rs | 140 ++++++++++++++++++++++----------------- crates/xml/Cargo.toml | 1 + crates/xml/src/lib.rs | 16 +++++ 5 files changed, 100 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b4ec8108..fb63097b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -420,6 +420,7 @@ dependencies = [ name = "anicraft-xml" version = "0.3.0" dependencies = [ + "craft-xfl", "craft-xml", "thiserror 2.0.21", ] @@ -1318,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=136b29dd76923d7d95d88ef48d5bd7c8da5576d8#136b29dd76923d7d95d88ef48d5bd7c8da5576d8" +source = "git+https://github.com/storytold/craft-libs?rev=bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a#bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1328,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=136b29dd76923d7d95d88ef48d5bd7c8da5576d8#136b29dd76923d7d95d88ef48d5bd7c8da5576d8" +source = "git+https://github.com/storytold/craft-libs?rev=bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a#bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index f2e1b674..9f9509dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "136b29dd76923d7d95d88ef48d5bd7c8da5576d8" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "136b29dd76923d7d95d88ef48d5bd7c8da5576d8" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index c9a10da9..cb021303 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -286,14 +286,13 @@ fn ramp(el: &X) -> Vec { } pub(crate) fn color(el: &X, key: &str, alpha_key: &str) -> Rgba { - let rgb = el.attr(key).and_then(|c| u32::from_str_radix(c.trim().trim_start_matches('#'), 16).ok()).unwrap_or(0); - Rgba::hex(rgb).with_alpha(el.f32(alpha_key).unwrap_or(1.0).clamp(0.0, 1.0)) + let parsed = craft_xfl::shape::color(el, key, alpha_key); + Rgba::hex(parsed.rgb).with_alpha(parsed.alpha) } fn matrix(el: &X) -> Affine { - let Some(m) = el.child("matrix").and_then(|m| m.child("Matrix")) else { return Affine::IDENTITY }; - let a = Affine { m: [m.f32("a").unwrap_or(1.0), m.f32("b").unwrap_or(0.0), m.f32("c").unwrap_or(0.0), m.f32("d").unwrap_or(1.0), m.f32("tx").unwrap_or(0.0), m.f32("ty").unwrap_or(0.0)] }; - if a.is_finite() { a } else { Affine::IDENTITY } + let m = craft_xfl::shape::matrix(el); + Affine { m: [m.a, m.b, m.c, m.d, m.tx, m.ty] } } /// Half the side of the square XFL gradients are defined on, in pixels (16384 twips / 20). @@ -302,19 +301,26 @@ const GRADIENT_HALF: f32 = 819.2; /// A fill definition (`SolidColor`, `LinearGradient`, `RadialGradient`, `BitmapFill`) as a /// paint. fn paint(def: &X, bitmaps: &HashMap, report: &mut Report) -> Option { - match def.name.as_str() { - "SolidColor" => Some(Paint::Solid(color(def, "color", "alpha"))), - "LinearGradient" | "RadialGradient" => { + let fill = craft_xfl::shape::Fill::new(def); + match fill.kind() { + craft_xfl::shape::FillKind::SolidColor => Some(Paint::Solid(color(def, "color", "alpha"))), + craft_xfl::shape::FillKind::LinearGradient | craft_xfl::shape::FillKind::RadialGradient => { let m = matrix(def); - let stops: Vec = def.children.iter().filter(|c| c.name == "GradientEntry").map(|g| GradientStop { offset: g.f32("ratio").unwrap_or(0.0).clamp(0.0, 1.0), color: color(g, "color", "alpha") }).collect(); + let stops: Vec = fill + .gradient_entries() + .map(|g| { + let color = g.color_value(); + GradientStop { offset: g.ratio().unwrap_or(0.0).clamp(0.0, 1.0), color: Rgba::hex(color.rgb).with_alpha(color.alpha) } + }) + .collect(); if stops.is_empty() { return None; } // Overflow, interpolation and the focal point carry over as they are (ADR 0074). - let spread = def.attr("spreadMethod").and_then(|s| Spread::from_key(s.trim())).unwrap_or_default(); - let linear_rgb = def.attr("interpolationMethod").is_some_and(|s| s.trim() == "linearRGB"); + let spread = fill.spread_method().and_then(|s| Spread::from_key(s.trim())).unwrap_or_default(); + let linear_rgb = fill.interpolation_method().is_some_and(|s| s.trim() == "linearRGB"); let frame = m.mul(&Affine::scale(GRADIENT_HALF, GRADIENT_HALF)); - let mut p = if def.name == "LinearGradient" { Paint::linear(Vec2::new(-1.0, 0.0), Vec2::new(1.0, 0.0), stops) } else { Paint::radial(Vec2::ZERO, 1.0, stops) }; + let mut p = if fill.kind() == craft_xfl::shape::FillKind::LinearGradient { Paint::linear(Vec2::new(-1.0, 0.0), Vec2::new(1.0, 0.0), stops) } else { Paint::radial(Vec2::ZERO, 1.0, stops) }; match &mut p { Paint::Linear { spread: s, linear_rgb: l, .. } => { *s = spread; @@ -323,14 +329,14 @@ fn paint(def: &X, bitmaps: &HashMap, report: &mut Report) -> O Paint::Radial { spread: s, linear_rgb: l, focal, .. } => { *s = spread; *l = linear_rgb; - *focal = def.f32("focalPointRatio").filter(|f| f.is_finite()).unwrap_or(0.0).clamp(-MAX_FOCAL, MAX_FOCAL); + *focal = fill.focal_point_ratio().unwrap_or(0.0).clamp(-MAX_FOCAL, MAX_FOCAL); } _ => {} } Some(p.with_frame(&frame, None)) } - "BitmapFill" => { - let Some(&bitmap) = def.attr("bitmapPath").and_then(|n| bitmaps.get(n)) else { + craft_xfl::shape::FillKind::Bitmap => { + let Some(&bitmap) = fill.bitmap_path().and_then(|n| bitmaps.get(n)) else { report.skip("bitmap fills of missing bitmaps"); return None; }; @@ -338,9 +344,9 @@ fn paint(def: &X, bitmaps: &HashMap, report: &mut Report) -> O let matrix = Affine { m: [m[0] / TWIPS, m[1] / TWIPS, m[2] / TWIPS, m[3] / TWIPS, m[4], m[5]] }; // Animate repeats a bitmap fill unless it is clipped (then the edge pixels extend, // which AniCraft draws as the image shown once). - Some(Paint::Bitmap { bitmap, repeat: !def.bool("bitmapIsClipped").unwrap_or(false), matrix }) + Some(Paint::Bitmap { bitmap, repeat: !fill.bitmap_is_clipped().unwrap_or(false), matrix }) } - _ => None, + craft_xfl::shape::FillKind::Other => None, } } @@ -348,39 +354,42 @@ fn paint(def: &X, bitmaps: &HashMap, report: &mut Report) -> O /// joints and miter limit, and the dashes of `DashedStroke` and dots of `DottedStroke` /// (ADR 0046). Ragged, stipple and hatched strokes are drawn solid. pub(crate) fn stroke(def: &X, bitmaps: &HashMap, report: &mut Report) -> Option { - if !matches!(def.name.as_str(), "SolidStroke" | "DashedStroke" | "DottedStroke" | "RaggedStroke" | "StippleStroke" | "HatchedStroke") { + let native = craft_xfl::shape::Stroke::new(def); + use craft_xfl::shape::StrokeKind as NativeStroke; + if native.kind() == NativeStroke::Other { return None; } // Round caps and joints are the format's default, and a miter limit of 3. - let cap = match def.attr("caps").map(str::trim) { + let cap = match native.caps().map(str::trim) { Some("none") => Cap::Butt, Some("square") => Cap::Square, _ => Cap::Round, }; - let join = match def.attr("joints").map(str::trim) { + let join = match native.joints().map(str::trim) { Some("miter") => Join::Miter, Some("bevel") => Join::Bevel, _ => Join::Round, }; - let miter_limit = def.f32("miterLimit").unwrap_or(anicraft_doc::stroke_style::DEFAULT_MITER_LIMIT); - let dash = match def.name.as_str() { - "DashedStroke" => Dash::dashed(def.f32("dash1").unwrap_or(6.0), def.f32("dash2").unwrap_or(3.0)), - "DottedStroke" => Dash::dotted(def.f32("dotSpace").unwrap_or(3.0)), - "SolidStroke" => None, + let miter_limit = native.miter_limit().unwrap_or(anicraft_doc::stroke_style::DEFAULT_MITER_LIMIT); + let dash = match native.kind() { + NativeStroke::Dashed => Dash::dashed(native.dash1().unwrap_or(6.0), native.dash2().unwrap_or(3.0)), + NativeStroke::Dotted => Dash::dotted(native.dot_space().unwrap_or(3.0)), + NativeStroke::Solid => None, _ => { report.skip("ragged, stipple and hatched strokes (drawn solid)"); None } }; let style = StrokeStyle { cap, join, miter_limit, dash }; - let width = def.f32("weight").unwrap_or(1.0).clamp(0.05, 1000.0); - let fill = def.child("fill").and_then(|f| f.children.first()); + let width = native.weight().unwrap_or(1.0).clamp(0.05, 1000.0); + let fill = native.fill(); let c = fill.map_or(Rgba::BLACK, |f| { - if f.name == "SolidColor" { - color(f, "color", "alpha") + if f.kind() == craft_xfl::shape::FillKind::SolidColor { + let value = f.color_value(); + Rgba::hex(value.rgb).with_alpha(value.alpha) } else { report.skip("gradient and bitmap strokes (drawn in one colour)"); - paint(f, bitmaps, report).map_or(Rgba::BLACK, |p| p.primary_color()) + paint(f.element(), bitmaps, report).map_or(Rgba::BLACK, |p| p.primary_color()) } }); Some(Stroke::new(c, width).with_style(style)) @@ -396,16 +405,23 @@ impl<'a> Builder<'a> { /// not a drawing object) is raw artwork: its shapes are marked to merge (ADR 0042), and the /// engine merges each keyframe's raw shapes into one drawing when it opens the file. fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec>, loose: bool) { + let Some(schema) = craft_xfl::shape::Shape::new(el) else { return }; let m = parent.mul(&matrix(el)); - let merge = loose && !el.bool("isDrawingObject").unwrap_or(false); - let fills: Vec<(u32, Option)> = el.list("fills").iter().map(|f| (f.u32("index").unwrap_or(0), f.children.first().and_then(|d| paint(d, &self.bitmaps, &mut self.report)))).collect(); - let strokes: Vec<(u32, Option)> = el.list("strokes").iter().map(|s| (s.u32("index").unwrap_or(0), s.children.first().and_then(|d| stroke(d, &self.bitmaps, &mut self.report)))).collect(); - let edges: Vec = el - .list("edges") - .iter() - .filter(|e| e.name == "Edge") - .map(|e| Edge { fill_left: e.u32("fillStyle0").unwrap_or(0), fill_right: e.u32("fillStyle1").unwrap_or(0), stroke: e.u32("strokeStyle").unwrap_or(0), segs: e.attr("edges").map(edges::parse).unwrap_or_default() }) - .collect(); + let merge = loose && !schema.is_drawing_object().unwrap_or(false); + let fills: Vec<(u32, Option)> = schema.fills().map(|style| { + let paint = style.definition().and_then(|definition| paint(definition.element(), &self.bitmaps, &mut self.report)); + (style.index().unwrap_or(0), paint) + }).collect(); + let strokes: Vec<(u32, Option)> = schema.strokes().map(|style| { + let stroke = style.definition().and_then(|definition| stroke(definition.element(), &self.bitmaps, &mut self.report)); + (style.index().unwrap_or(0), stroke) + }).collect(); + let edges: Vec = schema.edges().map(|edge| Edge { + fill_left: edge.fill_style0().unwrap_or(0), + fill_right: edge.fill_style1().unwrap_or(0), + stroke: edge.stroke_style().unwrap_or(0), + segs: edge.encoded_segments().map(edges::parse).unwrap_or_default(), + }).collect(); for (index, p) in fills { let (Some(p), true) = (p, index > 0) else { continue }; let path = edges::fill_path(&edges, index); @@ -894,14 +910,14 @@ impl<'a> Builder<'a> { /// `bin/`; either is used when it is a PNG or JPEG. Animate's own encodings of the data /// file are not public, so those bitmaps are reported instead. fn register_bitmaps(&mut self, root: &X) -> Result<(), XflError> { - for item in root.list("media").iter().filter(|i| i.name == "DOMBitmapItem").take(MAX_BITMAPS) { - let Some(name) = item.attr("name").filter(|n| !self.bitmaps.contains_key(*n)) else { continue }; + for item in craft_xfl::media::Catalog::new(root).bitmaps().take(MAX_BITMAPS) { + let Some(name) = item.name().filter(|n| !self.bitmaps.contains_key(*n)) else { continue }; let mut candidates = Vec::new(); - if let Some(href) = item.attr("href") { - candidates.push(format!("LIBRARY/{href}")); + if let Some(href) = item.href() { + candidates.push(craft_xfl::media::library_member(href)); } - if let Some(data) = item.attr("bitmapDataHRef") { - candidates.push(format!("bin/{data}")); + if let Some(data) = item.data_href() { + candidates.push(craft_xfl::media::data_member(data)); } let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(256).collect(); let (mut found_data, mut unreadable) = (false, false); @@ -927,7 +943,7 @@ impl<'a> Builder<'a> { Some(mut b) => { b.id = BitmapId(self.doc.alloc_id()); // Animate leaves out the default (smoothing on in current versions). - b.smoothing = item.bool("allowSmoothing").unwrap_or(true); + b.smoothing = item.allow_smoothing().unwrap_or(true); self.place_in_folder(name, anicraft_doc::LibraryItem::Bitmap(b.id)); self.bitmaps.insert(name.to_string(), b.id); self.doc.bitmaps.push(Arc::new(b)); @@ -946,14 +962,14 @@ impl<'a> Builder<'a> { /// own encoding of the data file is not public, so those sounds are reported by name, as is /// every other sound that doesn't come across, with its format and why (ADR 0039). fn register_sounds(&mut self, root: &X) -> Result<(), XflError> { - for item in root.list("media").iter().filter(|i| i.name == "DOMSoundItem").take(MAX_SOUNDS) { - let Some(name) = item.attr("name").filter(|n| !self.sounds.contains_key(*n)) else { continue }; + for item in craft_xfl::media::Catalog::new(root).sounds().take(MAX_SOUNDS) { + let Some(name) = item.name().filter(|n| !self.sounds.contains_key(*n)) else { continue }; let mut candidates = Vec::new(); - if let Some(href) = item.attr("href") { - candidates.push((format!("LIBRARY/{href}"), false)); + if let Some(href) = item.href() { + candidates.push((craft_xfl::media::library_member(href), false)); } - if let Some(data) = item.attr("soundDataHRef") { - candidates.push((format!("bin/{data}"), true)); + if let Some(data) = item.data_href() { + candidates.push((craft_xfl::media::data_member(data), true)); } let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(256).collect(); let shown: String = name.chars().take(256).collect(); @@ -1006,17 +1022,17 @@ impl<'a> Builder<'a> { /// original file (`href`, or `sourceExternalFilepath` inside the package) in `LIBRARY/`, then /// as its data file in `bin/` (`videoDataHRef`). fn register_videos(&mut self, root: &X) { - for item in root.list("media").iter().filter(|i| i.name == "DOMVideoItem").take(MAX_VIDEOS) { - let Some(name) = item.attr("name").filter(|n| !self.videos.contains_key(*n)) else { continue }; + for item in craft_xfl::media::Catalog::new(root).videos().take(MAX_VIDEOS) { + let Some(name) = item.name().filter(|n| !self.videos.contains_key(*n)) else { continue }; let mut candidates = Vec::new(); - if let Some(href) = item.attr("href") { - candidates.push(format!("LIBRARY/{href}")); + if let Some(href) = item.href() { + candidates.push(craft_xfl::media::library_member(href)); } - if let Some(src) = item.attr("sourceExternalFilepath").and_then(|p| p.strip_prefix("./")) { - candidates.push(src.replace('\\', "/")); + if let Some(path) = item.external_path().and_then(craft_xfl::media::packaged_external_member) { + candidates.push(path); } - if let Some(data) = item.attr("videoDataHRef") { - candidates.push(format!("bin/{data}")); + if let Some(data) = item.data_href() { + candidates.push(craft_xfl::media::data_member(data)); } let shown: String = name.chars().take(256).collect(); let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(240).collect(); @@ -1043,8 +1059,8 @@ impl<'a> Builder<'a> { } } // Its length as the item gives it (seconds), else from its frames and rate. - let seconds = item.f32("length").filter(|s| s.is_finite() && *s >= 0.0).or_else(|| { - let (frames, fps) = (item.f32("frameCount")?, item.f32("fps")?); + let seconds = item.length().filter(|s| *s >= 0.0).or_else(|| { + let (frames, fps) = (item.frame_count()?, item.frames_per_second()?); (frames.is_finite() && fps.is_finite() && fps > 0.0).then(|| frames.max(0.0) / fps) }); let length = seconds.map(|s| format!(", {:.1} s", s.min(1.0e7))).unwrap_or_default(); diff --git a/crates/xml/Cargo.toml b/crates/xml/Cargo.toml index 0a3519b1..810611d3 100644 --- a/crates/xml/Cargo.toml +++ b/crates/xml/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true repository.workspace = true [dependencies] +craft-xfl.workspace = true craft-xml.workspace = true thiserror.workspace = true diff --git a/crates/xml/src/lib.rs b/crates/xml/src/lib.rs index 20fe62ab..d2d6f8e7 100644 --- a/crates/xml/src/lib.rs +++ b/crates/xml/src/lib.rs @@ -20,6 +20,22 @@ pub struct Element { pub text: String, } +impl craft_xfl::shape::XflElement for Element { + type Elements<'a> = std::slice::Iter<'a, Element>; + + fn local_name(&self) -> &str { + self.name.rsplit(':').next().unwrap_or(&self.name) + } + + fn attr(&self, name: &str) -> Option<&str> { + Element::attr(self, name) + } + + fn elements(&self) -> Self::Elements<'_> { + self.children.iter() + } +} + impl Element { pub fn attr(&self, name: &str) -> Option<&str> { self.attrs.get(name).map(String::as_str) From e2146490ccb06decabe64e69d86a5ec76a547658 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 00:20:40 +0000 Subject: [PATCH 075/570] Use shared XFL primitive schema --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 18 ++++++++++++------ 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fb63097b..b747fbe5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a#bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" +source = "git+https://github.com/storytold/craft-libs?rev=352a410332c1c1d53bbb358b47cfd53ce18579b4#352a410332c1c1d53bbb358b47cfd53ce18579b4" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a#bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" +source = "git+https://github.com/storytold/craft-libs?rev=352a410332c1c1d53bbb358b47cfd53ce18579b4#352a410332c1c1d53bbb358b47cfd53ce18579b4" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 9f9509dd..26100da4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb9f9a95cc6e8780b1fef0fb9d684536d8b2230a" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "352a410332c1c1d53bbb358b47cfd53ce18579b4" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "352a410332c1c1d53bbb358b47cfd53ce18579b4" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index cb021303..a669d2ff 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -440,16 +440,22 @@ impl<'a> Builder<'a> { /// Rectangle and oval primitives. fn primitive(&mut self, el: &X, parent: &Affine, out: &mut Vec>) { - let (x, y) = (el.f32("x").unwrap_or(0.0), el.f32("y").unwrap_or(0.0)); - let (w, h) = (el.f32("objectWidth").unwrap_or(0.0), el.f32("objectHeight").unwrap_or(0.0)); + let Some(primitive) = craft_xfl::shape::Primitive::new(el) else { return }; + let (x, y) = (primitive.x().unwrap_or(0.0), primitive.y().unwrap_or(0.0)); + let (w, h) = (primitive.width().unwrap_or(0.0), primitive.height().unwrap_or(0.0)); if !(w > 0.0 && h > 0.0) { return; } - let path = if el.name == "DOMOvalObject" { Path::ellipse(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0) } else { Path::rounded_rect(x, y, w, h, el.f32("topLeftRadius").unwrap_or(0.0).max(0.0)) }; - let fill = el.child("fill").and_then(|f| f.children.first()).and_then(|d| paint(d, &self.bitmaps, &mut self.report)); - let stroke = el.child("stroke").and_then(|s| s.children.first()).and_then(|d| stroke(d, &self.bitmaps, &mut self.report)); + let path = if primitive.kind() == craft_xfl::shape::PrimitiveKind::Oval { + Path::ellipse(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0) + } else { + Path::rounded_rect(x, y, w, h, primitive.top_left_radius().unwrap_or(0.0).max(0.0)) + }; + let fill = primitive.fill().and_then(|definition| paint(definition.element(), &self.bitmaps, &mut self.report)); + let stroke = primitive.stroke().and_then(|definition| stroke(definition.element(), &self.bitmaps, &mut self.report)); if fill.is_some() || stroke.is_some() { - let m = parent.mul(&matrix(el)); + let native = primitive.matrix(); + let m = parent.mul(&Affine { m: [native.a, native.b, native.c, native.d, native.tx, native.ty] }); out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill, stroke, fill_rule: FillRule::NonZero, merge: false, warp: None }), m, ColorEffect::default())); } } From 905bc066804863ec77abe1c91bd1173651af7109 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 00:25:32 +0000 Subject: [PATCH 076/570] Refresh shared XFL candidate pin --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b747fbe5..c7adb151 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=352a410332c1c1d53bbb358b47cfd53ce18579b4#352a410332c1c1d53bbb358b47cfd53ce18579b4" +source = "git+https://github.com/storytold/craft-libs?rev=e4eddc5fe55a2cced3854a14f1ef326a20ad449b#e4eddc5fe55a2cced3854a14f1ef326a20ad449b" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=352a410332c1c1d53bbb358b47cfd53ce18579b4#352a410332c1c1d53bbb358b47cfd53ce18579b4" +source = "git+https://github.com/storytold/craft-libs?rev=e4eddc5fe55a2cced3854a14f1ef326a20ad449b#e4eddc5fe55a2cced3854a14f1ef326a20ad449b" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 26100da4..9c44a0d1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "352a410332c1c1d53bbb358b47cfd53ce18579b4" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "352a410332c1c1d53bbb358b47cfd53ce18579b4" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "e4eddc5fe55a2cced3854a14f1ef326a20ad449b" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e4eddc5fe55a2cced3854a14f1ef326a20ad449b" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From 8b322e9b69e5c6608817a2350448052222876367 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 00:34:50 +0000 Subject: [PATCH 077/570] Refresh shared XFL matrix compatibility pin --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c7adb151..d9f9f628 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e4eddc5fe55a2cced3854a14f1ef326a20ad449b#e4eddc5fe55a2cced3854a14f1ef326a20ad449b" +source = "git+https://github.com/storytold/craft-libs?rev=d5a77b7dc1f8b6445f26581c0a4ea63de7d25186#d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e4eddc5fe55a2cced3854a14f1ef326a20ad449b#e4eddc5fe55a2cced3854a14f1ef326a20ad449b" +source = "git+https://github.com/storytold/craft-libs?rev=d5a77b7dc1f8b6445f26581c0a4ea63de7d25186#d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 9c44a0d1..81c5bb2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "e4eddc5fe55a2cced3854a14f1ef326a20ad449b" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e4eddc5fe55a2cced3854a14f1ef326a20ad449b" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From b0e9a1dfad36aca42bf70ca917dff359506a8c25 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 01:25:19 +0000 Subject: [PATCH 078/570] Pin XFL importer to merged shared parser --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d9f9f628..70ec825a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d5a77b7dc1f8b6445f26581c0a4ea63de7d25186#d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" +source = "git+https://github.com/storytold/craft-libs?rev=0f59e325e5755a9524bc37dedc652fa215ca4d0c#0f59e325e5755a9524bc37dedc652fa215ca4d0c" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d5a77b7dc1f8b6445f26581c0a4ea63de7d25186#d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" +source = "git+https://github.com/storytold/craft-libs?rev=0f59e325e5755a9524bc37dedc652fa215ca4d0c#0f59e325e5755a9524bc37dedc652fa215ca4d0c" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 81c5bb2e..6a6254f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d5a77b7dc1f8b6445f26581c0a4ea63de7d25186" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "0f59e325e5755a9524bc37dedc652fa215ca4d0c" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0f59e325e5755a9524bc37dedc652fa215ca4d0c" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From fa40e696304c81d564af02da1a7a91ef76e94bfe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 02:09:04 +0000 Subject: [PATCH 079/570] Delegate XFL text schema parsing to craft-libs --- Cargo.lock | 4 +- Cargo.toml | 4 +- crates/xfl/src/text.rs | 86 +++++++++++++++++++++++------------------- crates/xml/src/lib.rs | 5 +++ 4 files changed, 56 insertions(+), 43 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 70ec825a..4e1ea254 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0f59e325e5755a9524bc37dedc652fa215ca4d0c#0f59e325e5755a9524bc37dedc652fa215ca4d0c" +source = "git+https://github.com/storytold/craft-libs?rev=603aaacba66f6512939be84b5ba9cc94e9426297#603aaacba66f6512939be84b5ba9cc94e9426297" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0f59e325e5755a9524bc37dedc652fa215ca4d0c#0f59e325e5755a9524bc37dedc652fa215ca4d0c" +source = "git+https://github.com/storytold/craft-libs?rev=603aaacba66f6512939be84b5ba9cc94e9426297#603aaacba66f6512939be84b5ba9cc94e9426297" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 6a6254f9..9586b131 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "0f59e325e5755a9524bc37dedc652fa215ca4d0c" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0f59e325e5755a9524bc37dedc652fa215ca4d0c" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "603aaacba66f6512939be84b5ba9cc94e9426297" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "603aaacba66f6512939be84b5ba9cc94e9426297" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/text.rs b/crates/xfl/src/text.rs index d54633f7..886e1bf7 100644 --- a/crates/xfl/src/text.rs +++ b/crates/xfl/src/text.rs @@ -12,7 +12,7 @@ //! instance that scripts and the viewer use, so it takes its main style, keeps its instance name, //! line type, border, selectability and maximum length, and the report counts them as running. -use crate::import::{Report, color}; +use crate::import::Report; use crate::xml::Element as X; use anicraft_doc::{LineType, Rgba, TextAlign, TextBlock, TextField, TextKind}; use anicraft_geom::Vec2; @@ -48,12 +48,12 @@ pub struct Placed { pub offset: Vec2, } -fn run_style(attrs: Option<&X>, flags: &mut Flags) -> RunStyle { +fn run_style(attrs: Option>, flags: &mut Flags) -> RunStyle { let Some(a) = attrs else { return RunStyle { face: String::new(), size: 12.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, left_margin: 0.0, right_margin: 0.0 }; }; - let num = |k: &str, lo: f32, hi: f32| a.f32(k).unwrap_or(0.0).clamp(lo, hi); - let align = match a.attr("alignment") { + let clamp = |number: Option, lo: f32, hi: f32| number.unwrap_or(0.0).clamp(lo, hi); + let align = match a.alignment() { Some("center") => TextAlign::Center, Some("right") => TextAlign::Right, Some(j) if j.starts_with("justify") => { @@ -62,23 +62,24 @@ fn run_style(attrs: Option<&X>, flags: &mut Flags) -> RunStyle { } _ => TextAlign::Left, }; - if a.f32("indent").is_some_and(|i| i != 0.0) { + if a.indent().is_some_and(|i| i != 0.0) { flags.indented = true; } - if a.attr("characterPosition").is_some_and(|p| p != "normal") { + if a.character_position().is_some_and(|p| p != "normal") { flags.shifted = true; } + let color = a.color(); RunStyle { - face: a.attr("face").unwrap_or("").chars().take(256).collect(), - size: a.f32("size").unwrap_or(12.0).clamp(1.0, 2000.0), - bold: a.bool("bold").unwrap_or(false), - italic: a.bool("italic").unwrap_or(false), - color: if a.attr("fillColor").is_some() { color(a, "fillColor", "alpha") } else { Rgba::BLACK.with_alpha(a.f32("alpha").unwrap_or(1.0).clamp(0.0, 1.0)) }, + face: a.face().unwrap_or("").chars().take(256).collect(), + size: a.size().unwrap_or(12.0).clamp(1.0, 2000.0), + bold: a.bold().unwrap_or(false), + italic: a.italic().unwrap_or(false), + color: Rgba::hex(color.rgb).with_alpha(color.alpha), align, - letter_spacing: num("letterSpacing", -1000.0, 1000.0), - line_spacing: num("lineSpacing", -1000.0, 1000.0), - left_margin: num("leftMargin", 0.0, 10_000.0), - right_margin: num("rightMargin", 0.0, 10_000.0), + letter_spacing: clamp(a.letter_spacing(), -1000.0, 1000.0), + line_spacing: clamp(a.line_spacing(), -1000.0, 1000.0), + left_margin: clamp(a.left_margin(), 0.0, 10_000.0), + right_margin: clamp(a.right_margin(), 0.0, 10_000.0), } } @@ -131,20 +132,20 @@ fn main_style(line: &Line) -> (usize, bool) { /// Lays out one text field. Fonts are looked up once per face name (`faces`); missing ones go /// into the report. pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, report: &mut Report) -> Vec { - if el.attr("orientation").is_some_and(|o| o != "horizontal") { + let Some(field) = craft_xfl::text::TextField::new(el) else { return Vec::new() }; + if field.orientation().is_some_and(|o| o != "horizontal") { report.skip("vertical text (drawn horizontal)"); } - if !el.list("filters").is_empty() { + if field.has_filters() { report.skip("filters on text"); } let mut flags = Flags::default(); let mut styles: Vec = Vec::new(); let mut lines: Vec = vec![Vec::new()]; let mut chars = 0usize; - let runs = el.list("textRuns"); - let mut cut = runs.len() > MAX_RUNS; - for run in runs.iter().filter(|r| r.name == "DOMTextRun").take(MAX_RUNS) { - let style = run_style(run.child("textAttrs").and_then(|t| t.child("DOMTextAttrs")), &mut flags); + let mut cut = field.run_entries_count() > MAX_RUNS; + for run in field.runs().take(MAX_RUNS) { + let style = run_style(run.style(), &mut flags); let s = match styles.iter().position(|x| *x == style) { Some(i) => i, None => { @@ -152,7 +153,7 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo styles.len() - 1 } }; - let text = run.child("characters").map_or("", |c| c.text.as_str()); + let text = run.characters(); // Animate ends lines with a carriage return; any line break starts a new line here. let text = text.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n"); for (i, piece) in text.split('\n').enumerate() { @@ -178,9 +179,9 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo if cut { report.skip("text cut to 100,000 characters per field"); } - if el.name != "DOMStaticText" { + if field.kind() != craft_xfl::text::TextFieldKind::Static { flags.report(report); - return text_field(el, fonts, faces, report, &lines, &styles).into_iter().collect(); + return text_field(field, fonts, faces, report, &lines, &styles).into_iter().collect(); } // Trailing empty lines draw nothing. while lines.last().is_some_and(|l| l.iter().all(|(t, _)| t.trim().is_empty())) { @@ -208,9 +209,9 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo } } - let auto = el.bool("autoExpand").unwrap_or(false); - let field_width = el.f32("width").filter(|w| *w > 0.0).map(|w| w.min(100_000.0)); - let origin = Vec2::new(el.f32("left").unwrap_or(0.0) + GUTTER, el.f32("top").unwrap_or(0.0) + GUTTER); + let auto = field.auto_expand().unwrap_or(false); + let field_width = field.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0)); + let origin = Vec2::new(field.left().unwrap_or(0.0) + GUTTER, field.top().unwrap_or(0.0) + GUTTER); let mut out: Vec = Vec::new(); let mut y = 0.0f32; for (s, text) in blocks { @@ -286,8 +287,15 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo /// A dynamic or input field (ADR 0066): one block in the field's main style, its box from the /// field's `width` and `height` (or the text's size, for an auto-size field), its text laid out /// inside the gutter. Empty fields are kept (an empty input field is the usual kind). -fn text_field(el: &X, fonts: &Fonts, faces: &mut HashMap, report: &mut Report, lines: &[Line], styles: &[RunStyle]) -> Option { - let kind = if el.name == "DOMInputText" { TextKind::Input } else { TextKind::Dynamic }; +fn text_field( + native: craft_xfl::text::TextField<'_, X>, + fonts: &Fonts, + faces: &mut HashMap, + report: &mut Report, + lines: &[Line], + styles: &[RunStyle], +) -> Option { + let kind = if native.kind() == craft_xfl::text::TextFieldKind::Input { TextKind::Input } else { TextKind::Dynamic }; report.run(if kind == TextKind::Input { "input text fields" } else { "dynamic text fields" }); let all: Line = lines.iter().flatten().cloned().collect(); let (s, mixed) = main_style(&all); @@ -297,25 +305,25 @@ fn text_field(el: &X, fonts: &Fonts, faces: &mut HashMap, rep let st = styles.get(s).cloned().unwrap_or_else(|| run_style(None, &mut Flags::default())); let text: String = lines.iter().map(|l| l.iter().map(|(t, _)| t.as_str()).collect::()).collect::>().join("\n"); let text = text.trim_end_matches('\n').to_string(); - let line_type = match el.attr("lineType") { + let line_type = match native.line_type() { Some("multiline") => LineType::Multiline, Some("multiline no wrap") => LineType::MultilineNoWrap, Some("password") if kind == TextKind::Input => LineType::Password, _ => LineType::Single, }; - let border = el.bool("border").unwrap_or(false); - let variable: String = el.attr("variableName").unwrap_or("").trim().chars().take(anicraft_doc::MAX_FIELD_NAME).collect(); + let border = native.border().unwrap_or(false); + let variable: String = native.variable_name().unwrap_or("").trim().chars().take(anicraft_doc::MAX_FIELD_NAME).collect(); if !variable.is_empty() { report.keep("text field variables (ActionScript 1.0 and 2.0)"); } - if el.bool("renderAsHTML").unwrap_or(false) { + if native.render_as_html().unwrap_or(false) { report.skip("text fields rendered as HTML (drawn as plain text)"); } - let max_chars = el.f32("maxCharacters").filter(|n| n.is_finite() && *n > 0.0).map_or(0, |n| n.min(anicraft_doc::MAX_FIELD_CHARS as f32) as u32); + let max_chars = native.max_characters().filter(|n| *n > 0.0).map_or(0, |n| n.min(anicraft_doc::MAX_FIELD_CHARS as f32) as u32); // Animate's "show border" draws a black line round a white box. - let field = TextField { lines: line_type, selectable: el.bool("isSelectable").unwrap_or(true), border, background: border, max_chars, variable, ..TextField::new(kind) }; - let auto = el.bool("autoExpand").unwrap_or(false); - let width = el.f32("width").filter(|w| w.is_finite() && *w > 0.0).map(|w| w.min(100_000.0)); + let field = TextField { lines: line_type, selectable: native.is_selectable().unwrap_or(true), border, background: border, max_chars, variable, ..TextField::new(kind) }; + let auto = native.auto_expand().unwrap_or(false); + let width = native.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0)); let face = faces.entry(st.face.clone()).or_insert_with(|| fonts.find_face(&st.face)).clone(); let wrap = width.and_then(|w| field.wrap_width(w - st.left_margin - st.right_margin)); let style = anicraft_text::Style { @@ -352,7 +360,7 @@ fn text_field(el: &X, fonts: &Fonts, faces: &mut HashMap, rep (Some(w), true) => w.max(tw + 2.0 * GUTTER), (None, _) => tw + 2.0 * GUTTER, }; - let box_height = el.f32("height").filter(|h| h.is_finite() && *h > 0.0).map_or(th + 2.0 * GUTTER, |h| h.min(100_000.0)); + let box_height = native.height().filter(|h| *h > 0.0).map_or(th + 2.0 * GUTTER, |h| h.min(100_000.0)); let block = TextBlock { text, font: family, @@ -370,5 +378,5 @@ fn text_field(el: &X, fonts: &Fonts, faces: &mut HashMap, rep field: Some(field), on_path: None, }; - Some(Placed { block, offset: Vec2::new(el.f32("left").unwrap_or(0.0), el.f32("top").unwrap_or(0.0)) }) + Some(Placed { block, offset: Vec2::new(native.left().unwrap_or(0.0), native.top().unwrap_or(0.0)) }) } diff --git a/crates/xml/src/lib.rs b/crates/xml/src/lib.rs index d2d6f8e7..ba5a69fc 100644 --- a/crates/xml/src/lib.rs +++ b/crates/xml/src/lib.rs @@ -5,6 +5,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use std::collections::HashMap; +use std::borrow::Cow; /// Largest document read (bytes). pub const MAX_INPUT: usize = 256 * 1024 * 1024; @@ -34,6 +35,10 @@ impl craft_xfl::shape::XflElement for Element { fn elements(&self) -> Self::Elements<'_> { self.children.iter() } + + fn text_content(&self) -> Cow<'_, str> { + Cow::Borrowed(&self.text) + } } impl Element { From d5f5e6e17953c17f32bd804b0475d48d67c50c36 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 02:24:34 +0000 Subject: [PATCH 080/570] Route AniCraft filter schema through craft-libs --- Cargo.lock | 4 +- Cargo.toml | 4 +- crates/xfl/src/import.rs | 143 +++++++++++++++++++++++++-------------- crates/xfl/src/tests.rs | 11 +++ 4 files changed, 106 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 70ec825a..95859cca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0f59e325e5755a9524bc37dedc652fa215ca4d0c#0f59e325e5755a9524bc37dedc652fa215ca4d0c" +source = "git+https://github.com/storytold/craft-libs?rev=6f7106fe0a00ff863c8498fb4dcf33a993fb8b01#6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0f59e325e5755a9524bc37dedc652fa215ca4d0c#0f59e325e5755a9524bc37dedc652fa215ca4d0c" +source = "git+https://github.com/storytold/craft-libs?rev=6f7106fe0a00ff863c8498fb4dcf33a993fb8b01#6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 6a6254f9..72365c69 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "0f59e325e5755a9524bc37dedc652fa215ca4d0c" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0f59e325e5755a9524bc37dedc652fa215ca4d0c" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index a669d2ff..c702f7c5 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -23,6 +23,7 @@ use crate::edges::{self, Edge}; use crate::xml::{self, Element as X}; +use craft_xfl::filters::{Filter as NativeFilter, FilterKind as NativeFilterKind, FilterList as NativeFilterList, FilterSide as NativeFilterSide}; use anicraft_doc::{ Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, ColorTransform, Filter, FilterEntry, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, CustomEase, EaseGroup, FrameScript, FrameSound, Language, Linkage, ScaleGrid, SoundSync, SourceScript, Spread, MAX_FOCAL, @@ -263,24 +264,31 @@ struct Builder<'a> { faces: HashMap, } -/// A bevel or gradient filter's `type`: `inner`, `outer` or `full` (`default` when missing). -fn filter_side(el: &X, default: FilterSide) -> FilterSide { - match el.attr("type").map(str::trim) { - Some("inner") => FilterSide::Inner, - Some("outer") => FilterSide::Outer, - Some("full") => FilterSide::Full, - _ => default, +/// Maps a neutral shared XFL filter side into the document model, applying the consumer's +/// established default when the wire value is absent or unknown. +fn filter_side(side: Option, default: FilterSide) -> FilterSide { + match side { + Some(NativeFilterSide::Inner) => FilterSide::Inner, + Some(NativeFilterSide::Outer) => FilterSide::Outer, + Some(NativeFilterSide::Full) => FilterSide::Full, + None => default, } } -/// A gradient filter's ramp: its `GradientEntry` children (directly, or in a wrapper), with -/// ratios 0..1 (or Flash's 0..255). -fn ramp(el: &X) -> Vec { - let entries = el.children.iter().flat_map(|c| if c.name == "GradientEntry" { std::slice::from_ref(c) } else { c.children.as_slice() }).filter(|g| g.name == "GradientEntry"); - let raw: Vec<(f32, Rgba)> = entries.take(anicraft_doc::MAX_RAMP_STOPS).map(|g| (g.f32("ratio").filter(|r| r.is_finite()).unwrap_or(0.0), color(g, "color", "alpha"))).collect(); +fn rgba(color: craft_xfl::shape::Color) -> Rgba { + Rgba::hex(color.rgb).with_alpha(color.alpha) +} + +/// Converts the neutral native ramp into AniCraft's sorted, normalized paint stops. +fn ramp(filter: &NativeFilter<'_, X>) -> Vec { + let raw: Vec<(f32, Rgba)> = filter + .ramp_entries() + .take(anicraft_doc::MAX_RAMP_STOPS) + .map(|entry| (entry.ratio().unwrap_or(0.0), rgba(entry.color()))) + .collect(); // One scale for the whole ramp: any ratio past 1 means bytes. - let scale = if raw.iter().any(|(r, _)| *r > 1.0) { 1.0 / 255.0 } else { 1.0 }; - let mut stops: Vec = raw.into_iter().map(|(r, c)| GradientStop { offset: (r * scale).clamp(0.0, 1.0), color: c }).collect(); + let scale = if raw.iter().any(|(ratio, _)| *ratio > 1.0) { 1.0 / 255.0 } else { 1.0 }; + let mut stops: Vec = raw.into_iter().map(|(ratio, color)| GradientStop { offset: (ratio * scale).clamp(0.0, 1.0), color }).collect(); stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); stops } @@ -493,50 +501,81 @@ impl<'a> Builder<'a> { /// are reported. fn filters(&mut self, el: &X) -> Vec { let mut out = Vec::new(); - for f in el.list("filters") { - let enabled = f.bool("enabled") != Some(false); - let num = |k: &str, d: f32| f.f32(k).unwrap_or(d); - let flag = |k: &str| f.bool(k).unwrap_or(false); - let quality = f.u32("quality").unwrap_or(1).clamp(1, 3) as u8; - let filter = match f.name.as_str() { - "BlurFilter" => Filter::Blur { blur_x: num("blurX", 5.0), blur_y: num("blurY", 5.0), quality }, - "DropShadowFilter" => Filter::DropShadow { - blur_x: num("blurX", 5.0), - blur_y: num("blurY", 5.0), - strength: num("strength", 1.0), + for f in NativeFilterList::new(el).iter() { + let enabled = f.enabled(); + let quality = f.quality(); + let num = |value: Option, default: f32| value.unwrap_or(default); + let flag = |value: Option| value.unwrap_or(false); + let filter = match f.kind() { + Some(NativeFilterKind::Blur) => Filter::Blur { blur_x: num(f.blur_x(), 5.0), blur_y: num(f.blur_y(), 5.0), quality }, + Some(NativeFilterKind::DropShadow) => Filter::DropShadow { + blur_x: num(f.blur_x(), 5.0), + blur_y: num(f.blur_y(), 5.0), + strength: num(f.strength(), 1.0), quality, - angle: num("angle", 45.0), - distance: num("distance", 4.0), - color: color(f, "color", "alpha"), - inner: flag("inner"), - knockout: flag("knockout"), - hide_object: flag("hideObject"), + angle: num(f.angle(), 45.0), + distance: num(f.distance(), 4.0), + color: rgba(f.color()), + inner: flag(f.inner()), + knockout: flag(f.knockout()), + hide_object: flag(f.hide_object()), }, - "GlowFilter" => Filter::Glow { blur_x: num("blurX", 5.0), blur_y: num("blurY", 5.0), strength: num("strength", 1.0), quality, color: color(f, "color", "alpha"), inner: flag("inner"), knockout: flag("knockout") }, - "AdjustColorFilter" => Filter::AdjustColor { brightness: num("brightness", 0.0), contrast: num("contrast", 0.0), saturation: num("saturation", 0.0), hue: num("hue", 0.0) }, - "BevelFilter" => Filter::Bevel { - blur_x: num("blurX", 5.0), - blur_y: num("blurY", 5.0), - strength: num("strength", 1.0), + Some(NativeFilterKind::Glow) => Filter::Glow { + blur_x: num(f.blur_x(), 5.0), + blur_y: num(f.blur_y(), 5.0), + strength: num(f.strength(), 1.0), quality, - angle: num("angle", 45.0), - distance: num("distance", 5.0), - shadow_color: color(f, "shadowColor", "shadowAlpha"), - highlight_color: if f.attr("highlightColor").is_some() { color(f, "highlightColor", "highlightAlpha") } else { Rgba::WHITE.with_alpha(num("highlightAlpha", 1.0).clamp(0.0, 1.0)) }, - side: filter_side(f, FilterSide::Inner), - knockout: flag("knockout"), + color: rgba(f.color()), + inner: flag(f.inner()), + knockout: flag(f.knockout()), }, - "GradientGlowFilter" | "GradientBevelFilter" => { - let glow = f.name == "GradientGlowFilter"; - let (blur_x, blur_y, strength, angle, distance, knockout) = (num("blurX", 5.0), num("blurY", 5.0), num("strength", 1.0), num("angle", 45.0), num("distance", 5.0), flag("knockout")); - let stops = ramp(f); - if glow { - Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops: if stops.is_empty() { anicraft_doc::default_glow_ramp() } else { stops }, side: filter_side(f, FilterSide::Outer), knockout } - } else { - Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, stops: if stops.is_empty() { anicraft_doc::default_bevel_ramp() } else { stops }, side: filter_side(f, FilterSide::Inner), knockout } + Some(NativeFilterKind::AdjustColor) => Filter::AdjustColor { + brightness: num(f.brightness(), 0.0), + contrast: num(f.contrast(), 0.0), + saturation: num(f.saturation(), 0.0), + hue: num(f.hue(), 0.0), + }, + Some(NativeFilterKind::Bevel) => Filter::Bevel { + blur_x: num(f.blur_x(), 5.0), + blur_y: num(f.blur_y(), 5.0), + strength: num(f.strength(), 1.0), + quality, + angle: num(f.angle(), 45.0), + distance: num(f.distance(), 5.0), + shadow_color: rgba(f.shadow_color()), + highlight_color: f.highlight_color().map(rgba).unwrap_or_else(|| Rgba::WHITE.with_alpha(num(f.highlight_alpha(), 1.0).clamp(0.0, 1.0))), + side: filter_side(f.side(), FilterSide::Inner), + knockout: flag(f.knockout()), + }, + Some(NativeFilterKind::GradientGlow) => { + let stops = ramp(&f); + Filter::GradientGlow { + blur_x: num(f.blur_x(), 5.0), + blur_y: num(f.blur_y(), 5.0), + strength: num(f.strength(), 1.0), + quality, + angle: num(f.angle(), 45.0), + distance: num(f.distance(), 5.0), + stops: if stops.is_empty() { anicraft_doc::default_glow_ramp() } else { stops }, + side: filter_side(f.side(), FilterSide::Outer), + knockout: flag(f.knockout()), } } - _ => { + Some(NativeFilterKind::GradientBevel) => { + let stops = ramp(&f); + Filter::GradientBevel { + blur_x: num(f.blur_x(), 5.0), + blur_y: num(f.blur_y(), 5.0), + strength: num(f.strength(), 1.0), + quality, + angle: num(f.angle(), 45.0), + distance: num(f.distance(), 5.0), + stops: if stops.is_empty() { anicraft_doc::default_bevel_ramp() } else { stops }, + side: filter_side(f.side(), FilterSide::Inner), + knockout: flag(f.knockout()), + } + } + None => { self.report.skip("unknown filters"); continue; } diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 67c73580..dbc3952b 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -211,6 +211,17 @@ fn symbols_instances_and_the_tween_between_them() { assert!(x > 100.0 && x < 300.0, "{x}"); } +#[test] +fn bevel_filter_keeps_white_highlight_when_only_alpha_is_stored() { + let mut files = package(); + let document = Box::leak(DOC.replace("", "").into_boxed_str()); + files.insert("DOMDocument.xml", document); + let (doc, _) = import(&files).unwrap(); + let ElementKind::Symbol { filters, .. } = &doc.timeline(0).layers[0].keyframes[0].elements[0].kind else { panic!("a symbol instance") }; + let anicraft_doc::Filter::Bevel { highlight_color, .. } = filters[0].filter else { panic!("a bevel filter") }; + assert_eq!(highlight_color, Rgba::WHITE.with_alpha(0.4)); +} + #[test] fn shapes_become_fills_and_strokes() { let (doc, _) = import(&package()).unwrap(); From 3696a4b4ef4a2ae3bda40ab80ca07625431972e6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 02:30:14 +0000 Subject: [PATCH 081/570] Move XFL shape hint parsing to craft-libs --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 27 +++++++++++---------------- 3 files changed, 15 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 95859cca..ebdff9d3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6f7106fe0a00ff863c8498fb4dcf33a993fb8b01#6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" +source = "git+https://github.com/storytold/craft-libs?rev=6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0#6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6f7106fe0a00ff863c8498fb4dcf33a993fb8b01#6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" +source = "git+https://github.com/storytold/craft-libs?rev=6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0#6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 72365c69..8a508bda 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6f7106fe0a00ff863c8498fb4dcf33a993fb8b01" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index c702f7c5..06a6558e 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -765,8 +765,9 @@ impl<'a> Builder<'a> { craft_xfl::document::TweenType::Other => {} } // Shape hints sit on both keyframes of a shape tween; they are paired up below. - if let Some(h) = f.child("shapeHints").filter(|h| !h.children.is_empty()) { - raw_hints.insert(start, self.raw_hints(h)); + let shape_hints = craft_xfl::shape_hints::ShapeHints::new(f); + if !shape_hints.is_empty() { + raw_hints.insert(start, self.raw_hints(f)); } // Frame scripts are kept verbatim (ADR 0013 tier 1); those in the subset run. if let Some(a) = f.child("Actionscript") { @@ -892,25 +893,19 @@ impl<'a> Builder<'a> { /// `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. - fn raw_hints(&mut self, list: &X) -> Vec { - let pt = |h: &X, joined: &str, x: &str, y: &str| -> Option { - let p = match h.attr(joined) { - Some(v) => { - let mut it = v.split([',', ' ']).filter(|s| !s.trim().is_empty()).map(|s| s.trim().parse::().ok()); - Vec2::new(it.next()??, it.next()??) - } - None => Vec2::new(h.f32(x)?, h.f32(y)?), - }; - (p.is_finite() && p.x.abs() < 1e6 && p.y.abs() < 1e6).then_some(p) + fn raw_hints(&mut self, frame: &X) -> Vec { + 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 mut out: Vec = Vec::new(); - for (n, h) in list.children.iter().enumerate().take(anicraft_doc::MAX_SHAPE_HINTS * 4) { - let order = h.u32("index").map(|i| i as usize).or_else(|| h.attr("name").and_then(anicraft_doc::hint_index)).unwrap_or(n); - let Some(here) = pt(h, "startPoint", "startX", "startY").or_else(|| pt(h, "point", "x", "y")) else { + 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 { self.report.skip("shape hints without a position"); continue; }; - out.push(RawHint { order, here, end: pt(h, "endPoint", "endX", "endY") }); + out.push(RawHint { order, here, end: to_vec(hint.end_point()) }); } out.sort_by_key(|h| h.order); if out.len() > anicraft_doc::MAX_SHAPE_HINTS { From 4554224ef88369c65377a23295c5cef3dabfc8e8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 02:36:23 +0000 Subject: [PATCH 082/570] Move AniCraft XFL easing schema parsing to craft-libs --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 20 +++++++++++--------- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ebdff9d3..c38b54fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0#6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" +source = "git+https://github.com/storytold/craft-libs?rev=bb0c1c52ce25c2e051717916b489912f5105833e#bb0c1c52ce25c2e051717916b489912f5105833e" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0#6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" +source = "git+https://github.com/storytold/craft-libs?rev=bb0c1c52ce25c2e051717916b489912f5105833e#bb0c1c52ce25c2e051717916b489912f5105833e" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 8a508bda..ca0b1f3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6eac1d353dd5b1ade38f6c08b0ecc8935848e3a0" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "bb0c1c52ce25c2e051717916b489912f5105833e" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb0c1c52ce25c2e051717916b489912f5105833e" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 06a6558e..3d6d0506 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -752,9 +752,10 @@ impl<'a> Builder<'a> { craft_xfl::document::TweenType::Motion | craft_xfl::document::TweenType::Shape => { let kind = if schema_frame.tween_type == craft_xfl::document::TweenType::Shape { TweenKind::Shape } else { TweenKind::Classic }; - let orient = f.bool("motionTweenOrientToPath").unwrap_or(false); + let native_tween = craft_xfl::tween::FrameTween::new(f); + let orient = native_tween.orient_to_path().unwrap_or(false); if kind == TweenKind::Classic - && f.attr("motionTweenRotate").is_some_and(|r| matches!(r.trim(), "clockwise" | "counter-clockwise")) + && native_tween.rotate().is_some_and(|r| matches!(r.trim(), "clockwise" | "counter-clockwise")) { self.report.skip("tween spins (turned the shortest way)"); } @@ -824,21 +825,22 @@ impl<'a> Builder<'a> { /// `useSingleEaseCurve="false"` each property group (`position`, `rotation`, `scale`, /// `color`, `filters`) has its own curve, and `all` (or the slider) eases the rest. fn easing(&mut self, f: &X) -> (Easing, Vec<(EaseGroup, Easing)>) { - let acc = f.f32("acceleration").unwrap_or(0.0).clamp(-100.0, 100.0); + let native_tween = craft_xfl::tween::FrameTween::new(f); + let acc = native_tween.acceleration().unwrap_or(0.0).clamp(-100.0, 100.0); let classic = if acc == 0.0 { Easing::Linear } else { Easing::Classic(acc) }; - if f.bool("hasCustomEase") != Some(true) { + if native_tween.has_custom_ease() != Some(true) { return (classic, Vec::new()); } - let curves: Vec<&X> = f.list("tweens").iter().filter(|c| c.name == "CustomEase").collect(); + let curves: Vec<_> = native_tween.custom_eases().collect(); if curves.is_empty() { self.report.skip("custom eases without their curve (drawn with the simple ease)"); return (classic, Vec::new()); } - let single = f.bool("useSingleEaseCurve") != Some(false) || curves.len() == 1; + let single = native_tween.use_single_ease_curve() != Some(false) || curves.len() == 1; let mut main = None; let mut groups: Vec<(EaseGroup, Easing)> = Vec::new(); for (n, c) in curves.iter().enumerate() { - let target = c.attr("target").map_or("all", str::trim); + let target = c.target(); // One curve for everything: the first. if single && n > 0 { break; @@ -863,10 +865,10 @@ impl<'a> Builder<'a> { } /// One `` curve; `None` (reported) when its points don't make a curve. - fn ease_curve(&mut self, c: &X) -> Option { + fn ease_curve(&mut self, c: &craft_xfl::tween::CustomEase<'_, X>) -> Option { // Far more than a curve keeps (longer ones are thinned), and one more to tell. const MAX_READ: usize = anicraft_doc::MAX_EASE_POINTS * 3 * 16 + 1; - let pts: Vec = c.children.iter().filter(|p| p.name == "Point").take(MAX_READ + 1).map(|p| Vec2::new(p.f32("x").unwrap_or(0.0), p.f32("y").unwrap_or(0.0))).collect(); + let pts: Vec = c.points().take(MAX_READ + 1).map(|point| Vec2::new(point.x().unwrap_or(0.0), point.y().unwrap_or(0.0))).collect(); if pts.len() > MAX_READ { self.report.skip("custom ease curves too long to read (drawn with the simple ease)"); return None; From d4cda23efd1349416854ed4c65a467f83938b0ef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 02:41:19 +0000 Subject: [PATCH 083/570] Move AniCraft frame sound schema parsing to craft-libs --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 44 ++++++++++++++++++++-------------------- 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c38b54fe..a65b9f07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb0c1c52ce25c2e051717916b489912f5105833e#bb0c1c52ce25c2e051717916b489912f5105833e" +source = "git+https://github.com/storytold/craft-libs?rev=858d1cde8a7e70d88f262cb636871e3ce9e1f60b#858d1cde8a7e70d88f262cb636871e3ce9e1f60b" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb0c1c52ce25c2e051717916b489912f5105833e#bb0c1c52ce25c2e051717916b489912f5105833e" +source = "git+https://github.com/storytold/craft-libs?rev=858d1cde8a7e70d88f262cb636871e3ce9e1f60b#858d1cde8a7e70d88f262cb636871e3ce9e1f60b" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index ca0b1f3b..4a3e4fb3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "bb0c1c52ce25c2e051717916b489912f5105833e" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb0c1c52ce25c2e051717916b489912f5105833e" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "858d1cde8a7e70d88f262cb636871e3ce9e1f60b" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "858d1cde8a7e70d88f262cb636871e3ce9e1f60b" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 3d6d0506..9f43d3bd 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -774,8 +774,8 @@ impl<'a> Builder<'a> { if let Some(a) = f.child("Actionscript") { k.script = self.frame_script(a); } - if let Some(name) = f.attr("soundName").filter(|n| !n.trim().is_empty()) { - k.sound = self.frame_sound(f, name); + if craft_xfl::sound::FrameSound::new(f).name().is_some_and(|name| !name.trim().is_empty()) { + k.sound = self.frame_sound(f); } let mut els = Vec::new(); self.elements(f.list("elements"), &Affine::IDENTITY, &mut els, 0); @@ -1138,22 +1138,24 @@ impl<'a> Builder<'a> { /// start, stop or stream), repeats (`soundLoopMode` loop or repeat, `soundLoop` times) and /// effect (`soundEffect`, and the volume points of a custom one in `SoundEnvelope`). /// Buttons' frames included: they play as the pointer changes the button's state. - fn frame_sound(&mut self, f: &X, name: &str) -> Option { + fn frame_sound(&mut self, f: &X) -> Option { + let native = craft_xfl::sound::FrameSound::new(f); + let name = native.name()?; let Some(id) = self.sounds.get(name).copied() else { self.report.skip("frame sounds whose sound isn't in the package"); return None; }; let mut fs = FrameSound::new(id); - fs.sync = match f.attr("soundSync").map(str::trim) { - Some("start") => SoundSync::Start, - Some("stop") => SoundSync::Stop, - Some("stream") => SoundSync::Stream, - _ => SoundSync::Event, + fs.sync = match native.sync_mode() { + craft_xfl::sound::SyncMode::Start => SoundSync::Start, + craft_xfl::sound::SyncMode::Stop => SoundSync::Stop, + craft_xfl::sound::SyncMode::Stream => SoundSync::Stream, + craft_xfl::sound::SyncMode::Event => SoundSync::Event, }; - fs.looping = f.attr("soundLoopMode").map(str::trim) == Some("loop"); - fs.repeat = f.u32("soundLoop").unwrap_or(1).clamp(1, anicraft_doc::sound::MAX_REPEAT); - fs.effect = self.sound_effect(f); - if f.attr("inPoint44").is_some() || f.attr("outPoint44").is_some() { + fs.looping = native.looping(); + fs.repeat = native.repeat().unwrap_or(1).clamp(1, anicraft_doc::sound::MAX_REPEAT); + fs.effect = self.sound_effect(&native); + if native.has_in_point() || native.has_out_point() { self.report.skip("sound in and out points (played whole)"); } Some(fs) @@ -1163,8 +1165,8 @@ impl<'a> Builder<'a> { /// volume points of its envelope (`SoundEnvelope`; each `SoundEnvelopePoint` a time in /// samples at 44.1 kHz, `mark44`, and a level per channel, `level0` left and `level1` right, /// `0..=32768`, as the SWF format's `SOUNDENVELOPE` keeps them). - fn sound_effect(&mut self, f: &X) -> SoundEffect { - let key: String = f.attr("soundEffect").unwrap_or("").chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect(); + fn sound_effect(&mut self, frame: &craft_xfl::sound::FrameSound<'_, X>) -> SoundEffect { + let key = frame.effect_key(); let preset = match key.as_str() { "" | "none" => Some(SoundEffect::None), "left" | "leftchannel" => Some(SoundEffect::LeftChannel), @@ -1175,14 +1177,12 @@ impl<'a> Builder<'a> { "fadeout" => Some(SoundEffect::FadeOut), _ => None, }; - let points: Vec = f - .child("SoundEnvelope") - .map(|e| e.children.iter().filter(|p| p.name == "SoundEnvelopePoint").take(anicraft_doc::sound::MAX_ENVELOPE_POINTS).collect::>()) - .unwrap_or_default() - .into_iter() - .map(|p| { - let level = |k: &str| p.f32(k).map_or(1.0, |v| v / 32_768.0); - EnvelopePoint::new(f64::from(p.f32("mark44").unwrap_or(0.0)) / 44_100.0, level("level0"), level("level1")) + let points: Vec = frame + .envelope_points() + .take(anicraft_doc::sound::MAX_ENVELOPE_POINTS) + .map(|point| { + let level = |value: Option| value.map_or(1.0, |value| value / 32_768.0); + EnvelopePoint::new(f64::from(point.mark44().unwrap_or(0.0)) / 44_100.0, level(point.level0()), level(point.level1())) }) .collect(); match preset { From a9a7da81c74104f5c076f6df4c14a49557edf4dd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 03:04:37 +0000 Subject: [PATCH 084/570] Refresh XFL consumer candidate pin --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a65b9f07..98dd175d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=858d1cde8a7e70d88f262cb636871e3ce9e1f60b#858d1cde8a7e70d88f262cb636871e3ce9e1f60b" +source = "git+https://github.com/storytold/craft-libs?rev=325354218a3fabe7c6eeade4a88ab1072d8d1ffd#325354218a3fabe7c6eeade4a88ab1072d8d1ffd" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=858d1cde8a7e70d88f262cb636871e3ce9e1f60b#858d1cde8a7e70d88f262cb636871e3ce9e1f60b" +source = "git+https://github.com/storytold/craft-libs?rev=325354218a3fabe7c6eeade4a88ab1072d8d1ffd#325354218a3fabe7c6eeade4a88ab1072d8d1ffd" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 4a3e4fb3..92b832f4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "858d1cde8a7e70d88f262cb636871e3ce9e1f60b" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "858d1cde8a7e70d88f262cb636871e3ce9e1f60b" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "325354218a3fabe7c6eeade4a88ab1072d8d1ffd" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "325354218a3fabe7c6eeade4a88ab1072d8d1ffd" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From 1fa8ec7ad95aa50cfe40c00f364141021df1b470 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 03:17:57 +0000 Subject: [PATCH 085/570] Pin XFL consumer to refreshed shared candidate --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 98dd175d..f143d31e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=325354218a3fabe7c6eeade4a88ab1072d8d1ffd#325354218a3fabe7c6eeade4a88ab1072d8d1ffd" +source = "git+https://github.com/storytold/craft-libs?rev=100b68ed48e82c3d352bd68d16120a7355a011a1#100b68ed48e82c3d352bd68d16120a7355a011a1" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=325354218a3fabe7c6eeade4a88ab1072d8d1ffd#325354218a3fabe7c6eeade4a88ab1072d8d1ffd" +source = "git+https://github.com/storytold/craft-libs?rev=100b68ed48e82c3d352bd68d16120a7355a011a1#100b68ed48e82c3d352bd68d16120a7355a011a1" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 92b832f4..14755131 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "325354218a3fabe7c6eeade4a88ab1072d8d1ffd" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "325354218a3fabe7c6eeade4a88ab1072d8d1ffd" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "100b68ed48e82c3d352bd68d16120a7355a011a1" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "100b68ed48e82c3d352bd68d16120a7355a011a1" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From 9484da6dc3bdb0c63e59686bacf9dcb390f6d0c1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 03:21:11 +0000 Subject: [PATCH 086/570] Pin XFL text schema consumer to merged revision --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4e1ea254..2f964dd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=603aaacba66f6512939be84b5ba9cc94e9426297#603aaacba66f6512939be84b5ba9cc94e9426297" +source = "git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93#7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=603aaacba66f6512939be84b5ba9cc94e9426297#603aaacba66f6512939be84b5ba9cc94e9426297" +source = "git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93#7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 9586b131..3f16dfb0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "603aaacba66f6512939be84b5ba9cc94e9426297" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "603aaacba66f6512939be84b5ba9cc94e9426297" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From a61c919b3a351b4ce630b0521099e77ebe9d3687 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 04:32:41 +0000 Subject: [PATCH 087/570] Refresh XFL consumer shared pin --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f143d31e..15a8a46a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=100b68ed48e82c3d352bd68d16120a7355a011a1#100b68ed48e82c3d352bd68d16120a7355a011a1" +source = "git+https://github.com/storytold/craft-libs?rev=b8ac3142860121c32144d82c6cd1f84e2ee99058#b8ac3142860121c32144d82c6cd1f84e2ee99058" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=100b68ed48e82c3d352bd68d16120a7355a011a1#100b68ed48e82c3d352bd68d16120a7355a011a1" +source = "git+https://github.com/storytold/craft-libs?rev=b8ac3142860121c32144d82c6cd1f84e2ee99058#b8ac3142860121c32144d82c6cd1f84e2ee99058" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 14755131..73aaa0c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "100b68ed48e82c3d352bd68d16120a7355a011a1" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "100b68ed48e82c3d352bd68d16120a7355a011a1" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b8ac3142860121c32144d82c6cd1f84e2ee99058" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b8ac3142860121c32144d82c6cd1f84e2ee99058" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From 3145b23b3f28a4d7450e13a02560be37f17b6ec5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 05:01:01 +0000 Subject: [PATCH 088/570] refactor(xfl): delegate library metadata to craft-libs --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 48 +++++++++++++++++++++++++--------------- crates/xfl/src/tests.rs | 32 +++++++++++++++++++++++++++ 4 files changed, 66 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2f964dd1..7c446fa5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93#7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" +source = "git+https://github.com/storytold/craft-libs?rev=fc82610ef916fe3c4d1b94597805dcf41dc9e111#fc82610ef916fe3c4d1b94597805dcf41dc9e111" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93#7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" +source = "git+https://github.com/storytold/craft-libs?rev=fc82610ef916fe3c4d1b94597805dcf41dc9e111#fc82610ef916fe3c4d1b94597805dcf41dc9e111" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 3f16dfb0..d3afd2a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "fc82610ef916fe3c4d1b94597805dcf41dc9e111" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "fc82610ef916fe3c4d1b94597805dcf41dc9e111" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index a669d2ff..1da95fb1 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -1164,8 +1164,8 @@ impl<'a> Builder<'a> { /// Allocates ids for every symbol the document lists, parsing their files. fn register_symbols(&mut self, root: &X) -> Result<(), XflError> { let mut seen = HashSet::new(); - for inc in root.list("symbols").iter().filter(|i| i.name == "Include").take(MAX_SYMBOLS) { - let Some(href) = inc.attr("href") else { continue }; + for inc in craft_xfl::document::symbol_includes(root).take(MAX_SYMBOLS) { + let Some(href) = inc.href() else { continue }; if !seen.insert(href.to_string()) { continue; } @@ -1200,16 +1200,17 @@ impl<'a> Builder<'a> { if item.name != "DOMSymbolItem" { continue; } - let name = item.attr("name").map(str::to_string).unwrap_or_else(|| href.trim_end_matches(".xml").to_string()); + let symbol = craft_xfl::document::SymbolItem::new(&item); + let name = symbol.name().map(str::to_string).unwrap_or_else(|| href.trim_end_matches(".xml").to_string()); // The format leaves out default values, and a symbol's default type is movie clip: // only graphics and buttons say what they are. - let kind = match item.attr("symbolType").map(str::trim) { + let kind = match symbol.symbol_type().map(str::trim) { Some("graphic") => SymbolKind::Graphic, Some("button") => SymbolKind::Button, _ => SymbolKind::MovieClip, }; let id = SymbolId(self.doc.alloc_id()); - let linkage = self.linkage(&item); + let linkage = self.linkage(symbol); self.ids.insert(name.clone(), id); self.pending.push(PendingSymbol { id, name, kind, linkage, item, timeline: model.symbol_timeline }); } @@ -1218,12 +1219,20 @@ impl<'a> Builder<'a> { /// A library symbol's script class (`linkageClassName`, or an older document's /// `linkageIdentifier`, when `linkageExportForAS` doesn't turn it off) and its base class. - fn linkage(&mut self, item: &X) -> Option { - if item.attr("linkageExportForAS").is_some_and(|v| v.trim() != "true") { + fn linkage(&mut self, item: craft_xfl::document::SymbolItem<'_, X>) -> Option { + if item.linkage_export_for_action_script().is_some_and(|v| v.trim() != "true") { return None; } - let class = ["linkageClassName", "linkageIdentifier"].iter().find_map(|k| item.attr(k).map(str::trim).filter(|c| !c.is_empty()))?; - let base = item.attr("linkageBaseClass").map(str::trim).filter(|b| anicraft_doc::actions::valid_class_name(b)).unwrap_or(""); + let class = [item.linkage_class_name(), item.linkage_identifier()] + .into_iter() + .flatten() + .map(str::trim) + .find(|class| !class.is_empty())?; + let base = item + .linkage_base_class() + .map(str::trim) + .filter(|base| anicraft_doc::actions::valid_class_name(base)) + .unwrap_or(""); let l = Linkage { class: class.to_string(), base: base.to_string() }; if l.check().is_err() { self.report.skip("linkage classes that aren't class names (left out)"); @@ -1236,14 +1245,17 @@ impl<'a> Builder<'a> { /// A symbol's 9-slice guides (ADR 0055): `scaleGridLeft`, `scaleGridRight`, `scaleGridTop` /// and `scaleGridBottom` on the `DOMSymbolItem`, in the symbol's space, written when its /// guides are on. All four or none; guides given the wrong way round are put in order. - fn scale_grid(&mut self, item: &X) -> Option { - let keys = ["scaleGridLeft", "scaleGridRight", "scaleGridTop", "scaleGridBottom"]; - if keys.iter().all(|k| item.attr(k).is_none()) { + fn scale_grid(&mut self, item: craft_xfl::document::SymbolItem<'_, X>) -> Option { + if !item.has_scale_grid() { return None; } - let v: Vec = keys.iter().filter_map(|k| item.f32(k)).collect(); - let grid = match v[..] { - [l, r, t, b] => Some(ScaleGrid { left: l.min(r), right: l.max(r), top: t.min(b), bottom: t.max(b) }), + let grid = match (item.scale_grid_left(), item.scale_grid_right(), item.scale_grid_top(), item.scale_grid_bottom()) { + (Some(left), Some(right), Some(top), Some(bottom)) => Some(ScaleGrid { + left: left.min(right), + right: left.max(right), + top: top.min(bottom), + bottom: top.max(bottom), + }), _ => None, }; let grid = grid.filter(|g| g.check().is_ok()); @@ -1285,7 +1297,7 @@ impl<'a> Builder<'a> { None => Timeline { layers: vec![Arc::new(Layer::new(LayerId(self.doc.alloc_id()), "Layer 1"))] }, }; let short = name.rsplit('/').next().unwrap_or(&name).to_string(); - let scale_grid = self.scale_grid(&item); + let scale_grid = self.scale_grid(craft_xfl::document::SymbolItem::new(&item)); self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, scale_grid, scale_grid_kept: None, timeline })); self.place_in_folder(&name, anicraft_doc::LibraryItem::Symbol(id)); } @@ -1294,8 +1306,8 @@ impl<'a> Builder<'a> { /// The Library's folders (``, so empty ones come across too), each a path such as /// `Characters/Hero` (ADR 0050). fn register_folders(&mut self, root: &X) { - for f in root.list("folders").iter().filter(|f| f.name == "DOMFolderItem").take(anicraft_doc::library::MAX_FOLDERS) { - if let Some(path) = f.attr("name") { + for folder in craft_xfl::document::library_folders(root).take(anicraft_doc::library::MAX_FOLDERS) { + if let Some(path) = folder.name() { self.doc.ensure_folder_path(path); } } diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 67c73580..6dbbd71d 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -491,6 +491,38 @@ trace(n);]]> + + + + + + + + "#; + let symbol = r#" + + "#; + let files = HashMap::from([("DOMDocument.xml", document), ("LIBRARY/Ui/Panel.xml", symbol)]); + let (doc, report) = import(&files).unwrap(); + + assert_eq!(doc.library.len(), 1, "repeated Include paths still register one library symbol"); + let panel = &doc.library[0]; + assert_eq!(panel.name, "Panel"); + assert_eq!(panel.kind, SymbolKind::Button); + assert_eq!(panel.linkage.as_ref().map(|linkage| (linkage.class.as_str(), linkage.base.as_str())), Some(("ui.Panel", "flash.display.MovieClip"))); + let grid = panel.scale_grid.expect("all four finite guide attributes form a grid"); + assert_eq!((grid.left, grid.right, grid.top, grid.bottom), (10.0, 90.0, 10.0, 30.0)); + let folder_paths: Vec = doc.library_tree.folders.iter().map(|folder| doc.entry_path(anicraft_doc::LibraryEntry::Folder(folder.id))).collect(); + assert_eq!(folder_paths, ["Empty", "Ui"]); + assert!(!report.skipped.contains_key("missing library files"), "non-Include extension nodes are ignored"); +} + #[test] fn loose_shapes_come_in_raw_and_drawing_objects_and_groups_as_groups() { // Animate's raw shapes (merge drawing) are loose `DOMShape`s; a drawing object says so, and From 164c3ac955bcbae3d4f34fbcc811cf0114c05955 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 05:38:28 +0000 Subject: [PATCH 089/570] chore(xfl): pin shared sound schema merge --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 15a8a46a..d940a183 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8ac3142860121c32144d82c6cd1f84e2ee99058#b8ac3142860121c32144d82c6cd1f84e2ee99058" +source = "git+https://github.com/storytold/craft-libs?rev=bf48df0473a58c85e8bd050e23f97379dd902215#bf48df0473a58c85e8bd050e23f97379dd902215" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8ac3142860121c32144d82c6cd1f84e2ee99058#b8ac3142860121c32144d82c6cd1f84e2ee99058" +source = "git+https://github.com/storytold/craft-libs?rev=bf48df0473a58c85e8bd050e23f97379dd902215#bf48df0473a58c85e8bd050e23f97379dd902215" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 73aaa0c6..2a757451 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b8ac3142860121c32144d82c6cd1f84e2ee99058" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b8ac3142860121c32144d82c6cd1f84e2ee99058" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "bf48df0473a58c85e8bd050e23f97379dd902215" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bf48df0473a58c85e8bd050e23f97379dd902215" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From b5b4466ee64312a34ddd00299c90d941c64193c5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 06:06:03 +0000 Subject: [PATCH 090/570] chore(xfl): pin shared library metadata merge --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7c446fa5..a2d310e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fc82610ef916fe3c4d1b94597805dcf41dc9e111#fc82610ef916fe3c4d1b94597805dcf41dc9e111" +source = "git+https://github.com/storytold/craft-libs?rev=0073b2674f853ce8225bb5a8ed59c53e2ff3ab45#0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fc82610ef916fe3c4d1b94597805dcf41dc9e111#fc82610ef916fe3c4d1b94597805dcf41dc9e111" +source = "git+https://github.com/storytold/craft-libs?rev=0073b2674f853ce8225bb5a8ed59c53e2ff3ab45#0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index d3afd2a9..dacc836e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "fc82610ef916fe3c4d1b94597805dcf41dc9e111" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "fc82610ef916fe3c4d1b94597805dcf41dc9e111" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From 247e6e0e756ca30318d260cd1aba5651ac375dac Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 06:09:10 +0000 Subject: [PATCH 091/570] docs: record XFL shared schema progress --- docs/roadmap.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/roadmap.md b/docs/roadmap.md index 64a84a17..6a7acafb 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -118,6 +118,10 @@ Next, in order: ~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), ~~text~~ ✅ (one style per line; per-character styles with the text model), motion tweens, and ~~a larger self-authored corpus checked by render tests~~ ✅ (ADR 0035). + - Shared wire-schema work in progress: filters, shape hints, tweens/eases and frame-sound + envelopes now read through craft-libs views; AniCraft keeps validation and mapping into its + document models. Audit any remaining native document wire parsing before declaring the + full XFL format cutover complete. 2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅, ~~text, clip paths and masks (onto mask layers)~~ ✅ (ADR 0021). ~~dashes~~ ✅ (ADR 0046). ~~soft masks (luminance and alpha), text on a path (`textPath`) and per-character positions where simple~~ ✅ (ADR 0070). Next for SVG: booleans between two curved clips, multi-line blocks from stacked chunks, images and style sheets. ## Risks From e265a0826b1b6e78e6d72e466fea64fe94f76851 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 06:15:25 +0000 Subject: [PATCH 092/570] docs: clarify shared XFL reader status --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 6a7acafb..971fe60c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. **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. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, choosing an output device other than the system's default, `stopAllSounds` as a timeline action. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. 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). Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): 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** (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). 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. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | From dfe509e601e5b41cd0c204c381ddc98daec513ad Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 01:51:03 -0500 Subject: [PATCH 093/570] refactor(engine): share animated WebP container writing (M4) --- crates/engine/src/anim.rs | 61 +++++++++++---------------------- crates/engine/src/anim_tests.rs | 17 +++++++++ docs/roadmap.md | 2 +- 3 files changed, 38 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs index 293e5dea..7e28b96f 100644 --- a/crates/engine/src/anim.rs +++ b/crates/engine/src/anim.rs @@ -225,14 +225,14 @@ fn idat(png: &[u8]) -> Result> { Ok(out) } -/// A RIFF file's first chunk named `id`, whole (header, data and padding). +/// A RIFF file's first chunk named `id`, payload only; craft-webp owns container framing. fn riff_chunk<'a>(riff: &'a [u8], id: &[u8; 4]) -> Option<&'a [u8]> { let mut at = 12usize; while let Some(head) = riff.get(at..at + 8) { let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; let whole = 8 + len + (len & 1); if &head[0..4] == id { - return riff.get(at..at + whole).or_else(|| riff.get(at..at + 8 + len)); + return riff.get(at + 8..at + 8 + len); } at += whole; } @@ -322,47 +322,26 @@ fn apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> R Ok(out) } -fn le24(v: &mut Vec, x: u32) { - v.extend_from_slice(&x.to_le_bytes()[..3]); -} - -fn riff_push(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { - let len = u32::try_from(data.len()).map_err(|_| EngineError::Format("an animated WebP frame is too large".into()))?; - out.extend_from_slice(id); - out.extend_from_slice(&len.to_le_bytes()); - out.extend_from_slice(data); - if len & 1 == 1 { - out.push(0); - } - Ok(()) -} - -/// The animated WebP file: frames with their durations. `background` is the stage colour as -/// the `ANIM` background (RGBA), or transparent. +/// The animated WebP container is shared; frame selection, delta rectangles and timing +/// remain application policy. `Encoded::data` is a raw VP8L payload, not a RIFF chunk. fn webp_file(w: u32, h: u32, plays: u32, alpha: bool, background: [u8; 4], frames: &[(&Encoded, u32)]) -> Result> { - let mut body = b"WEBP".to_vec(); - let mut vp8x = vec![if alpha { 0x10 | 0x02 } else { 0x02 }, 0, 0, 0]; - le24(&mut vp8x, w - 1); - le24(&mut vp8x, h - 1); - riff_push(&mut body, b"VP8X", &vp8x)?; + use craft_webp::anim::{AnimFrame, AnimOptions, Payload}; + let frames: Vec<_> = frames + .iter() + .map(|(f, ms)| AnimFrame { + x: f.rect.x, + y: f.rect.y, + width: f.rect.w, + height: f.rect.h, + duration_ms: *ms, + blend: f.over, + dispose_to_background: false, + payload: Payload::Lossless { vp8l: &f.data }, + }) + .collect(); let [r, g, b, a] = background; - let mut anim = vec![b, g, r, a]; - anim.extend_from_slice(&u16::try_from(plays).unwrap_or(u16::MAX).to_le_bytes()); - riff_push(&mut body, b"ANIM", &anim)?; - for (f, ms) in frames { - let mut anmf = Vec::with_capacity(16 + f.data.len()); - le24(&mut anmf, f.rect.x / 2); - le24(&mut anmf, f.rect.y / 2); - le24(&mut anmf, f.rect.w - 1); - le24(&mut anmf, f.rect.h - 1); - le24(&mut anmf, *ms); - anmf.push(if f.over { 0 } else { 0x02 }); // blending: alpha-blend or replace; dispose: none - anmf.extend_from_slice(&f.data); - riff_push(&mut body, b"ANMF", &anmf)?; - } - let mut out = Vec::with_capacity(body.len() + 8); - riff_push(&mut out, b"RIFF", &body)?; - Ok(out) + let opts = AnimOptions { loop_count: u16::try_from(plays).unwrap_or(u16::MAX), background_bgra: [b, g, r, a], alpha, ..Default::default() }; + craft_webp::anim::animation(w, h, &frames, &opts).map_err(|e| EngineError::Format(e.to_string())) } // ----- the command ------------------------------------------------------------------------- diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs index 03dce153..02c3f88c 100644 --- a/crates/engine/src/anim_tests.rs +++ b/crates/engine/src/anim_tests.rs @@ -405,3 +405,20 @@ fn sizes() { } let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn shared_webp_container_preserves_payload_timing_loop_and_alpha() { + let px = [12, 34, 56, 128]; + let f = encode(Kind::Webp, None, &px, 1, 1).unwrap(); + assert_eq!(f.data.first(), Some(&0x2f), "raw VP8L payload, not a nested chunk"); + let bytes = webp_file(1, 1, 7, true, [1, 2, 3, 4], &[(&f, 123)]).unwrap(); + let anim = riff_chunk(&bytes, b"ANIM").unwrap(); + assert_eq!(anim, &[3, 2, 1, 4, 7, 0]); + let decoded = decode_webp(&bytes); + assert_eq!(decoded.size, (1, 1)); + assert_eq!(decoded.loop_count, 7); + assert!(decoded.alpha); + assert_eq!(decoded.frames, vec![(px.to_vec(), 123)]); + assert!(webp_file(1, 1, 0, false, [0; 4], &[]).is_err()); + assert!(webp_file(1, 1, 0, false, [0; 4], &[(&f, 1 << 24)]).is_err()); +} diff --git a/docs/roadmap.md b/docs/roadmap.md index 971fe60c..c2c604cf 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. **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. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, choosing an output device other than the system's default, `stopAllSounds` as a timeline action. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. 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). 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). 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. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | From cf31596dba56db34a47aa124cd193c8c6fb71e8e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 01:55:13 -0500 Subject: [PATCH 094/570] docs(engine): clarify shared WebP payload contract (M4) --- crates/engine/src/anim.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs index 7e28b96f..0c4af63a 100644 --- a/crates/engine/src/anim.rs +++ b/crates/engine/src/anim.rs @@ -65,7 +65,7 @@ pub struct Rect { } /// One frame, compressed: the region it covers, whether it blends over what is there (else it -/// replaces it), and its image data (PNG `IDAT` data, or a whole `VP8L` chunk). +/// replaces it), and its image data (PNG `IDAT` data, or a raw `VP8L` payload). struct Encoded { rect: Rect, over: bool, From 7a05cc1f08169d0a988e33dfc7e086fa2c8e2163 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:22:02 +0000 Subject: [PATCH 095/570] refactor(xfl): use shared native color effect view --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- crates/xfl/src/import.rs | 18 ++++++++++-------- crates/xfl/src/tests.rs | 30 +++++++++++++++++++++++++++++- 4 files changed, 43 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a2d310e3..09dfd718 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0073b2674f853ce8225bb5a8ed59c53e2ff3ab45#0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" +source = "git+https://github.com/storytold/craft-libs?rev=502f056d6cc4a708e4be53a5bd53d726b07c3440#502f056d6cc4a708e4be53a5bd53d726b07c3440" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0073b2674f853ce8225bb5a8ed59c53e2ff3ab45#0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" +source = "git+https://github.com/storytold/craft-libs?rev=502f056d6cc4a708e4be53a5bd53d726b07c3440#502f056d6cc4a708e4be53a5bd53d726b07c3440" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index dacc836e..952d9b02 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0073b2674f853ce8225bb5a8ed59c53e2ff3ab45" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "502f056d6cc4a708e4be53a5bd53d726b07c3440" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "502f056d6cc4a708e4be53a5bd53d726b07c3440" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 3f6551c9..2c195cf4 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -610,19 +610,21 @@ impl<'a> Builder<'a> { /// channel's multiplier other than 1 or an offset, −255..255), or alpha alone. Values are /// clamped into Animate's ranges. fn color_effect(&mut self, c: &X) -> ColorEffect { - let mul = |k: &str| c.f32(k).filter(|v| v.is_finite()).unwrap_or(1.0); - let off = |k: &str| c.f32(k).filter(|v| v.is_finite()).unwrap_or(0.0) / 255.0; - let alpha = mul("alphaMultiplier"); - let fx = if let Some(t) = c.f32("tintMultiplier") { - let tint = ColorEffect::Tint { color: color(c, "tintColor", "__none").with_alpha(1.0), amount: t }; + let native = craft_xfl::shape::NativeColorEffect::new(c); + let multipliers = native.multipliers(); + let alpha = multipliers[3]; + let fx = if let Some(t) = native.tint_multiplier() { + let tint_color = native.tint_color(); + let tint = ColorEffect::Tint { color: Rgba::hex(tint_color.rgb).with_alpha(1.0), amount: t }; if alpha != 1.0 { tint.with_alpha(alpha) } else { tint } - } else if let Some(b) = c.f32("brightness").filter(|b| *b != 0.0) { + } else if let Some(b) = native.brightness().filter(|b| *b != 0.0) { let bright = ColorEffect::Brightness(b); if alpha != 1.0 { bright.with_alpha(alpha) } else { bright } } else { + let offsets = native.offsets().map(|value| value / 255.0); let t = ColorTransform { - mul: [mul("redMultiplier"), mul("greenMultiplier"), mul("blueMultiplier"), alpha], - add: [off("redOffset"), off("greenOffset"), off("blueOffset"), off("alphaOffset")], + mul: multipliers, + add: offsets, }; if t.changes_colour() || t.add[3] != 0.0 { ColorEffect::Advanced(t) diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 97f57f1d..9e1ca2ef 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -1,7 +1,7 @@ //! Import tests on a small, self-authored XFL package. use crate::import::{XflError, import_with}; -use anicraft_doc::{ElementKind, LayerKind, LoopMode, Paint, Rgba, SymbolKind, evaluate}; +use anicraft_doc::{ColorEffect, ColorTransform, ElementKind, LayerKind, LoopMode, Paint, Rgba, SymbolKind, evaluate}; use std::collections::HashMap; #[test] @@ -211,6 +211,34 @@ fn symbols_instances_and_the_tween_between_them() { assert!(x > 100.0 && x < 300.0, "{x}"); } +#[test] +fn shared_native_color_effect_view_preserves_anicraft_style_mapping() { + let document = r##" + + + + + + + "##; + let symbol = r#""#; + let files = HashMap::from([("DOMDocument.xml", document), ("LIBRARY/Target.xml", symbol)]); + let (doc, _) = import(&files).unwrap(); + let elements = &doc.timeline(0).layers[0].keyframes[0].elements; + + let tint = ColorTransform { mul: [0.75, 0.75, 0.75, 0.5], add: [0.25 * 0x33 as f32 / 255.0, 0.25 * 0x66 as f32 / 255.0, 0.25 * 0x99 as f32 / 255.0, 0.0] }; + assert_eq!(elements[0].name, "Tint"); + assert_eq!(elements[0].color, ColorEffect::Advanced(tint).sanitized(), "tint keeps precedence over brightness and composes alpha"); + + let bright = ColorEffect::Brightness(-0.25).with_alpha(0.75); + assert_eq!(elements[1].name, "Bright"); + assert_eq!(elements[1].color, bright.sanitized()); + + let advanced = ColorTransform { mul: [2.0, 1.0, -0.5, 0.5], add: [1.0, -0.5, 0.0, 128.0 / 255.0] }; + assert_eq!(elements[2].name, "Advanced"); + assert_eq!(elements[2].color, ColorEffect::Advanced(advanced).sanitized(), "invalid multipliers default to identity and offsets stay in XFL byte units until mapping"); +} + #[test] fn bevel_filter_keeps_white_highlight_when_only_alpha_is_stored() { let mut files = package(); From de7f52f207b6189b2ec8b43be1bac0248854fa34 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:31:11 +0000 Subject: [PATCH 096/570] test(xfl): tighten native color effect parity --- crates/xfl/src/import.rs | 5 +---- crates/xfl/src/tests.rs | 9 +++++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 2c195cf4..89c3acfb 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -622,10 +622,7 @@ impl<'a> Builder<'a> { if alpha != 1.0 { bright.with_alpha(alpha) } else { bright } } else { let offsets = native.offsets().map(|value| value / 255.0); - let t = ColorTransform { - mul: multipliers, - add: offsets, - }; + let t = ColorTransform { mul: multipliers, add: offsets }; if t.changes_colour() || t.add[3] != 0.0 { ColorEffect::Advanced(t) } else if alpha != 1.0 { diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 9e1ca2ef..cc981731 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -226,7 +226,8 @@ fn shared_native_color_effect_view_preserves_anicraft_style_mapping() { let (doc, _) = import(&files).unwrap(); let elements = &doc.timeline(0).layers[0].keyframes[0].elements; - let tint = ColorTransform { mul: [0.75, 0.75, 0.75, 0.5], add: [0.25 * 0x33 as f32 / 255.0, 0.25 * 0x66 as f32 / 255.0, 0.25 * 0x99 as f32 / 255.0, 0.0] }; + let mut tint = ColorTransform::tint(Rgba::hex(0x336699), 0.25); + tint.mul[3] = 0.5; assert_eq!(elements[0].name, "Tint"); assert_eq!(elements[0].color, ColorEffect::Advanced(tint).sanitized(), "tint keeps precedence over brightness and composes alpha"); @@ -236,7 +237,11 @@ fn shared_native_color_effect_view_preserves_anicraft_style_mapping() { let advanced = ColorTransform { mul: [2.0, 1.0, -0.5, 0.5], add: [1.0, -0.5, 0.0, 128.0 / 255.0] }; assert_eq!(elements[2].name, "Advanced"); - assert_eq!(elements[2].color, ColorEffect::Advanced(advanced).sanitized(), "invalid multipliers default to identity and offsets stay in XFL byte units until mapping"); + assert_eq!( + elements[2].color, + ColorEffect::Advanced(advanced).sanitized(), + "invalid multipliers default to identity and offsets stay in XFL byte units until mapping" + ); } #[test] From 95a8ea65e43ec3daf2f23eed719ca4cfac83521e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:53:39 +0000 Subject: [PATCH 097/570] chore(xfl): pin merged shared color effect view --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 09dfd718..95897439 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-xfl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=502f056d6cc4a708e4be53a5bd53d726b07c3440#502f056d6cc4a708e4be53a5bd53d726b07c3440" +source = "git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11#b67b9f90c50091a3090f93fa054c34e409edba11" dependencies = [ "craft-xml", "miniz_oxide 0.8.9", @@ -1329,7 +1329,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=502f056d6cc4a708e4be53a5bd53d726b07c3440#502f056d6cc4a708e4be53a5bd53d726b07c3440" +source = "git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11#b67b9f90c50091a3090f93fa054c34e409edba11" dependencies = [ "quick-xml 0.41.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index 952d9b02..292dd09b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "502f056d6cc4a708e4be53a5bd53d726b07c3440" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "502f056d6cc4a708e4be53a5bd53d726b07c3440" } +craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" From 88afd1dfccdbf61c3cf2a25fe9779d68f7d268e9 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 14:13:51 +0530 Subject: [PATCH 098/570] fix(engine): keep the stage picture in the edited scene (#305) --- crates/engine/src/editing.rs | 8 +++++++- crates/engine/src/editing_tests.rs | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index 5024ceb3..f7db5935 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -277,7 +277,13 @@ impl Session { /// timeline at its playhead where its instance stands, over the timelines it sits in dimmed. pub fn stage_picture(&self) -> Arc { let Some(view) = self.edit_view() else { - return Arc::new(StagePicture { doc: self.doc.clone(), frame: self.doc.scene_start(self.scene).saturating_add(self.frame), state: self.state, front: None }); + // The stage picture is a movie frame (`stage_start + frame`), and a playhead moved + // past the scene's last frame would otherwise land in the next scene (#305): the + // editor shows the active scene alone, at its last frame. + let scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); + let last = self.doc.timeline(scene).frame_count().saturating_sub(1); + let frame = self.doc.scene_start(scene).saturating_add(self.frame.min(last)); + return Arc::new(StagePicture { doc: self.doc.clone(), frame, state: self.state, front: None }); }; let mut h = std::collections::hash_map::DefaultHasher::new(); (self.state, self.scene, self.frame).hash(&mut h); diff --git a/crates/engine/src/editing_tests.rs b/crates/engine/src/editing_tests.rs index 4b38fa91..5740ba99 100644 --- a/crates/engine/src/editing_tests.rs +++ b/crates/engine/src/editing_tests.rs @@ -159,6 +159,21 @@ fn an_open_button_shows_its_hit_area_over_its_other_states() { assert_eq!(s.hit_overlay(), None); } +#[test] +fn a_playhead_past_the_scene_end_shows_that_scene_not_the_next_one() { + let mut s = Session::default(); + // Scene 2 holds a blue square; Scene 1 stays empty with a single frame. + run(&mut s, "scene.new", json!({"name": "Second"})); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 40, "h": 40, "fill": "#0000ff", "stroke": null, "object": true})); + run(&mut s, "scene.select", json!({"scene": 0})); + assert_eq!(s.doc.scenes.len(), 2); + // The playhead can be moved far past Scene 1's one frame (#305). + s.set_frame(8); + let pic = s.stage_picture(); + assert_eq!(pic.doc.locate(pic.frame), (0, 0), "the picture is Scene 1's last frame, not Scene 2's"); + assert!(anicraft_doc::evaluate(&pic.doc, pic.frame).items.is_empty(), "Scene 2's artwork is not drawn in Scene 1"); +} + #[test] fn the_stage_shows_the_open_symbol_in_place_over_the_dimmed_stage() { let (mut s, _, _) = boxed(); From ccb736201c2761cd7062433c28f18e65c00aebd4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 04:46:36 -0500 Subject: [PATCH 099/570] fix(engine): pin exported shared WebP animation API --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d940a183..61937882 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1311,7 +1311,7 @@ dependencies = [ [[package]] name = "craft-webp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=0c144b7d983899d4b5b281046dd03a8b1ab35fbb#0c144b7d983899d4b5b281046dd03a8b1ab35fbb" dependencies = [ "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 2a757451..0d6b3477 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,7 @@ craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["decode", "pcm-encode"] } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "0c144b7d983899d4b5b281046dd03a8b1ab35fbb" } craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "bf48df0473a58c85e8bd050e23f97379dd902215" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bf48df0473a58c85e8bd050e23f97379dd902215" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same From 47e96c0e17d6c9932643d6260f9bf94fac2654e9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 05:38:15 -0500 Subject: [PATCH 100/570] test(engine): distinguish WebP still decode from animation timing --- crates/engine/src/anim_tests.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs index 02c3f88c..f5730fbf 100644 --- a/crates/engine/src/anim_tests.rs +++ b/crates/engine/src/anim_tests.rs @@ -414,11 +414,20 @@ fn shared_webp_container_preserves_payload_timing_loop_and_alpha() { let bytes = webp_file(1, 1, 7, true, [1, 2, 3, 4], &[(&f, 123)]).unwrap(); let anim = riff_chunk(&bytes, b"ANIM").unwrap(); assert_eq!(anim, &[3, 2, 1, 4, 7, 0]); + let frame = riff_chunk(&bytes, b"ANMF").unwrap(); + assert_eq!(&frame[12..15], &[123, 0, 0], "single-frame duration is retained on the wire"); + // The pinned image decoder treats one-frame WebP as a still image (delay 0). + // Check that contract separately, then use two distinct frames to exercise playback timing. let decoded = decode_webp(&bytes); + assert_eq!(decoded.frames, vec![(px.to_vec(), 0)]); + let second_px = [90, 80, 70, 160]; + let second = encode(Kind::Webp, None, &second_px, 1, 1).unwrap(); + let animation = webp_file(1, 1, 7, true, [1, 2, 3, 4], &[(&f, 123), (&second, 47)]).unwrap(); + let decoded = decode_webp(&animation); assert_eq!(decoded.size, (1, 1)); assert_eq!(decoded.loop_count, 7); assert!(decoded.alpha); - assert_eq!(decoded.frames, vec![(px.to_vec(), 123)]); + assert_eq!(decoded.frames, vec![(px.to_vec(), 123), (second_px.to_vec(), 47)]); assert!(webp_file(1, 1, 0, false, [0; 4], &[]).is_err()); assert!(webp_file(1, 1, 0, false, [0; 4], &[(&f, 1 << 24)]).is_err()); } From 516e818b1ca6637f9a95e45ddca2cfcf9c4a8068 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 16:40:31 +0530 Subject: [PATCH 101/570] feat(panels): a Scale lock that keeps width and height in proportion (#304) --- src/app.rs | 4 ++ src/panels.rs | 117 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+) diff --git a/src/app.rs b/src/app.rs index da2d4af3..f617ebae 100644 --- a/src/app.rs +++ b/src/app.rs @@ -451,6 +451,9 @@ pub struct App { pub width_sel: Option<(anicraft_engine::doc::ElementId, usize)>, /// Opens the Tools bar's fill swatch picker on the next frame (the `swatches` screenshot). pub open_fill_swatch: bool, + /// The Properties panel's Scale lock (#304; view state, not undoable): while on, editing + /// one Scale axis adjusts the other so the selection keeps its width:height proportion. + pub scale_lock: bool, /// The bone picked on the stage (ADR 0043; view state). pub bone_sel: Option, /// The Bind tool's options: Paint Weights, the brush, the focused point (ADR 0090). @@ -727,6 +730,7 @@ impl App { points: Vec::new(), width_sel: None, open_fill_swatch: false, + scale_lock: false, bone_sel: None, bind: crate::bind_tool::BindOptions::default(), warp_pin: None, diff --git a/src/panels.rs b/src/panels.rs index ea88621d..a64c920c 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -723,6 +723,31 @@ pub(crate) fn element_title(doc: &anicraft_engine::doc::Document, e: &anicraft_e if e.name.is_empty() { kind } else { tr!("{name} ({kind})", name = e.name, kind = kind) } } +/// The Scale lock's link (#304): with the lock on, editing one Scale axis (percent, as the +/// Properties panel shows it) adjusts the other so the selection keeps its width:height +/// proportion (multiplicative, not forced equal). `x_changed` says which axis was edited. +/// A degenerate old axis (near zero) cannot divide, so the other axis follows the new value +/// instead. Both are clamped to the DragValues' range, so a typed extreme cannot produce a +/// zero or negative scale. +fn linked_scale(old: (f32, f32), now: (f32, f32), x_changed: bool) -> (f32, f32) { + const MIN: f32 = 1.0; + const MAX: f32 = 10000.0; + let (ox, oy) = old; + let (mut nx, mut ny) = now; + if x_changed { + if ox.abs() <= 1e-6 { + ny = nx; + } else { + ny = oy * nx / ox; + } + } else if oy.abs() <= 1e-6 { + nx = ny; + } else { + nx = ox * ny / oy; + } + (nx.clamp(MIN, MAX), ny.clamp(MIN, MAX)) +} + /// "mixed" after a value that differs across the selection (the field shows the first one's). fn mixed(ui: &mut egui::Ui, differs: bool) { if differs { @@ -877,9 +902,21 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E }); } row(ui, tr!("Scale"), |ui| { + let (sx0, sy0) = (sx, sy); let a = ui.add(egui::DragValue::new(&mut sx).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale width")); let b = ui.add(egui::DragValue::new(&mut sy).suffix(" %").speed(0.5).range(1.0..=10000.0).max_decimals(1)).named(tr!("Scale height")); + // The Scale lock (#304): view state, off by default. On, editing one axis scales + // the other so the selection keeps its width:height proportion. + let locked = app.scale_lock; + let lock = crate::timeline::icon_button(ui, tr!("Lock scale"), Some(locked), if locked { Icon::Lock } else { Icon::Unlock }); + if lock.clicked() { + app.scale_lock = !locked; + } + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("scale_lock_geometry"), (a.rect, b.rect, lock.rect))); if a.changed() || b.changed() { + if locked { + (sx, sy) = linked_scale((sx0, sy0), (sx, sy), a.changed()); + } live(app, tr_noop!("Scale"), "element.set_transform", json!({"sx": sx / 100.0, "sy": sy / 100.0})); } mixed(ui, m.scale); @@ -2990,4 +3027,84 @@ mod tests { assert!(!stroke_only(t), "{t:?} fills"); } } + + /// #304: the Scale lock keeps the width:height proportion (multiplicative). + #[test] + fn linked_scale_keeps_the_proportion() { + // 100x50, X edited to 200: the height doubles too. + assert_eq!(linked_scale((100.0, 50.0), (200.0, 50.0), true), (200.0, 100.0)); + // 100x50, Y edited to 25: the width halves too. + assert_eq!(linked_scale((100.0, 50.0), (100.0, 25.0), false), (50.0, 25.0)); + // A degenerate old axis cannot divide: the other axis follows the new value. + assert_eq!(linked_scale((0.0, 50.0), (200.0, 50.0), true), (200.0, 200.0)); + assert_eq!(linked_scale((100.0, 0.0), (100.0, 25.0), false), (25.0, 25.0)); + // Clamped to the DragValues' range, so an extreme cannot make a zero/negative scale. + assert_eq!(linked_scale((100.0, 100.0), (20000.0, 100.0), true), (10000.0, 10000.0)); + assert_eq!(linked_scale((100.0, 200.0), (100.0, 0.01), false), (1.0, 1.0)); + assert_eq!(linked_scale((100.0, 100.0), (-5.0, 100.0), true), (1.0, 1.0)); + } + + /// #304, headless: the lock toggle flips view state (one click), and the row's edit path + /// scales both axes proportionally in a single undo step; with the lock off only the + /// edited axis changes. Typing a value into a DragValue is not driven here (that needs a + /// focused text field plus key events): the value link itself is covered by + /// `linked_scale_keeps_the_proportion`, and this test drives the same helper plus the + /// same `element.set_transform` the row sends. + #[test] + fn scale_lock_toggle_links_the_axes_in_one_undo_step() { + use egui::{Event, Modifiers, PointerButton, Pos2}; + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(std::path::PathBuf::from("unused.png"))); + app.run("draw.rect", json!({"x": 10, "y": 10, "w": 100, "h": 50, "fill": "#ff0000", "stroke": null})); + app.run("edit.select_all", json!({})); + assert!(!app.s.selection.is_empty()); + assert!(!app.scale_lock, "the lock defaults off"); + let screen = || egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(1600.0, 1400.0))), ..Default::default() }; + let frames = |ctx: &egui::Context, app: &mut App| { + for _ in 0..2 { + let mut out = ctx.run_ui(screen(), |ui| app.frame(ui)); + out.textures_delta.clear(); + } + }; + frames(&ctx, &mut app); + let (_, _, lock_rect) = ctx.data(|d| d.get_temp::<(Rect, Rect, Rect)>(egui::Id::new("scale_lock_geometry"))).expect("the Scale row drew"); + // Click the lock: view state only (no document change, no undo step). + let at = lock_rect.center(); + let press = |pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let steps = app.s.history_len(); + let mut out = ctx.run_ui(screen(), |ui| app.frame(ui)); + out.textures_delta.clear(); + let mut out = ctx.run_ui(egui::RawInput { events: vec![Event::PointerMoved(at), press(true)], ..screen() }, |ui| app.frame(ui)); + out.textures_delta.clear(); + let mut out = ctx.run_ui(egui::RawInput { events: vec![press(false)], ..screen() }, |ui| app.frame(ui)); + out.textures_delta.clear(); + frames(&ctx, &mut app); + assert!(app.scale_lock, "one click turns the lock on"); + assert_eq!(app.s.history_len(), steps, "toggling the lock is view state, not undoable"); + // The row's locked path: X 100 % -> 200 % keeps the 1:1 proportion. + let (sx, sy) = linked_scale((100.0, 100.0), (200.0, 100.0), true); + let steps = app.s.history_len(); + live(&mut app, tr_noop!("Scale"), "element.set_transform", json!({"sx": sx / 100.0, "sy": sy / 100.0})); + app.s.end_gesture(); + assert_eq!(app.s.history_len(), steps + 1, "one undo step for the live edit"); + let check = |app: &App| { + let els = app.s.selected_elements(); + let d = els.first().expect("selected").1.transform.decompose(); + (d.sx, d.sy) + }; + let (sx, sy) = check(&app); + assert!((sx - 2.0).abs() < 1e-4 && (sy - 2.0).abs() < 1e-4, "both axes doubled, got ({sx}, {sy})"); + app.s.undo().expect("undo"); + let (sx, sy) = check(&app); + assert!((sx - 1.0).abs() < 1e-4 && (sy - 1.0).abs() < 1e-4, "one undo restores both, got ({sx}, {sy})"); + // Lock off: the same row sends only the edited axis's change through. + app.scale_lock = false; + let steps = app.s.history_len(); + live(&mut app, tr_noop!("Scale"), "element.set_transform", json!({"sx": 3.0, "sy": 1.0})); + app.s.end_gesture(); + assert_eq!(app.s.history_len(), steps + 1); + let (sx, sy) = check(&app); + assert!((sx - 3.0).abs() < 1e-4 && (sy - 1.0).abs() < 1e-4, "only X changed, got ({sx}, {sy})"); + app.s.undo().expect("undo"); + } } From e677a3d5293665f3ed5803e5cff8e9fcb9d4f84f Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 16:40:31 +0530 Subject: [PATCH 102/570] feat(shell): an editable zoom field with a separate presets arrow (#43) --- src/app.rs | 4 ++ src/main.rs | 2 + src/panels.rs | 38 +++++++++++++++-- src/zoom_tests.rs | 101 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 src/zoom_tests.rs diff --git a/src/app.rs b/src/app.rs index da2d4af3..2c826f9d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -451,6 +451,9 @@ pub struct App { pub width_sel: Option<(anicraft_engine::doc::ElementId, usize)>, /// Opens the Tools bar's fill swatch picker on the next frame (the `swatches` screenshot). pub open_fill_swatch: bool, + /// The zoom edit-bar field's draft while it has the keyboard (view state, not undoable): + /// `None` shows the current zoom, `Some` is what is being typed. + pub zoom_text: Option, /// The bone picked on the stage (ADR 0043; view state). pub bone_sel: Option, /// The Bind tool's options: Paint Weights, the brush, the focused point (ADR 0090). @@ -727,6 +730,7 @@ impl App { points: Vec::new(), width_sel: None, open_fill_swatch: false, + zoom_text: None, bone_sel: None, bind: crate::bind_tool::BindOptions::default(), warp_pin: None, diff --git a/src/main.rs b/src/main.rs index 8c62d086..2cfae746 100644 --- a/src/main.rs +++ b/src/main.rs @@ -429,3 +429,5 @@ mod rulers_tests; mod retime_ui_tests; #[cfg(test)] mod tilt_ui_tests; +#[cfg(test)] +mod zoom_tests; diff --git a/src/panels.rs b/src/panels.rs index ea88621d..afae12fb 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -321,18 +321,48 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let z = app.view.zoom; let canvas = app.stage_cache.canvas; - egui::ComboBox::from_id_salt("zoom").width(84.0).selected_text(text(Type::Data, format!("{:>4.0}%", z * 100.0))).show_ui(ui, |ui| { + // The presets arrow alone opens the menu (Flash parity): clicking the text never does. + let arrow = ui.menu_button("▾", |ui| { if ui.selectable_label(false, tr!("Fit in window")).clicked() { + ui.close(); app.view.fit = true; } for pct in [25.0f32, 50.0, 100.0, 200.0, 400.0, 800.0] { if ui.selectable_label((z * 100.0 - pct).abs() < 0.5, text(Type::Data, format!("{pct:>4.0}%"))).clicked() { + ui.close(); app.zoom_about(canvas, canvas.center(), pct / 100.0); } } - }) - .response - .set_name(tr!("Zoom")); + }); + arrow.response.set_name(tr!("Zoom presets")); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("zoom_arrow"), arrow.response.rect)); + // The percentage itself is typed here: focus to type a value, Enter or focus loss applies it. + let was_editing = app.zoom_text.is_some(); + let mut value = app.zoom_text.take().unwrap_or_else(|| format!("{:>4.0}%", z * 100.0)); + let field = with_type(ui, Type::Data, |ui| ui.add(egui::TextEdit::singleline(&mut value).desired_width(56.0).char_limit(7)).named(tr!("Zoom"))); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("zoom_field"), field.rect)); + if !was_editing && field.gained_focus() { + // Type digits over digits, not over the percent sign. + value = format!("{:.0}", z * 100.0); + } + let enter = ui.input(|i| i.key_pressed(egui::Key::Enter)); + if field.lost_focus() || (enter && field.has_focus()) { + let typed = value.trim(); + let typed = typed.strip_suffix('%').unwrap_or(typed).trim(); + if let Ok(pct) = typed.parse::() + && pct.is_finite() + { + app.zoom_about(canvas, canvas.center(), pct.clamp(5.0, 6400.0) / 100.0); + } + app.zoom_text = None; + if enter { + ui.memory_mut(|m| m.surrender_focus(field.id)); + } + } else if field.has_focus() { + app.zoom_text = Some(value); + } else { + app.zoom_text = None; + } // Beside the zoom, as in Animate (#251): a toggle, on = the pasteboard is hidden. let clip = app.view.clip_to_stage; if crate::timeline::icon_button(ui, tr!("Clip content outside the stage"), Some(clip), Icon::ClipStage).clicked() { diff --git a/src/zoom_tests.rs b/src/zoom_tests.rs new file mode 100644 index 00000000..2ad72bab --- /dev/null +++ b/src/zoom_tests.rs @@ -0,0 +1,101 @@ +//! The zoom edit-bar field (#43): an editable percentage with a separate presets arrow, +//! driven frame by frame like the retime tests. + +use crate::app::App; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; + +fn frame(ctx: &egui::Context, app: &mut App, events: Vec, modifiers: Modifiers) { + let mut all = vec![Event::ModifiersChanged(modifiers)]; + all.extend(events); + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), events: all, ..Default::default() }; + ctx.run_ui(input, |ui| app.frame(ui)).textures_delta.clear(); +} + +fn settle(ctx: &egui::Context, app: &mut App) { + for _ in 0..3 { + frame(ctx, app, Vec::new(), Modifiers::NONE); + } +} + +fn button(pos: Pos2, pressed: bool, modifiers: Modifiers) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers } +} + +fn click(ctx: &egui::Context, app: &mut App, at: Pos2, modifiers: Modifiers) { + frame(ctx, app, vec![Event::PointerMoved(at)], modifiers); + frame(ctx, app, vec![button(at, true, modifiers)], modifiers); + frame(ctx, app, vec![button(at, false, modifiers)], modifiers); + settle(ctx, app); +} + +fn key(ctx: &egui::Context, app: &mut App, key: egui::Key, modifiers: Modifiers) { + frame(ctx, app, vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], modifiers); + frame(ctx, app, vec![Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }], modifiers); + settle(ctx, app); +} + +fn type_text(ctx: &egui::Context, app: &mut App, s: &str) { + frame(ctx, app, vec![Event::Text(s.to_owned())], Modifiers::NONE); + settle(ctx, app); +} + +fn select_all(ctx: &egui::Context, app: &mut App) { + frame(ctx, app, vec![Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::CTRL }], Modifiers::CTRL); + frame(ctx, app, vec![Event::Key { key: egui::Key::A, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::CTRL }], Modifiers::CTRL); + settle(ctx, app); +} + +fn clear_field(ctx: &egui::Context, app: &mut App) { + select_all(ctx, app); + // Selection or not, this leaves the field empty (the seed is 3-4 digits). + for _ in 0..8 { + frame(ctx, app, vec![Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + frame(ctx, app, vec![Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + } + settle(ctx, app); +} + +fn zoom_rects(ctx: &egui::Context) -> (Rect, Rect) { + let field = ctx.data(|d| d.get_temp::(egui::Id::new("zoom_field"))).expect("the zoom field drew"); + let arrow = ctx.data(|d| d.get_temp::(egui::Id::new("zoom_arrow"))).expect("the zoom arrow drew"); + (field, arrow) +} + +#[test] +fn zoom_field_types_a_value_and_rejects_garbage() { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png"))); + app.view.fit = false; + app.view.zoom = 1.0; + settle(&ctx, &mut app); + app.view.fit = false; + app.view.zoom = 1.0; + settle(&ctx, &mut app); + + // Clicking the text focuses it without changing the zoom (no presets menu from the text). + let (field, arrow) = zoom_rects(&ctx); + let before = app.view.zoom; + click(&ctx, &mut app, field.center(), Modifiers::NONE); + assert!((app.view.zoom - before).abs() < 1e-6, "focusing the field leaves zoom alone"); + // Clicking the arrow alone does not change the zoom either (it only opens the presets). + click(&ctx, &mut app, arrow.center(), Modifiers::NONE); + assert!((app.view.zoom - before).abs() < 1e-6, "the presets arrow alone zooms nothing"); + key(&ctx, &mut app, egui::Key::Escape, Modifiers::NONE); + + // Type a custom value and press Enter: the stage zooms there. + let (field, _) = zoom_rects(&ctx); + click(&ctx, &mut app, field.center(), Modifiers::NONE); + clear_field(&ctx, &mut app); + type_text(&ctx, &mut app, "150"); + key(&ctx, &mut app, egui::Key::Enter, Modifiers::NONE); + assert!((app.view.zoom - 1.5).abs() < 0.01, "typed 150% zooms to 1.5, got {}", app.view.zoom); + + // Garbage reverts to the current zoom without changing anything. + let (field, _) = zoom_rects(&ctx); + click(&ctx, &mut app, field.center(), Modifiers::NONE); + clear_field(&ctx, &mut app); + type_text(&ctx, &mut app, "abc"); + key(&ctx, &mut app, egui::Key::Enter, Modifiers::NONE); + assert!((app.view.zoom - 1.5).abs() < 0.01, "invalid text keeps zoom at 1.5, got {}", app.view.zoom); +} From 4b9608fb1f03b23f5dcd2b90120c0d4614594906 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 16:40:31 +0530 Subject: [PATCH 103/570] fix(timeline): stop the ruler playhead at the last material frame (#352) --- src/timeline.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/src/timeline.rs b/src/timeline.rs index 37ed1f9b..6343b733 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -36,6 +36,14 @@ fn start_pad(cell_w: f32, extra: f32) -> f32 { fn frame_center(cell_left: f32, cell_w: f32) -> f32 { (cell_left + cell_w * 0.5).round() + 0.5 } + +/// Where the playhead goes when the ruler is clicked or dragged: the pointed-to frame, +/// stopped at the last frame that has material (#352), so the playhead never leaves the +/// edited timeline. Cell clicks, keys and `timeline.goto` keep their own behaviour. +fn playhead_target(frame: u32, frames: u32) -> u32 { + frame.min(frames.saturating_sub(1)) +} + const FOOTER_H: f32 = 38.0; /// The bottom bar's frame zoom and Frame View at its right end: the 56 pt slider, its field, the /// menu button and spacing. @@ -529,7 +537,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { && app.onion_ui.drag.is_none() && let Some(p) = ruler_resp.interact_pointer_pos() { app.playing = false; - app.run("timeline.goto", json!({"frame": frame_at(p.x)})); + app.run("timeline.goto", json!({"frame": playhead_target(frame_at(p.x), app.s.frame_count())})); } // The onion menu on a right-click, as the markers live here (ADR 0047). ruler_resp.context_menu(|ui| crate::onion::menu(app, ui)); @@ -1873,4 +1881,63 @@ mod tests { // A deleted layer invalidates the selection. assert!(FrameSel { anchor: (LayerId(9), 0), head: (LayerId(1), 0) }.layers(&ls).is_empty()); } + + #[test] + fn the_ruler_playhead_stops_at_the_last_frame_with_material() { + use egui::{Event, Modifiers, PointerButton, Pos2}; + fn frame(ctx: &egui::Context, app: &mut App, events: Vec, modifiers: Modifiers) { + let mut all = vec![Event::ModifiersChanged(modifiers)]; + all.extend(events); + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), events: all, ..Default::default() }; + ctx.run_ui(input, |ui| app.frame(ui)).textures_delta.clear(); + } + fn settle(ctx: &egui::Context, app: &mut App) { + for _ in 0..3 { + frame(ctx, app, Vec::new(), Modifiers::NONE); + } + } + fn button(pos: Pos2, pressed: bool, modifiers: Modifiers) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers } + } + fn drag(ctx: &egui::Context, app: &mut App, from: Pos2, to: Pos2, modifiers: Modifiers) { + frame(ctx, app, vec![Event::PointerMoved(from)], modifiers); + frame(ctx, app, vec![button(from, true, modifiers)], modifiers); + for i in 1..=10 { + frame(ctx, app, vec![Event::PointerMoved(from + (to - from) * (i as f32 / 10.0))], modifiers); + } + frame(ctx, app, vec![button(to, false, modifiers)], modifiers); + settle(ctx, app); + } + fn click(ctx: &egui::Context, app: &mut App, at: Pos2, modifiers: Modifiers) { + frame(ctx, app, vec![Event::PointerMoved(at)], modifiers); + frame(ctx, app, vec![button(at, true, modifiers)], modifiers); + frame(ctx, app, vec![button(at, false, modifiers)], modifiers); + settle(ctx, app); + } + assert_eq!(playhead_target(26, 8), 7); + assert_eq!(playhead_target(3, 8), 3); + assert_eq!(playhead_target(0, 0), 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.show_panel(crate::dock::Panel::Timeline); + let layer = app.s.layer; + app.run("timeline.insert_frame", json!({"layer": layer.0, "frame": 0, "count": 7})); + app.s.set_frame(0); + settle(&ctx, &mut app); + assert_eq!(app.s.frame_count(), 8); + // Where the active row's frames are drawn, as the timeline drew them. + let row = ctx.data(|d| d.get_temp::<(egui::Rect, f32, f32, f32)>(egui::Id::new("tl_geometry"))); + let Some((cells, x0, cell_w, scroll)) = row else { panic!("the timeline drew") }; + // The ruler sits directly above the cells; the frame's column is its centre. + let y = cells.top() - RULER_H / 2.0; + let x = |f: u32| x0 + (f as f32 - scroll) * cell_w + cell_w * 0.5; + // Dragging past the material stops at the last frame that has it (#352). + drag(&ctx, &mut app, pos2(x(2), y), pos2(x(26), y), Modifiers::NONE); + assert_eq!(app.s.frame, 7); + // A click past the end clamps too, while a drag inside still moves freely. + drag(&ctx, &mut app, pos2(x(7), y), pos2(x(3), y), Modifiers::NONE); + assert_eq!(app.s.frame, 3); + click(&ctx, &mut app, pos2(x(12), y), Modifiers::NONE); + assert_eq!(app.s.frame, 7); + } } From 12148ff77fb9d5c1f1ba41de4450b323873312ba Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:57:11 +0100 Subject: [PATCH 104/570] docs(status): remove implemented features from the missing list (M8) --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index eb6390d7..6e63fcf4 100644 --- a/README.md +++ b/README.md @@ -195,9 +195,8 @@ The details, including the server entry for other MCP clients, are in [`docs/mcp [**docs/roadmap.md**](docs/roadmap.md) has the honest status by dimension, milestones M0–M8 and what's next. -**What's missing:** audio layers, ActionScript beyond the timeline subset (frame scripts -are kept, and those that control the timeline run; ADR 0013), motion tweens from XFL, a GPU renderer, and macOS and Linux CI runners -(AniCraft is verified on Windows so far). +**What's missing:** ActionScript beyond the timeline subset (frame scripts are kept, and those +that control the timeline run; ADR 0013), and motion tweens from XFL. **Workspace:** strict downward-only layering, checked by `cargo test`: From 163721d1a3ac1eb0a0d584d5173275e2cbc075bb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:28:02 -0500 Subject: [PATCH 105/570] Use shared Base64 encoding for bitmap document payloads --- Cargo.lock | 42 ++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + crates/doc/Cargo.toml | 1 + crates/doc/src/bitmap.rs | 30 +++++++++++++++------------- 4 files changed, 61 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7c7d100c..8f8878b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -296,6 +296,7 @@ dependencies = [ "anicraft-audio", "anicraft-geom", "craft-image-codecs", + "craft-mime", "serde", "serde_json", ] @@ -1123,6 +1124,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "core_maths" version = "0.1.1" @@ -1215,6 +1222,11 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" + [[package]] name = "craft-gif" version = "0.1.0" @@ -1274,6 +1286,16 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "chrono", + "craft-codepage", + "encoding_rs", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1650,6 +1672,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -2791,6 +2827,12 @@ dependencies = [ "target-features", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" diff --git a/Cargo.toml b/Cargo.toml index b278d39d..e8e76a85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ anicraft-audio = { path = "crates/audio" } anicraft-gpu = { path = "crates/gpu" } anicraft-guide = { path = "crates/guide" } craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["decode", "pcm-encode"] } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 1ed9359d..1f75a22f 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true repository.workspace = true [dependencies] +craft-mime.workspace = true anicraft-geom.workspace = true serde = { workspace = true, features = ["rc"] } # Bitmaps are decoded and encoded via craft-image-codecs. diff --git a/crates/doc/src/bitmap.rs b/crates/doc/src/bitmap.rs index 7dc24966..47e6e65b 100644 --- a/crates/doc/src/bitmap.rs +++ b/crates/doc/src/bitmap.rs @@ -167,19 +167,7 @@ pub(crate) mod base64_bytes { const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; pub fn encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for chunk in data.chunks(3) { - let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)]; - let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); - for (i, shift) in [18, 12, 6, 0].into_iter().enumerate() { - if i <= chunk.len() { - out.push(ALPHABET[((n >> shift) & 63) as usize] as char); - } else { - out.push('='); - } - } - } - out + craft_mime::base64::STANDARD.encode(data) } pub fn decode(text: &str) -> Option> { @@ -228,6 +216,22 @@ mod tests { encode_png(w, h, rgba).unwrap() } + #[test] + fn shared_base64_encoder_preserves_all_byte_remainders() { + for (input, expected) in + [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] + { + assert_eq!(base64_bytes::encode(input.as_bytes()), expected); + } + let all: Vec = (0..=255).cycle().take(513).collect(); + for len in 0..=all.len() { + let encoded = base64_bytes::encode(&all[..len]); + assert_eq!(encoded.len(), len.div_ceil(3) * 4); + assert_eq!(encoded.bytes().rev().take_while(|b| *b == b'=').count(), (3 - len % 3) % 3); + assert_eq!(base64_bytes::decode(&encoded).as_deref(), Some(&all[..len])); + } + } + #[test] fn base64_round_trips() { for data in [&b""[..], b"f", b"fo", b"foo", b"foob", b"fooba", b"foobar", &[0, 255, 128, 7, 9]] { From caa4e7376393bda9c8ba32bf7343704be9e505d9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:30:58 -0500 Subject: [PATCH 106/570] Specify shared MIME version for dependency policy --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index e8e76a85..1ba2d48a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ anicraft-audio = { path = "crates/audio" } anicraft-gpu = { path = "crates/gpu" } anicraft-guide = { path = "crates/guide" } craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["decode", "pcm-encode"] } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } From 20cc73ad90bb9d2d74f1e8e3f568529a9f6ccdcf Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:32:51 +0100 Subject: [PATCH 107/570] docs(cli): document direct Animate inputs (M8) Updated documentation to clarify file types accepted by subcommands and conversion process. --- docs/guide/working-headless.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/guide/working-headless.md b/docs/guide/working-headless.md index 3f6ce06f..032d71d6 100644 --- a/docs/guide/working-headless.md +++ b/docs/guide/working-headless.md @@ -23,9 +23,9 @@ prints the version. Two rules hold everywhere: -* Each subcommand takes a document path, or `--sample` for the built-in sample animation. The - positional document must be a `.anicraft` file (to work on an Animate file, see - [Converting Animate files](#converting-animate-files)). +* Subcommands that open a document accept a `.anicraft` file, an Animate `.fla` or `.xfl` + file, an XFL folder, or `--sample` for the built-in sample animation. See + [Converting Animate files](#converting-animate-files) to save an import as `.anicraft`. * **Frame flags on the command line are 1-based**, as on the timeline: `--frame 1` is the first frame. Frame numbers inside JSON params are 0-based, as everywhere in the engine. @@ -159,8 +159,13 @@ Renders are deterministic: the same document and flags give the same pixels on e ### Converting Animate files -The positional document must be a `.anicraft` file, but the `file.open` command reads `.fla`, -`.xfl` and XFL folders. Start from the sample, open the Animate file over it, and save: +Pass a `.fla`, `.xfl` file or XFL folder directly to any subcommand that opens a document: + +```sh +anicraft-cli info intro.fla +``` + +To save an import as `.anicraft` and print its import report, use `file.open` and `--save`: ```sh anicraft-cli exec --sample file.open '{"path":"intro.fla"}' --save intro.anicraft From 4c7aa9c3c318edf603bd08f07d25553fe1be1350 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:33:42 -0500 Subject: [PATCH 108/570] Use shared bounded APNG container assembly --- Cargo.lock | 78 ++++++++++++++++++++++++++++++--- Cargo.toml | 2 + crates/engine/Cargo.toml | 1 + crates/engine/src/anim.rs | 69 ++++++++++------------------- crates/engine/src/anim_tests.rs | 64 +++++++++++++++++++++++++++ 5 files changed, 162 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7c7d100c..73189c40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -295,7 +295,7 @@ dependencies = [ "anicraft-actions", "anicraft-audio", "anicraft-geom", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", "serde", "serde_json", ] @@ -313,7 +313,8 @@ dependencies = [ "anicraft-xfl", "craft-anicraft-format", "craft-gif", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", "craft-webp", "miniz_oxide 0.8.9", "rayon", @@ -375,7 +376,7 @@ dependencies = [ "anicraft-doc", "anicraft-geom", "boa_engine", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", "rayon", "serde_json", "thiserror 2.0.21", @@ -410,7 +411,7 @@ dependencies = [ "anicraft-geom", "anicraft-text", "anicraft-xml", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", "craft-xfl", "miniz_oxide 0.8.9", "thiserror 2.0.21", @@ -1223,13 +1224,38 @@ dependencies = [ "gif", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + [[package]] name = "craft-image-codecs" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" dependencies = [ - "craft-jpeg", - "craft-metadata", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", "exr", "flate2", "half", @@ -1246,6 +1272,14 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-jpeg" version = "0.1.0" @@ -1262,6 +1296,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "brotli-decompressor", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -1269,11 +1315,20 @@ source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9b dependencies = [ "brotli-decompressor", "chrono", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", "quick-xml 0.41.0", "serde", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -2278,6 +2333,15 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hayro-jpeg2000" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] + [[package]] name = "hermit-abi" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index b278d39d..ea3130c9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,8 @@ anicraft-guide = { path = "crates/guide" } craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["decode", "pcm-encode"] } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +# Isolate the already-merged APNG container from the existing raster-codec pin. +craft-apng-container = { package = "craft-image-codecs", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "55b1d7f3c598b600a130ae63f4a40334a230ae7b", default-features = false } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "0c144b7d983899d4b5b281046dd03a8b1ab35fbb" } craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 16ce2720..b06903ea 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -23,6 +23,7 @@ rayon.workspace = true web-time.workspace = true craft-gif.workspace = true craft-image-codecs.workspace = true +craft-apng-container.workspace = true craft-webp.workspace = true regex.workspace = true diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs index 0c4af63a..60d0cce5 100644 --- a/crates/engine/src/anim.rs +++ b/crates/engine/src/anim.rs @@ -274,52 +274,31 @@ fn still(kind: Kind) -> Result { // ----- the files --------------------------------------------------------------------------- -fn png_chunk(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { - let len = u32::try_from(data.len()).ok().filter(|l| *l < 1 << 31).ok_or_else(|| EngineError::Format("an animated PNG frame is too large".into()))?; - out.extend_from_slice(&len.to_be_bytes()); - let from = out.len(); - out.extend_from_slice(id); - out.extend_from_slice(data); - let crc = anicraft_xfl::zip::crc32(out.get(from..).unwrap_or(&[])); - out.extend_from_slice(&crc.to_be_bytes()); - Ok(()) -} - -/// The APNG file: frames with their delays (the first frame is the default image). +/// The shared container owns PNG chunks, CRCs and APNG sequence validation. +/// Frame selection, compression and exact rational timing remain AniCraft policy. fn apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result> { - let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); - let mut ihdr = Vec::with_capacity(13); - ihdr.extend_from_slice(&w.to_be_bytes()); - ihdr.extend_from_slice(&h.to_be_bytes()); - ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA, deflate, adaptive filters, no interlace - png_chunk(&mut out, b"IHDR", &ihdr)?; - let count = u32::try_from(frames.len()).map_err(|_| EngineError::Format("too many frames".into()))?; - let mut actl = count.to_be_bytes().to_vec(); - actl.extend_from_slice(&plays.to_be_bytes()); - png_chunk(&mut out, b"acTL", &actl)?; - let mut seq = 0u32; - for (k, (f, (num, den))) in frames.iter().enumerate() { - let mut fctl = Vec::with_capacity(26); - for v in [seq, f.rect.w, f.rect.h, f.rect.x, f.rect.y] { - fctl.extend_from_slice(&v.to_be_bytes()); - } - fctl.extend_from_slice(&num.to_be_bytes()); - fctl.extend_from_slice(&den.to_be_bytes()); - fctl.extend_from_slice(&[0, u8::from(f.over)]); // dispose: none; blend: source or over - png_chunk(&mut out, b"fcTL", &fctl)?; - seq += 1; - if k == 0 { - png_chunk(&mut out, b"IDAT", &f.data)?; - } else { - let mut fdat = Vec::with_capacity(f.data.len() + 4); - fdat.extend_from_slice(&seq.to_be_bytes()); - fdat.extend_from_slice(&f.data); - png_chunk(&mut out, b"fdAT", &fdat)?; - seq += 1; - } - } - png_chunk(&mut out, b"IEND", &[])?; - Ok(out) + use craft_apng_container::apng::Frame; + // Bound the output by the already-compressed payloads plus exact framing. + // Pixel/frame budgets are enforced before rendering, unchanged by this adapter. + let budget = frames + .iter() + .enumerate() + .try_fold(65usize, |size, (index, (f, _))| size.checked_add(50 + if index == 0 { 0 } else { 4 }).and_then(|n| n.checked_add(f.data.len()))) + .ok_or_else(|| EngineError::Format("animated PNG output size overflow".into()))?; + let frames: Vec<_> = frames + .iter() + .map(|(f, (num, den))| Frame { + width: f.rect.w, + height: f.rect.h, + x: f.rect.x, + y: f.rect.y, + delay_num: *num, + delay_den: *den, + over: f.over, + data: &f.data, + }) + .collect(); + craft_apng_container::apng::encode(w, h, plays, &frames, budget).map_err(|e| EngineError::Format(e.to_string())) } /// The animated WebP container is shared; frame selection, delta rectangles and timing diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs index f5730fbf..6be0a5f9 100644 --- a/crates/engine/src/anim_tests.rs +++ b/crates/engine/src/anim_tests.rs @@ -431,3 +431,67 @@ fn shared_webp_container_preserves_payload_timing_loop_and_alpha() { assert!(webp_file(1, 1, 0, false, [0; 4], &[]).is_err()); assert!(webp_file(1, 1, 0, false, [0; 4], &[(&f, 1 << 24)]).is_err()); } + +// Frozen pre-cutover assembly oracle (original APNG implementation by Tanish Manku). +fn png_chunk(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { + let len = + u32::try_from(data.len()).ok().filter(|l| *l < 1 << 31).ok_or_else(|| EngineError::Format("an animated PNG frame is too large".into()))?; + out.extend_from_slice(&len.to_be_bytes()); + let from = out.len(); + out.extend_from_slice(id); + out.extend_from_slice(data); + let crc = anicraft_xfl::zip::crc32(out.get(from..).unwrap_or(&[])); + out.extend_from_slice(&crc.to_be_bytes()); + Ok(()) +} + +/// The APNG file: frames with their delays (the first frame is the default image). +fn legacy_apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result> { + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = Vec::with_capacity(13); + ihdr.extend_from_slice(&w.to_be_bytes()); + ihdr.extend_from_slice(&h.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA, deflate, adaptive filters, no interlace + png_chunk(&mut out, b"IHDR", &ihdr)?; + let count = u32::try_from(frames.len()).map_err(|_| EngineError::Format("too many frames".into()))?; + let mut actl = count.to_be_bytes().to_vec(); + actl.extend_from_slice(&plays.to_be_bytes()); + png_chunk(&mut out, b"acTL", &actl)?; + let mut seq = 0u32; + for (k, (f, (num, den))) in frames.iter().enumerate() { + let mut fctl = Vec::with_capacity(26); + for v in [seq, f.rect.w, f.rect.h, f.rect.x, f.rect.y] { + fctl.extend_from_slice(&v.to_be_bytes()); + } + fctl.extend_from_slice(&num.to_be_bytes()); + fctl.extend_from_slice(&den.to_be_bytes()); + fctl.extend_from_slice(&[0, u8::from(f.over)]); // dispose: none; blend: source or over + png_chunk(&mut out, b"fcTL", &fctl)?; + seq += 1; + if k == 0 { + png_chunk(&mut out, b"IDAT", &f.data)?; + } else { + let mut fdat = Vec::with_capacity(f.data.len() + 4); + fdat.extend_from_slice(&seq.to_be_bytes()); + fdat.extend_from_slice(&f.data); + png_chunk(&mut out, b"fdAT", &fdat)?; + seq += 1; + } + } + png_chunk(&mut out, b"IEND", &[])?; + Ok(out) +} + +#[test] +fn shared_apng_container_preserves_exact_wire_bytes() { + let first = Encoded { rect: Rect { x: 0, y: 0, w: 3, h: 2 }, over: false, data: vec![1, 2, 3] }; + let second = Encoded { rect: Rect { x: 2, y: 1, w: 1, h: 1 }, over: true, data: vec![4, 5] }; + for plays in [0, 1, 7] { + for delay in [(0, 0), (200, 2997), (u16::MAX, u16::MAX)] { + let frames = [(&first, delay), (&second, (1, 100)), (&second, (0, 1))]; + assert_eq!(apng_file(3, 2, plays, &frames).unwrap(), legacy_apng_file(3, 2, plays, &frames).unwrap()); + } + } + assert!(apng_file(3, 2, 0, &[]).is_err()); + assert!(apng_file(3, 2, 0, &[(&second, (1, 1))]).is_err()); +} From 86cad3be9e8391075742297ee2622d077df67c62 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:40:12 +0100 Subject: [PATCH 109/570] docs(web): list Web Audio among supported browser behavior (M8) --- docs/web.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/web.md b/docs/web.md index d2740da2..51f7978c 100644 --- a/docs/web.md +++ b/docs/web.md @@ -65,13 +65,15 @@ autosave) work. On another host, serve over HTTPS for the same reason. Compressi shows as missing (the browser never gives its path back): open it again with Open. * **Leaving the page** with unsaved changes asks first. * **Shortcuts** are the desktop ones; on a Mac they use ⌘. +* **Sound playback** uses Web Audio (ADR 0095): playback, scrubbing, previews and Test Movie, + with the playhead following the sound. The browser opens sound on the first play (a click). + Where a browser has no Web Audio, playback is silent with a notice. ## Not in the web editor yet | Missing | Why, and what to do meanwhile | |---|---| | Video export | It runs ffmpeg, which a page can't start. The menu item is dimmed; export a GIF, PNG sequence or HTML page. | -| Sound playback | Through Web Audio (ADR 0095), as on the desktop: playback, scrubbing, previews and Test Movie, the playhead following the sound. The browser opens sound on the first play (a click). Where a browser has no Web Audio, playback is silent with a notice. | | GPU stage | The stage draws on the CPU, on one thread. The GPU renderer builds for the web but isn't wired to WebGPU yet. | | Installing plug-ins | Plug-ins live in a folder on the computer. Use the desktop app. | | Fonts on your computer | A page can't see them. Text uses the bundled faces. | From fadc1ad4e34e7afbec571f94a62405e3aa13418d Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:41:57 +0100 Subject: [PATCH 110/570] docs(guide): remove stale browser sound limitation (M8) --- docs/guide/images-and-sound.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/guide/images-and-sound.md b/docs/guide/images-and-sound.md index a106015a..478021f0 100644 --- a/docs/guide/images-and-sound.md +++ b/docs/guide/images-and-sound.md @@ -242,4 +242,3 @@ Lottie animations carry no sound. See [Exporting and Publish](exporting-and-publ * Picking a colour from a bitmap's pixels with the Eyedropper. * Panning beyond what the envelope does. -* Sound playback in the web version. From dbdd97fe11847d2d9e297204bbf8530d3d3a4999 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:43:44 +0100 Subject: [PATCH 111/570] docs(guide): describe first-play browser audio (M8) --- docs/guide/getting-started.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index ac8d5030..ac915c9a 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -49,8 +49,9 @@ shows it in an installed copy) into the portable copy's `data` folder. **Preferences › About** shows which kind of copy you are running and every folder it uses, each with an **Open** button. -There is also a web version that runs in a modern browser. It can't play sound, export video -or install plug-ins yet, and menu items that can't work there are dimmed and say why. +There is also a web version that runs in a modern browser. Sound starts on your first play +through Web Audio. It can't export video or install plug-ins yet, and menu items that can't +work there are dimmed and say why. To get newer versions later, choose **Help › Check for Updates…**. From 9193b581f2080058c88cdc42a0a00805e2c2dca6 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:45:35 +0100 Subject: [PATCH 112/570] docs(cli): list the light theme in startup help (M8) --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 8c62d086..fd0aa201 100644 --- a/src/main.rs +++ b/src/main.rs @@ -266,7 +266,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|light|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ From 66fd4d952bb597f61c797356f43af8e197553560 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:06:16 +0100 Subject: [PATCH 113/570] fix(geom): reject non-finite affine inverses (M1) --- crates/geom/src/affine.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/geom/src/affine.rs b/crates/geom/src/affine.rs index c64bfebd..5dce8e96 100644 --- a/crates/geom/src/affine.rs +++ b/crates/geom/src/affine.rs @@ -67,7 +67,7 @@ impl Affine { self.m[0] * self.m[3] - self.m[1] * self.m[2] } - /// Inverse, or `None` for a singular (or non-finite) matrix. + /// Inverse, or `None` for a singular matrix or non-finite input or result. pub fn inverse(&self) -> Option { let det = self.determinant(); if !det.is_finite() || det.abs() < 1e-12 { @@ -79,7 +79,9 @@ impl Affine { let ib = -b * inv; let ic = -c * inv; let id = a * inv; - Some(Affine { m: [ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)] }) + let inverse = Affine { m: [ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)] }; + // A finite determinant does not cover translation or overflow in the inverse. + inverse.is_finite().then_some(inverse) } pub fn translation(&self) -> Vec2 { @@ -179,6 +181,24 @@ mod tests { assert!(Affine::scale(0.0, 1.0).inverse().is_none()); } + #[test] + fn inverse_rejects_non_finite_coefficients() { + for value in [f32::INFINITY, f32::NEG_INFINITY, f32::NAN] { + for index in 0..6 { + let mut m = Affine::IDENTITY; + m.m[index] = value; + assert!(m.inverse().is_none(), "{m:?}"); + } + } + } + + #[test] + fn inverse_rejects_overflow_from_finite_coefficients() { + let m = Affine { m: [0.5, 0.0, 0.0, 0.5, f32::MAX, 0.0] }; + assert!(m.is_finite()); + assert!(m.inverse().is_none()); + } + #[test] fn decompose_compose_identity() { for (rot, sx, sy, skew) in [(0.3, 2.0, 1.5, 0.0), (-2.5, 0.5, 3.0, 0.2), (1.0, 1.0, -1.0, 0.0)] { From 76954859c3741df9c1603b20221c7d67f851e2fe Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:21:41 +0100 Subject: [PATCH 114/570] docs(plugins): describe all element kinds and null bounds (M6) Align the existing elements response schema with camera/group kinds and nullable evaluated bounds. --- docs/plugins.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/plugins.md b/docs/plugins.md index 353dd626..8dd9c320 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -115,9 +115,11 @@ first). A refused or failed request is an answer, not a trap: the plug-in decide |---|---| | `{"op":"command","id":"draw.star","params":{…}}` | The command's result (see `anicraft-cli commands` for ids and params). | | `{"op":"document"}` | `{abi, stage: {width, height, fps, background}, scene, scenes, frame, frames, layer, layers: [{id, name, kind, visible, locked, parent}], selection: [ids]}` (the selection on every layer, ADR 0044) | -| `{"op":"elements","selected"?:bool,"paths"?:bool}` | The elements on the active layer at the playhead (tweens applied): `{layer, frame, elements: [{id, kind: shape\|symbol\|text, name, selected, transform: [a,b,c,d,e,f], bounds: [x,y,w,h] (stage), alpha, fill, stroke, path (SVG path data, local space, with "paths")}]}` (at most 10,000). | +| `{"op":"elements","selected"?:bool,"paths"?:bool}` | The elements on the active layer at the playhead (tweens applied): `{layer, frame, elements: [{id, kind: shape\|symbol\|text\|camera\|group, name, selected, transform: [a,b,c,d,e,f], bounds: [x,y,w,h]\|null (stage), alpha, fill, stroke, path (SVG path data, local space, with "paths")}]}` (at most 10,000). | | `{"op":"log","message":"…"}` | `null`; the line goes into the run's report, and the last one explains a failure. | +`bounds` is `null` for cameras and for any element whose evaluated bounds are empty. + Unknown ops answer `{"ok":false,"error":"unknown op '…'"}`, so a plug-in can feature-detect. New ops and plug-in kinds are added without changing version 1; the version changes only when an existing contract changes. From 95a2f8a5fcc7c4dfb16155a43343827169469a3e Mon Sep 17 00:00:00 2001 From: Untoldent Date: Sun, 15 Nov 2026 14:24:38 -0500 Subject: [PATCH 115/570] Fix scene breadcrumb navigation and improve scene selector UX --- crates/engine/src/cmds_scene.rs | 2 +- docs/guide/coming-from-animate.md | 2 +- docs/guide/reference/commands.md | 2 +- docs/guide/timeline.md | 2 +- docs/guide/workspace.md | 2 +- src/panels.rs | 256 +++++++++++++++++++++++++++--- 6 files changed, 239 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmds_scene.rs b/crates/engine/src/cmds_scene.rs index b619c6c8..4afdbceb 100644 --- a/crates/engine/src/cmds_scene.rs +++ b/crates/engine/src/cmds_scene.rs @@ -10,7 +10,7 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("scene.new", "Scene", "Insert", None, "{name?}", true, new_scene as crate::RunFn), + c("scene.new", "New Scene", "Insert", None, "{name?}", true, new_scene as crate::RunFn), c("scene.duplicate", "Duplicate Scene", "Modify/Scene", None, "{scene?}", true, duplicate_scene), c("scene.rename", "Rename Scene", "Modify/Scene", None, "{name, scene?}", true, rename_scene), c("scene.delete", "Delete Scene", "Modify/Scene", None, "{scene?}", true, delete_scene), diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 0134c835..8b68ed24 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -30,7 +30,7 @@ Animator and Designer, plus your own saved workspaces and Reset. | History | The History panel on the right. | | Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, overflow and Linear RGB, like the Color panel. **Window › Swatches** keeps the document's colours and gradients (click applies to the active stroke or fill, drag to reorder, import and export swatch files and GIMP `.gpl` palettes; not Adobe `.aco`/`.ase`/`.clr`). | | Transform and Info | Position, scale and rotation rows in Properties, and the Free Transform tool. | -| Scene | The scene menu at the top left of the stage, **Insert › Scene** and **Modify › Scene**. | +| Scene | The scene menu at the top left of the stage, **Insert › New Scene** and **Modify › Scene**. | | Find and Replace | **Edit › Find and Replace** (**Ctrl+F**). | | Publish Settings | **File › Publish Settings…** (**Ctrl+Shift+F12**). | diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 63035678..d96a588f 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -143,7 +143,7 @@ This page is generated from the command registry, so it always matches the versi Parameters: `{layer?}` - **Add Camera** `camera.add` · Insert › Timeline · changes the document Parameters: `{} (a camera layer on top of the scene, at rest: it sees the stage as it is; nothing happens if there is one)` -- **Scene** `scene.new` · changes the document +- **New Scene** `scene.new` · changes the document Parameters: `{name?}` ## Modify diff --git a/docs/guide/timeline.md b/docs/guide/timeline.md index a88e877a..578a854e 100644 --- a/docs/guide/timeline.md +++ b/docs/guide/timeline.md @@ -269,7 +269,7 @@ tween's object on several frames, and dragging the shared pivot. A movie can have several scenes, each with its own timeline, played one after another. -* Add one with **Insert › Scene**. +* Add one with **Insert › New Scene**. * Switch scenes from the scene menu at the top left of the stage, or with **Shift+Page Up** and **Shift+Page Down**. * Duplicate, rename, reorder and delete them under **Modify › Scene**. Deleting a scene with diff --git a/docs/guide/workspace.md b/docs/guide/workspace.md index dca9e266..907f0ba0 100644 --- a/docs/guide/workspace.md +++ b/docs/guide/workspace.md @@ -242,7 +242,7 @@ exactly as the movie will frame it. While the preview is on you can't edit artwo A movie can be split into scenes that play one after another. Each scene has its own timeline. Use the scene menu at the left of the edit bar to switch scenes and to manage them: -* **Insert › Scene** adds a new scene. +* **Insert › New Scene** adds a new scene. * **Modify › Scene** has **Duplicate Scene**, **Rename Scene**, **Delete Scene**, **Move Scene Earlier** and **Move Scene Later**. * **Control › Previous Scene** (**Shift+Page Up**) and **Control › Next Scene** diff --git a/src/panels.rs b/src/panels.rs index ea88621d..cae54df0 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -259,35 +259,98 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { ui.horizontal_centered(|ui| { // The scene being edited; the menu switches scenes and manages them. let name = app.s.doc.scenes.get(app.s.scene).map_or_else(|| tr!("Scene").to_string(), |s| s.name.clone()); - egui::ComboBox::from_id_salt("scene").selected_text(text(Type::Body, name).strong()).height(480.0).show_ui(ui, |ui| { - ui.set_min_width(240.0); - let scenes: Vec<(String, u32)> = app.s.doc.scenes.iter().map(|s| (s.name.clone(), s.timeline.frame_count())).collect(); - for (i, (n, frames)) in scenes.iter().enumerate() { - let r = ui.horizontal(|ui| { - let r = ui.selectable_label(i == app.s.scene, n.as_str()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(text(Type::DataSmall, format!("{frames} f")).color(T.text_faint)); - }); - r + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 1.0; + let inside_symbol = !app.s.editing.is_empty(); + + if inside_symbol { + let label_response = ui.add( + egui::Button::new(text(Type::Body, name.clone()).strong()) + .corner_radius(egui::CornerRadius { + nw: 6, + ne: 0, + sw: 6, + se: 0, + }) + ); + + #[cfg(test)] + ui.ctx().data_mut(|data| { + data.insert_temp( + egui::Id::new("test_scene_label_rect"), + label_response.interact_rect, + ); }); - if r.inner.clicked() && i != app.s.scene { - app.playing = false; - app.frame_sel = None; - app.run("scene.select", serde_json::json!({"scene": i})); - } else if r.inner.clicked() && !app.s.editing.is_empty() { - // The scene itself, from inside a symbol: back to it (ADR 0045). + + if label_response.clicked() { app.playing = false; app.frame_sel = None; app.run("symbol.exit", serde_json::json!({"all": true})); } } - ui.separator(); - for id in ["scene.new", "scene.duplicate", "scene.rename", "scene.delete", "scene.move_up", "scene.move_down"] { - crate::menus::cmd_item(app, ui, id); + + if inside_symbol { + let corners = egui::CornerRadius { + nw: 0, + ne: 6, + sw: 0, + se: 6, + }; + + let widgets = &mut ui.style_mut().visuals.widgets; + widgets.inactive.corner_radius = corners; + widgets.hovered.corner_radius = corners; + widgets.active.corner_radius = corners; + widgets.open.corner_radius = corners; } - }) - .response - .set_name(tr!("Scene")); + + let scene_caption = if inside_symbol { String::new() } else { name }; + + let scene_response = egui::ComboBox::from_id_salt("scene") + .width(if inside_symbol { 32.0 } else { ui.spacing().combo_width }) + .selected_text(text(Type::Body, scene_caption).strong()) + .height(480.0) + .show_ui(ui, |ui| { + ui.set_min_width(240.0); + let scenes: Vec<(String, u32)> = app.s.doc.scenes.iter().map(|s| (s.name.clone(), s.timeline.frame_count())).collect(); + for (i, (n, frames)) in scenes.iter().enumerate() { + let r = ui.add( + egui::Button::selectable(i == app.s.scene, n.as_str()) + .right_text(text(Type::DataSmall, format!("{frames} f")).color(T.text_faint)) + .min_size(egui::vec2(ui.available_width(), ui.spacing().interact_size.y)), + ); + if r.clicked() && i != app.s.scene { + app.playing = false; + app.frame_sel = None; + app.run("scene.select", serde_json::json!({"scene": i})); + } else if r.clicked() && !app.s.editing.is_empty() { + // The scene itself, from inside a symbol: back to it (ADR 0045). + app.playing = false; + app.frame_sel = None; + app.run("symbol.exit", serde_json::json!({"all": true})); + } + } + ui.separator(); + for id in ["scene.new", "scene.duplicate", "scene.rename", "scene.delete", "scene.move_up", "scene.move_down"] { + crate::menus::cmd_item(app, ui, id); + } + }) + .response; + + #[cfg(test)] + ui.ctx().data_mut(|data| { + data.insert_temp( + egui::Id::new("test_scene_arrow_rect"), + scene_response.interact_rect, + ); + data.insert_temp( + egui::Id::new("test_scene_arrow_id"), + scene_response.id, + ); + }); + + scene_response.set_name(tr!("Scene")); + }); // The symbols open for editing (ADR 0045), as in Animate's edit bar: a click on one // goes back to it; the last is the one being edited. // A group (ADR 0073) shows as "Group" and a drawing object (ADR 0080) as "Drawing @@ -2990,4 +3053,153 @@ mod tests { assert!(!stroke_only(t), "{t:?} fills"); } } + + #[test] + fn scene_breadcrumb_padding_click_exits_symbol() { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new( + anicraft_engine::doc::sample::demo() + ); + let mut app = App::with_context( + &ctx, + session, + Some(std::path::PathBuf::from("unused.png")), + ); + + // Open a REAL library symbol for editing. + let symbol = app.s.doc.library.first() + .expect("Demo should contain a symbol") + .id.0; + + assert!(app.run("symbol.edit", json!({"symbol": symbol})).is_some()); + assert_eq!(app.s.editing.len(), 1); + + let input = |events| egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1200.0, 800.0), + )), + events, + ..Default::default() + }; + + // Draw the REAL edit bar so egui can measure its controls. + ctx.run_ui(input(vec![]), |ui| edit_bar(&mut app, ui)) + .textures_delta.clear(); + + // Get the actual scene control's interaction rectangle. + let label_rect = ctx.data(|data| { + data.get_temp::( + egui::Id::new("test_scene_label_rect") + ) + }).expect("Scene control rectangle should exist"); + + // Click near the scene button's left edge, away from the text. + let click = egui::pos2( + label_rect.left() + 2.0, + label_rect.center().y, + ); + assert!(label_rect.contains(click)); + + // A real click involves a press and a release. + for pressed in [true, false] { + let events = vec![ + egui::Event::PointerMoved(click), + egui::Event::PointerButton { + pos: click, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }, + ]; + + ctx.run_ui(input(events), |ui| edit_bar(&mut app, ui)) + .textures_delta.clear(); + } + + // Clicking the arrow should open the menu without leaving the symbol. + assert!( + app.s.editing.is_empty(), + "Clicking scene-label padding should return to the scene" + ); + } + + #[test] + fn scene_breadcrumb_arrow_opens_menu_without_exiting_symbol() { + let ctx = egui::Context::default(); + let session = anicraft_engine::Session::new( + anicraft_engine::doc::sample::demo() + ); + let mut app = App::with_context( + &ctx, + session, + Some(std::path::PathBuf::from("unused.png")), + ); + + // Open a REAL library symbol for editing. + let symbol = app.s.doc.library.first() + .expect("Demo should contain a symbol") + .id.0; + + assert!(app.run("symbol.edit", json!({"symbol": symbol})).is_some()); + assert_eq!(app.s.editing.len(), 1); + + let input = |events| egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1200.0, 800.0), + )), + events, + ..Default::default() + }; + + // Draw the edit bar once so egui can measure the dropdown arrow. + ctx.run_ui(input(vec![]), |ui| edit_bar(&mut app, ui)) + .textures_delta.clear(); + + // Get the actual dropdown arrow's rectangle and widget ID. + let arrow_rect = ctx.data(|data| { + data.get_temp::( + egui::Id::new("test_scene_arrow_rect") + ) + }).expect("Scene arrow rectangle should exist"); + + let arrow_id = ctx.data(|data| { + data.get_temp::( + egui::Id::new("test_scene_arrow_id") + ) + }).expect("Scene arrow ID should exist"); + + // Click the centre of the arrow control. + let click = arrow_rect.center(); + assert!(arrow_rect.contains(click)); + + // A real click involves a press and a release. + for pressed in [true, false] { + let events = vec![ + egui::Event::PointerMoved(click), + egui::Event::PointerButton { + pos: click, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }, + ]; + + ctx.run_ui(input(events), |ui| edit_bar(&mut app, ui)) + .textures_delta.clear(); + } + + // Clicking the scene name should leave symbol-editing mode. + assert_eq!( + app.s.editing.len(), + 1, + "Clicking the arrow must not exit symbol-editing mode" + ); + + assert!( + egui::ComboBox::is_open(&ctx, arrow_id), + "Clicking the arrow should open the scene dropdown" + ); + } } From f0ecb72dbeb5cc06dda9d57fa797bb863f02bfeb Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:25:24 +0100 Subject: [PATCH 116/570] fix(actions): preserve negative zero in Math.round (M6) Preserve the sign of negative fractions rounded to zero in the exported HTML player. --- crates/render/src/html/player.js | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index 439cf6b4..0285a984 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -551,6 +551,7 @@ var AniCraft = (function () { // Math.round as the Rust evaluator computes it. function round(x) { if (!Number.isFinite(x)) return x; + if (x >= -0.5 && x < 0) return -0; const f = Math.floor(x); return x - f >= 0.5 ? f + 1 : f; } From 6e8b0898d6d88c473bc39a29a54ad63dbeb9d4ac Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:26:31 +0100 Subject: [PATCH 117/570] fix(actions): preserve signed zero in Rust rounding (M6) Keep the negative sign for values from -0.5 up to zero, matching the HTML player fix. --- crates/actions/src/as3/run.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/actions/src/as3/run.rs b/crates/actions/src/as3/run.rs index 262237fe..83fac4ba 100644 --- a/crates/actions/src/as3/run.rs +++ b/crates/actions/src/as3/run.rs @@ -119,6 +119,10 @@ pub fn round(x: f64) -> f64 { if !x.is_finite() { return x; } + // Negative fractions rounded to zero keep their sign, so their reciprocal is -Infinity. + if (-0.5..0.0).contains(&x) { + return -0.0; + } let f = x.floor(); if x - f >= 0.5 { f + 1.0 } else { f } } From f731be87915dc8d9940f01e2497da5adc98d2b3a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:27:29 +0100 Subject: [PATCH 118/570] test(actions): cover negative-zero rounding (M6) Check the sign bits and reciprocal trace through the AS3 evaluator. --- crates/actions/src/as3/tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index 2cc2e506..fa5b3dd9 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -172,6 +172,14 @@ fn expressions_follow_ecmascript() { ); } +#[test] +fn math_round_preserves_negative_zero() { + for value in [-0.5, -0.4, -0.0] { + assert_eq!(run::round(value).to_bits(), (-0.0f64).to_bits(), "{value}"); + } + assert_eq!(lines("trace(1 / Math.round(-0.5), 1 / Math.round(-0.4));"), ["-Infinity -Infinity"]); +} + #[test] fn if_else_and_loops_run_with_break_and_continue() { let a = lines( From 2ce43c9ba833e563c70471497d1af04665e53dd2 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:28:12 +0100 Subject: [PATCH 119/570] test(render): cover signed-zero round traces in exports (M6) Keep Rust and exported HTML reciprocal traces aligned for negative fractions that round to zero. --- crates/render/src/html_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 61a6ed35..ef143f57 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -819,7 +819,7 @@ fn logic() -> Document { trace(\"start \" + score + \" \" + label + \" \" + ticks + \" \" + currentFrame + \"/\" + totalFrames + \" \" + currentLabel);\n\ for (var i:int = 0; i < 5; i++) { if (i % 2 == 0) continue; total += i * 1.5; }\n\ var k:int = 3; while (k > 0) { k--; } do { k += 2; } while (k < 5);\n\ - trace(total, k, Math.max(1, 7, 3), Math.min(), Math.round(-2.5), Math.abs(-0.25), int(\"42\") + uint(-1), 7 / 2, \"10\" < \"9\", 1 == \"1\", null == undefined);\n\ + trace(total, k, Math.max(1, 7, 3), Math.min(), Math.round(-2.5), 1 / Math.round(-0.5), 1 / Math.round(-0.4), Math.abs(-0.25), int(\"42\") + uint(-1), 7 / 2, \"10\" < \"9\", 1 == \"1\", null == undefined);\n\ trace(Math.floor(Math.random() * 100), Math.random() < 1, knob.x, knob.y, knob.alpha, knob.visible, knob.name, panel.currentFrame, panel.totalFrames);\n\ addEventListener(Event.ENTER_FRAME, onTick);\n\ stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\n\ @@ -866,7 +866,7 @@ fn the_js_player_runs_small_logic_like_the_rust_player() { script.push((vec![Event::Move(at(10.0, 10.0)), Event::Leave], vec![Event::KeyDown(39)])); script.extend((0..20).map(|_| none())); let lines = compare(&doc, &script); - for want in ["start 0 go 0 1/33 null", "6 6 7 Infinity -2 0.25 4294967337 3.5 true true true", "10 true 100 100 1 true knob 1 4", "frame 2: 2 go!", "Script on frame 4 of the main timeline stopped: line 4: no instance named “ghost” here", "stopped ticking", "up 39 true", "key 65"] { + for want in ["start 0 go 0 1/33 null", "6 6 7 Infinity -2 -Infinity -Infinity 0.25 4294967337 3.5 true true true", "10 true 100 100 1 true knob 1 4", "frame 2: 2 go!", "Script on frame 4 of the main timeline stopped: line 4: no instance named “ghost” here", "stopped ticking", "up 39 true", "key 65"] { assert!(lines.iter().any(|l| l == want), "the logic fixture never wrote {want:?}: {lines:?}"); } assert!(lines.iter().any(|l| l == "click knob true 11"), "{lines:?}"); From 379635fc64015c363f1cc92bc68d8037ac5603f2 Mon Sep 17 00:00:00 2001 From: Untoldent Date: Sun, 15 Nov 2026 14:57:46 -0500 Subject: [PATCH 120/570] test: correct scene breadcrumb test comments --- src/panels.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/panels.rs b/src/panels.rs index cae54df0..2f016c4b 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -3117,7 +3117,7 @@ mod tests { .textures_delta.clear(); } - // Clicking the arrow should open the menu without leaving the symbol. + // Clicking the scene name should leave symbol-editing mode. assert!( app.s.editing.is_empty(), "Clicking scene-label padding should return to the scene" @@ -3190,7 +3190,7 @@ mod tests { .textures_delta.clear(); } - // Clicking the scene name should leave symbol-editing mode. + // Clicking the arrow should open the menu without leaving the symbol. assert_eq!( app.s.editing.len(), 1, From b566745647979b0071f7b209f27c5c4d358e6c54 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:09:45 -0500 Subject: [PATCH 121/570] Reuse shared HTML escaping while preserving control policies --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + crates/guide/Cargo.toml | 1 + crates/guide/src/lib.rs | 13 +------------ crates/guide/src/tests.rs | 28 ++++++++++++++++++++++++++++ crates/render/Cargo.toml | 1 + crates/render/src/html.rs | 18 ++++++------------ crates/render/src/html_tests.rs | 29 +++++++++++++++++++++++++++++ 8 files changed, 74 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8f8878b1..3fa33c3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -355,6 +355,7 @@ dependencies = [ name = "anicraft-guide" version = "0.3.0" dependencies = [ + "craft-html", "pulldown-cmark", ] @@ -376,6 +377,7 @@ dependencies = [ "anicraft-doc", "anicraft-geom", "boa_engine", + "craft-html", "craft-image-codecs", "rayon", "serde_json", @@ -1235,6 +1237,11 @@ dependencies = [ "gif", ] +[[package]] +name = "craft-html" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" + [[package]] name = "craft-image-codecs" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 1ba2d48a..e61d94fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ anicraft-gpu = { path = "crates/gpu" } anicraft-guide = { path = "crates/guide" } craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-html = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["decode", "pcm-encode"] } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } diff --git a/crates/guide/Cargo.toml b/crates/guide/Cargo.toml index c7b99d53..921066a6 100644 --- a/crates/guide/Cargo.toml +++ b/crates/guide/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true repository.workspace = true [dependencies] +craft-html.workspace = true # CommonMark with GFM tables (MIT; ADR 0069). Default features off: no command-line binary. pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs index f525299f..8b11f10d 100644 --- a/crates/guide/src/lib.rs +++ b/crates/guide/src/lib.rs @@ -192,18 +192,7 @@ pub fn title(markdown: &str) -> String { } fn escape(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - c => out.push(c), - } - } - out + craft_html::escape(s) } /// `../` once per folder the page is in, to reach the book's root. diff --git a/crates/guide/src/tests.rs b/crates/guide/src/tests.rs index 3a969a95..32a7a7c1 100644 --- a/crates/guide/src/tests.rs +++ b/crates/guide/src/tests.rs @@ -114,3 +114,31 @@ fn writes_the_book_to_a_folder() { assert!(dir.join("index.html").is_file() && dir.join("reference").join("commands.html").is_file()); let _ = std::fs::remove_dir_all(&dir); } + +// Frozen pre-cutover escaping oracle; original application behavior. +fn previous_html_escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +#[test] +fn shared_html_escape_preserves_all_unicode_scalars() { + for ch in (0..=0x10ffff).filter_map(char::from_u32) { + let mut buf = [0u8; 4]; + let text = ch.encode_utf8(&mut buf); + assert_eq!(super::escape(text), previous_html_escape(text), "{ch:?}"); + } + for text in ["bc\";\ntrace(score_txt.text);\ntrace(score_txt.htmlText);\ntrace(name_txt.htmlText);"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Score: 12 hot")); + let st = s.state.fields.get(&vec![ElementId(5)]).unwrap(); + let rich = st.rich.as_ref().expect("styled"); + assert_eq!(rich.runs.iter().map(|r| (r.chars, r.style.bold, r.style.color.r > 0.5)).collect::>(), vec![(7, false, false), (2, true, false), (1, false, false), (3, false, true)]); + assert_eq!(rich.paragraphs[0].align, crate::TextAlign::Center); + assert!(s.output.contains(&"Score: 12 hot".to_string()), "{:?}", s.output); + // Read back in the subset, in the field's own font and size; nothing of the script tag. + let html = s.output.iter().find(|l| l.starts_with("

      ")).expect("htmlText traced"); + assert!(html.contains("12") && html.contains("color=\"#ff0000\">hot

      ") && !html.contains("script"), "{html}"); + // A field no script touched reads its authored text and style. + assert!(s.output.contains(&"

      ".to_string()), "{:?}", s.output); + // Setting `text` afterwards puts it back in the field's own style. + let d = field_doc("score_txt.htmlText = \"a\";\nscore_txt.text = \"plain\";\ntrace(score_txt.htmlText);"); + let s = start(&d, &mut Mono); + assert!(s.state.fields.get(&vec![ElementId(5)]).unwrap().rich.is_none()); + assert!(s.output.contains(&"

      plain

      ".to_string()), "{:?}", s.output); + // Typing into a styled input field continues the style before the caret. + let d = field_doc("stop();\nname_txt.htmlText = \"ab\";"); + let s = start(&d, &mut Mono); + let s = type_into_name(&d, &s.state, "c"); + let st = s.state.fields.get(&vec![ElementId(6)]).unwrap(); + assert_eq!(st.text.as_deref(), Some("abc")); + let runs = &st.rich.as_ref().unwrap().runs; + assert_eq!((runs.len(), runs[0].chars, runs[0].style.bold), (1, 3, true)); + // Not a field, or null: a message, and the movie goes on. + let d = field_doc("score_txt.htmlText = null;"); + assert!(start(&d, &mut Mono).output.iter().any(|l| l.contains("`htmlText` is set to text"))); +} + +#[test] +fn change_events_fire_once_per_edit_by_the_viewer() { + let d = field_doc( + "stop();\nvar n:int = 0;\nfunction onChange(e:Event):void { n++; trace(\"change \" + n + \": \" + e.target.text + \" \" + (e.currentTarget == name_txt)); }\nname_txt.addEventListener(Event.CHANGE, onChange);\nname_txt.addEventListener(Event.CHANGE, onChange);\nname_txt.text = \"set by script\";\nscore_txt.addEventListener(Event.CHANGE, onChange);", + ); + let s = start(&d, &mut Mono); + assert!(s.output.is_empty(), "a script setting text fires nothing: {:?}", s.output); + assert_eq!(s.state.listeners.get(&vec![ElementId(6)]).map(Vec::len), Some(1), "the same listener is added once"); + // Three characters: three events, each after its edit, with the field as target. + let s = type_into_name(&d, &s.state, "abc"); + let changes: Vec<&String> = s.output.iter().filter(|l| l.starts_with("change")).collect(); + assert_eq!(changes.len(), 3, "{:?}", s.output); + assert_eq!(changes[2].as_str(), "change 3: set by scriptabc true"); + // Caret moves, selecting and keys that change nothing fire nothing; a deletion fires once. + let s2 = input(&d, &s.state, &[Event::KeyDown(37), Event::KeyDown(36), Event::SelectAll, Event::KeyDown(13), Event::KeyDown(9)], &mut Mono); + assert!(s2.output.iter().all(|l| !l.starts_with("change")), "{:?}", s2.output); + let s3 = input(&d, &s.state, &[Event::KeyDown(8)], &mut Mono); + assert_eq!(s3.output.iter().filter(|l| l.starts_with("change")).count(), 1, "{:?}", s3.output); + // Backspace at the start of an empty field changes nothing and fires nothing. + let d2 = field_doc("stop();\nname_txt.addEventListener(Event.CHANGE, function (e:Event):void { trace(\"change\"); });"); + let s = start(&d2, &mut Mono); + let s = input(&d2, &s.state, &[Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0)), Event::KeyDown(8), Event::KeyDown(46)], &mut Mono); + assert!(s.output.is_empty(), "{:?}", s.output); + // Removing the listener stops it; other instances don't send change events. + let d3 = field_doc("stop();\nfunction f(e:Event):void { trace(\"change\"); }\nname_txt.addEventListener(Event.CHANGE, f);\nname_txt.removeEventListener(Event.CHANGE, f);"); + let s = start(&d3, &mut Mono); + assert!(type_into_name(&d3, &s.state, "a").output.is_empty()); + // The same events and state give the same output (the player stays deterministic). + let s = start(&d, &mut Mono); + assert_eq!(type_into_name(&d, &s.state, "xy"), type_into_name(&d, &s.state, "xy")); +} + +#[test] +fn a_fields_change_actions_run_in_its_timeline() { + let mut d = field_doc("stop();"); + // The name field traces on every change (the action IR's side of Event.CHANGE). + let layer = Arc::make_mut(&mut Arc::make_mut(&mut d.scenes[0]).timeline.layers[0]); + let kf = Arc::make_mut(&mut layer.keyframes[0]); + for e in &mut kf.elements { + if e.id == ElementId(6) + && let ElementKind::Text(t) = &mut Arc::make_mut(e).kind + { + Arc::make_mut(t).field.as_mut().unwrap().on_change = vec![Action::Trace { message: "edited".into() }]; + } + } + let s = start(&d, &mut Mono); + let s = type_into_name(&d, &s.state, "ab"); + assert_eq!(s.output, vec!["edited".to_string(), "edited".to_string()]); + // It is saved with the field and older files open without it. + let ElementKind::Text(t) = &d.scenes[0].timeline.layers[0].keyframes[0].elements[1].kind else { panic!() }; + let json = serde_json::to_string(t.field.as_ref().unwrap()).unwrap(); + assert!(json.contains("\"on_change\""), "{json}"); + let back: TextField = serde_json::from_str(&json).unwrap(); + assert_eq!(&back, t.field.as_ref().unwrap()); + assert!(!serde_json::to_string(&TextField::new(TextKind::Input)).unwrap().contains("on_change"), "fields without one save as before"); +} + +#[test] +fn max_chars_and_restrict_limit_what_the_viewer_types() { + let d = field_doc("stop();\ntrace(name_txt.maxChars, name_txt.restrict);\nname_txt.maxChars = 4;\nname_txt.restrict = \"A-Z0-9\";\ntrace(name_txt.maxChars, name_txt.restrict);"); + let s = start(&d, &mut Mono); + assert_eq!(s.output, vec!["0 null".to_string(), "4 A-Z0-9".to_string()]); + let s = type_into_name(&d, &s.state, "aB-c1D2E3"); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("B1D2"), "only capitals and digits, four of them"); + // A script may still set anything: the limits are the viewer's. + let d = field_doc("stop();\nname_txt.restrict = \"\";\nname_txt.maxChars = 2;\nname_txt.text = \"longer than two\";"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("longer than two")); + assert_eq!(type_into_name(&d, &s.state, "x").state.fields.get(&vec![ElementId(6)]).and_then(|f| f.text.clone()).as_deref(), Some("longer than two"), "an empty restrict lets nothing in"); + // null lifts the restriction. + let d = field_doc("stop();\nname_txt.restrict = \"x\";\nname_txt.restrict = null;"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&type_into_name(&d, &s.state, "ok").state, 6).as_deref(), Some("ok")); +} + diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index a96a7def..faff585c 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -403,6 +403,18 @@ pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_wid field_lay(fonts, &anicraft_text::RichText { text: shown, runs: &[run], paragraphs: &[para], width: field.wrap_width(box_width) }, style.align, field, box_width) } +/// A field's text laid out in the styles a script gave it with `htmlText` (ADR 0107), and the +/// colour each of the layout's paints stands for. Links don't cut pieces here: a colour is one +/// piece. +pub fn field_layout_rich(fonts: &Fonts, block: &TextBlock, field: &TextField, shown: &str, rich: &anicraft_doc::html_text::RichStyles) -> std::result::Result<(anicraft_text::Layout, Vec), anicraft_text::TextError> { + let mut d = TextBlock { text: shown.to_string(), runs: Vec::new(), paragraphs: Vec::new(), ..block.clone() }; + let runs = rich.runs.iter().map(|r| TextRun { chars: r.chars, style: CharStyle { url: String::new(), ..r.style.clone() } }).collect(); + d.set_styles(runs, rich.paragraphs.clone()); + let (runs, paras, paints) = rich_parts(&d); + let l = field_lay(fonts, &anicraft_text::RichText { text: shown, runs: &runs, paragraphs: ¶s, width: field.wrap_width(block.box_width) }, d.align, field, block.box_width)?; + Ok((l, paints.into_iter().map(|(c, _)| c).collect())) +} + /// `t` with its text changed to `text`, its runs and paragraphs following the change (one /// edit: what was typed continues the style before it). pub(crate) fn retext(t: &TextBlock, text: &str) -> TextBlock { diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index 9306aaea..128d6dd9 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -94,21 +94,27 @@ impl ScriptHost for ScriptRunner<'_> { } } - fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { - field_look(block, shown) + fn lay_out_field(&mut self, block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::html_text::RichStyles>) -> Option { + field_look(block, shown, rich) } } /// A field's text laid out with this computer's fonts, as the player draws and edits it /// (ADR 0066). -pub fn field_look(block: &TextBlock, shown: &str) -> Option { +pub fn field_look(block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::html_text::RichStyles>) -> Option { let f = block.field.as_ref()?; - let l = crate::cmds_text::field_layout(anicraft_text::Fonts::get(), &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?; + let fonts = anicraft_text::Fonts::get(); + // Styled text (`htmlText`, ADR 0107) is laid out run by run, one piece per colour. + let (l, colors) = match rich { + Some(r) => crate::cmds_text::field_layout_rich(fonts, block, f, shown, r).ok()?, + None => (crate::cmds_text::field_layout(fonts, &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?, Vec::new()), + }; + let pieces: Vec<(anicraft_doc::Rgba, std::sync::Arc)> = if colors.len() > 1 || colors.first().is_some_and(|c| *c != block.color) { l.pieces.iter().filter_map(|(k, p)| Some((*colors.get(*k as usize)?, std::sync::Arc::new(p.clone())))).collect() } else { Vec::new() }; let mut lines: Vec = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, stops: c.stops }).collect(); if lines.is_empty() { lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }); } - Some(FieldLook { outline: std::sync::Arc::new(l.outline), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) + Some(FieldLook { outline: std::sync::Arc::new(l.outline), pieces: pieces.into(), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) } /// What a running frame script talks to. From 472e3972aed8c4a8e6ce36379763549479c07629 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 20 Nov 2026 14:33:06 -0700 Subject: [PATCH 386/570] feat(fields): the change event in actions.set and the Actions panel; end-to-end Test Movie test (M5) --- crates/engine/src/cmds_actions.rs | 46 ++++++++++++++++++++++- crates/engine/src/tests_script.rs | 62 +++++++++++++++++++++++++++++++ src/actions_panel.rs | 58 ++++++++++++++++++++++++++--- 3 files changed, 159 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index fe106894..02a4f0a6 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y} or {tick, type: key_down|key_up|key, key: code|letter|LEFT…}], seed?: Math.random()'s seed (default 0)} plays the movie with its actions and frame scripts from the first frame; returns the output, the sounds it started ({tick, sound, name, sync, gain}; buttons' as the pointer changes their state) and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn), - c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} sets an instance's event handler. An empty list clears it", true, set), + c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} (or event: change on an input text field: what it does when the viewer changes its text, ADR 0107) sets an instance's event handler. An empty list clears it", true, set), c("actions.clear", "Clear Actions", "", None, "{symbol?, layer?, frame?} clears the keyframe's actions; {element, event?} clears an instance's handlers (one event, or all)", true, clear), c("actions.list", "List Actions", "", None, "{} every keyframe with actions or a frame script and every instance with event handlers, in every scene and symbol", false, list), c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance, or a dynamic or input text field, for actions and scripts", true, set_name), @@ -142,8 +142,28 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": lid.0, "keyframe": k.start, "actions": n, "summary": summary})) } +/// `{element, event: "change", actions}`: what an input text field does when the viewer +/// changes its text (ADR 0107). +fn set_change(s: &mut Session, p: &Value) -> Result { + let list = parse_actions(p)?; + let el = instance_mut(s, p)?; + let id = el.id; + match &mut el.kind { + ElementKind::Text(t) if t.field.as_ref().is_some_and(|f| f.kind == anicraft_doc::TextKind::Input) => { + if let Some(f) = Arc::make_mut(t).field.as_mut() { + f.on_change = list.clone(); + } + } + _ => return Err(EngineError::State("only input text fields have a change event: the viewer changes their text (set the text's type to Input in Properties)".into())), + } + Ok(json!({"element": id.0, "event": "change", "actions": list.len()})) +} + fn set_handler(s: &mut Session, p: &Value) -> Result { - let event = ButtonEvent::from_key(str_req(p, "event")?).ok_or_else(|| EngineError::Param("param 'event' must be click, press, release, over or out".into()))?; + if opt_str(p, "event")? == Some("change") { + return set_change(s, p); + } + let event = ButtonEvent::from_key(str_req(p, "event")?).ok_or_else(|| EngineError::Param("param 'event' must be click, press, release, over or out (or change, on an input text field)".into()))?; let list = parse_actions(p)?; let e = instance_mut(s, p)?.clone(); interactive_kind(s, &e)?; @@ -165,6 +185,20 @@ fn set_handler(s: &mut Session, p: &Value) -> Result { fn clear(s: &mut Session, p: &Value) -> Result { if p.get("element").is_some() { + // An input text field's change actions (its one event). + if matches!(opt_str(p, "event")?, None | Some("change")) { + let el = instance_mut(s, p)?; + let id = el.id; + if let ElementKind::Text(t) = &mut el.kind { + let n = t.field.as_ref().map_or(0, |f| usize::from(!f.on_change.is_empty())); + if n > 0 + && let Some(f) = Arc::make_mut(t).field.as_mut() + { + f.on_change.clear(); + } + return Ok(json!({"element": id.0, "cleared": n})); + } + } let event = match opt_str(p, "event")? { Some(k) => Some(ButtonEvent::from_key(k).ok_or_else(|| EngineError::Param("param 'event' must be click, press, release, over or out".into()))?), None => None, @@ -211,6 +245,14 @@ fn list(s: &mut Session, _: &Value) -> Result { merge(&mut v, &at); instances.push(v); } + if let ElementKind::Text(t) = &e.kind + && let Some(f) = t.field.as_ref().filter(|f| !f.on_change.is_empty()) + { + let evs = json!([{"event": "change", "actions": serde_json::to_value(&f.on_change).unwrap_or(Value::Null), "summary": f.on_change.iter().map(Action::describe).collect::>().join("; ")}]); + let mut v = json!({"timeline": name, "layer": l.id.0, "frame": k.start, "element": e.id.0, "name": e.name, "field": f.kind.key(), "events": evs}); + merge(&mut v, &at); + instances.push(v); + } } } } diff --git a/crates/engine/src/tests_script.rs b/crates/engine/src/tests_script.rs index f6d52817..eaa22b1a 100644 --- a/crates/engine/src/tests_script.rs +++ b/crates/engine/src/tests_script.rs @@ -259,3 +259,65 @@ fn text_fields_are_made_named_saved_and_typed_into() { // Plug-ins may set text types (document content, like the rest of text.*). assert!(crate::cmds_plugin::plugin_may_call("text.field").is_ok()); } + +/// The rest of the text-field API (ADR 0107), end to end through commands: `htmlText` laid out +/// in its colours with this computer's fonts, change events from scripts and from the action +/// list, `maxChars` and `restrict`, in a headless Test Movie. +#[test] +fn html_text_change_events_and_limits_run_in_test_movie() { + if anicraft_text::Fonts::get().families().is_empty() { + return; + } + let mut s = Session::default(); + let ok = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + ok(&mut s, "text.create", json!({"text": "0", "type": "dynamic", "x": 20, "y": 20, "size": 20})); + ok(&mut s, "text.field", json!({"width": 300, "height": 60, "lines": "multiline"})); + ok(&mut s, "instance.set_name", json!({"name": "out_txt"})); + let input = ok(&mut s, "text.create", json!({"text": "", "type": "input", "x": 20, "y": 100, "size": 20}))["element"].as_u64().unwrap(); + ok(&mut s, "text.field", json!({"width": 200, "height": 30})); + ok(&mut s, "instance.set_name", json!({"name": "name_txt"})); + // The action list's change event: only on input fields, one undo step, listed, cleared. + let steps = s.history().undo_len(); + let v = ok(&mut s, "actions.set", json!({"element": input, "event": "change", "actions": [{"op": "trace", "message": "edited"}]})); + assert_eq!((v["event"].as_str(), v["actions"].as_u64()), (Some("change"), Some(1))); + assert_eq!(s.history().undo_len(), steps + 1); + let list = ok(&mut s, "actions.list", json!({})); + assert!(list["instances"].as_array().unwrap().iter().any(|i| i["element"] == input && i["events"][0]["event"] == "change" && i["field"] == "input"), "{list}"); + let dynamic = s.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.name == "out_txt").unwrap().id.0; + assert!(s.execute("actions.set", &json!({"element": dynamic, "event": "change", "actions": []})).unwrap_err().to_string().contains("only input text fields")); + assert_eq!(ok(&mut s, "actions.clear", json!({"element": input, "event": "change"}))["cleared"], 1); + s.undo().unwrap(); + ok(&mut s, "script.set", json!({"frame": 0, "text": "stop();\nvar n:int = 0;\nout_txt.htmlText = \"

      Type your NAME

      \";\nname_txt.maxChars = 6;\nname_txt.restrict = \"A-Z\";\nname_txt.addEventListener(Event.CHANGE, onChange);\nfunction onChange(e:Event):void { n++; out_txt.htmlText = \"\" + e.target.text + \" (\" + n + \")\"; }\ntrace(out_txt.htmlText);"})); + // The file keeps it all. + let saved = crate::format::to_json(&s.doc).unwrap(); + assert_eq!(crate::format::from_json(&saved).unwrap(), s.doc); + // The first frame: styled text, read back as HTML in the subset. + let v = ok(&mut s, "control.test_movie", json!({"frames": 1})); + let line = v["output"].as_array().unwrap().iter().map(|l| l["line"].as_str().unwrap_or("").to_string()).find(|l| l.starts_with("your
      ") && line.contains("size=\"28\" color=\"#cc0000\">NAME

      "), "{line}"); + // Typing: lower case and digits are refused, six capitals at most, one change per edit. + let v = ok(&mut s, "control.test_movie", json!({"frames": 3, "events": [{"tick": 1, "type": "click", "x": 40, "y": 112}, {"tick": 1, "type": "text", "text": "aB1cDEFGHIJ"}]})); + let fields = v["state"]["fields"].as_array().unwrap(); + let text_of = |n: &str| fields.iter().find(|f| f["name"] == n).map(|f| f["text"].clone()).unwrap(); + assert_eq!(text_of("name_txt"), "BDEFGH"); + assert_eq!(text_of("out_txt"), "BDEFGH (6)", "six edits, six events"); + let edited = v["output"].as_array().unwrap().iter().filter(|l| l["line"] == "edited").count(); + assert_eq!(edited, 6, "the action list's change event ran with each: {}", v["output"]); + // The look a styled field gets: one piece per colour, laid out by the engine's fonts. + let block = match &s.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.name == "out_txt").unwrap().kind { + ElementKind::Text(t) => t.clone(), + _ => panic!("text"), + }; + let parsed = anicraft_doc::html_text::parse("black red bold", &block.char_style(), &block.para_style()); + let look = crate::player::field_look(&block, &parsed.text, Some(&parsed.styles)).expect("laid out"); + assert_eq!(look.pieces.len(), 2, "black and red"); + assert!(look.pieces[1].0.r > 0.9 && look.pieces[1].0.g < 0.1); + let plain = crate::player::field_look(&block, &parsed.text, None).unwrap(); + assert!(plain.pieces.is_empty(), "one colour draws as one outline, as before"); + assert!(look.outline != plain.outline, "the bold run has its own glyphs"); + // Hostile HTML never reaches the layout as markup or stops the movie. + ok(&mut s, "script.set", json!({"frame": 0, "text": "out_txt.htmlText = \"
      ab\" + \"\";\ntrace(out_txt.text);"})); + let v = ok(&mut s, "control.test_movie", json!({"frames": 1})); + assert!(v["output"].as_array().unwrap().iter().any(|l| l["line"] == "ab"), "{}", v["output"]); +} + diff --git a/src/actions_panel.rs b/src/actions_panel.rs index a6f97400..9ebcf804 100644 --- a/src/actions_panel.rs +++ b/src/actions_panel.rs @@ -64,9 +64,19 @@ fn selected_instance(app: &App) -> Option<(Element, SymbolKind)> { (kind != SymbolKind::Graphic).then(|| ((**e).clone(), kind)) } +/// The selected input text field, if exactly one element is selected and it is one (ADR 0107): +/// its change event is edited where an instance's events are. +fn selected_input(app: &App) -> Option { + let sel = app.s.selected_elements(); + let [(_, e)] = sel.as_slice() else { return None }; + let ElementKind::Text(t) = &e.kind else { return None }; + t.field.as_ref().is_some_and(|f| f.kind == anicraft_engine::doc::TextKind::Input).then(|| (**e).clone()) +} + /// The panel's contents, wherever it is. pub fn panel(app: &mut App, ui: &mut egui::Ui) { let inst = selected_instance(app); + let input = if inst.is_none() { selected_input(app) } else { None }; ui.horizontal_wrapped(|ui| { if ui.selectable_label(app.actions.tab == Tab::Frame, tr!("Frame")).on_hover_text(tr!("What runs when the playhead enters a keyframe")).clicked() { app.actions.tab = Tab::Frame; @@ -78,9 +88,13 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) { (false, true) => tr!("Movie clip (unnamed)").to_string(), (false, false) => tr!("Movie clip “{name}”", name = e.name), }, - None => tr!("Instance").to_string(), + None => match &input { + Some(e) if e.name.is_empty() => tr!("Input text (unnamed)").to_string(), + Some(e) => tr!("Input text “{name}”", name = e.name), + None => tr!("Instance").to_string(), + }, }; - let r = ui.add_enabled(inst.is_some(), egui::Button::selectable(app.actions.tab == Tab::Instance, label)).on_hover_text(tr!("What the selected button or movie clip does on clicks and the pointer")); + let r = ui.add_enabled(inst.is_some() || input.is_some(), egui::Button::selectable(app.actions.tab == Tab::Instance, label)).on_hover_text(tr!("What the selected button or movie clip does on clicks and the pointer")); let r = r.on_disabled_hover_text(tr!("Select one button or movie clip instance on the stage")); if r.clicked() { app.actions.tab = Tab::Instance; @@ -89,9 +103,12 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) { ui.separator(); match (app.actions.tab, inst) { (Tab::Instance, Some((e, _))) => instance_tab(app, ui, &e), - (Tab::Instance, None) => { - ui.label(text(Type::Caption, tr!("Select one button or movie clip instance on the stage to give it events (a graphic can't have them: set its symbol's Type in Properties)."))); - } + (Tab::Instance, None) => match input { + Some(e) => input_tab(app, ui, &e), + None => { + ui.label(text(Type::Caption, tr!("Select one button or movie clip instance on the stage to give it events (a graphic can't have them: set its symbol's Type in Properties). An input text field has a change event."))); + } + }, (Tab::Frame, _) => frame_tab(app, ui), } } @@ -616,6 +633,37 @@ fn instance_tab(app: &mut App, ui: &mut egui::Ui, e: &Element) { } } +/// An input text field's one event (ADR 0107): what it does each time the viewer changes its +/// text. +fn input_tab(app: &mut App, ui: &mut egui::Ui, e: &Element) { + let ElementKind::Text(t) = &e.kind else { return }; + let Some(f) = &t.field else { return }; + let doc = app.s.doc.clone(); + let tl = app.s.timeline().clone(); + let cx = Choices::new(&doc, &tl, true); + ui.label(text(Type::Caption, tr!("Runs each time the viewer changes the field's text, on the timeline the field is on. Scripts hear the same event with addEventListener(Event.CHANGE, …)."))); + ui.add_space(6.0); + if f.on_change.is_empty() { + if ui.button(tr!("Add change event")).on_hover_text(tr!("Do something each time the viewer types in this field")).clicked() { + let first = Action::Play { target: Target::this() }; + app.run("actions.set", json!({"element": e.id.0, "event": "change", "actions": [first]})); + } + return; + } + ui.horizontal(|ui| { + ui.label(text(Type::Body, tr!("On change")).strong()).on_hover_text(tr!("The viewer changed the field's text")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.small_button(tr!("Remove event")).clicked() { + app.run("actions.clear", json!({"element": e.id.0, "event": "change"})); + app.status_ok(tr!("Removed the change event — {undo} to undo", undo = app.undo_key())); + } + }); + }); + if let Some((new, live)) = edit_list(ui, "change", &f.on_change, &cx) { + run(app, live, tr_noop!("Edit event"), "actions.set", json!({"element": e.id.0, "event": "change", "actions": new})); + } +} + /// An event's heading in the Instance tab ("On click"): one sentence per event. fn event_heading(ev: ButtonEvent) -> &'static str { match ev { From 882434838ea483d62e225199dcf5f353cfd4db83 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 20 Nov 2026 14:41:45 -0700 Subject: [PATCH 387/570] feat(export): htmlText, change events, maxChars and restrict in the HTML page's player, at parity with Test Movie (M5) --- crates/doc/src/field.rs | 4 + crates/render/src/html.rs | 40 ++ crates/render/src/html/player.js | 679 ++++++++++++++++++++++++++++++- crates/render/src/html_tests.rs | 155 ++++++- 4 files changed, 858 insertions(+), 20 deletions(-) diff --git a/crates/doc/src/field.rs b/crates/doc/src/field.rs index 94c5c04e..7c60fbe5 100644 --- a/crates/doc/src/field.rs +++ b/crates/doc/src/field.rs @@ -264,6 +264,10 @@ impl Editor<'_> { let one = !self.field.lines.multiline(); let restrict = self.st.restrict.clone(); let mut add: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !one)).filter(|c| *c == '\n' || restrict.as_deref().is_none_or(|r| allowed(r, *c))).collect(); + // Typing only what the field refuses does nothing (it doesn't delete the selection). + if add.is_empty() && !s.is_empty() { + return Changed::default(); + } let (a, b) = self.st.selection(); let value = self.st.value(self.block).to_string(); let kept = chars(&value) - (b - a); diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 3474d1be..9813999e 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -576,6 +576,46 @@ impl<'a> Bake<'a> { if f.max_chars > 0 { o["mx"] = json!(f.max_chars.min(MAX_FIELD_CHARS as u32)); } + // What `htmlText` reads and is read against (ADR 0107): the field's own style `st` + // and first paragraph's alignment `al`, exactly; the authored runs `rs` (`[characters, + // style]`) and paragraph alignments `ps` when the text has several; and `oc`, the + // actions its change event runs. + let align_key = |a: TextAlign| match a { + TextAlign::Left => "left", + TextAlign::Center => "center", + TextAlign::Right => "right", + }; + let style = |s: &anicraft_doc::CharStyle| { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let mut st = json!({"f": s.font, "z": exact(s.size), "c": [b(s.color.r), b(s.color.g), b(s.color.b)]}); + if s.bold { + st["b"] = json!(true); + } + if s.italic { + st["i"] = json!(true); + } + if s.underline { + st["u"] = json!(true); + } + if s.letter_spacing != 0.0 { + st["ls"] = exact(s.letter_spacing); + } + if !s.url.is_empty() { + st["url"] = json!(s.url); + } + st + }; + o["st"] = style(&t.char_style()); + o["al"] = json!(align_key(t.para_style().align)); + if t.has_runs() { + o["rs"] = Value::Array(t.styled_runs().iter().map(|r| json!([r.chars, style(&r.style)])).collect()); + } + if !t.paragraphs.is_empty() { + o["ps"] = Value::Array(t.paragraph_styles().iter().map(|q| json!(align_key(q.align))).collect()); + } + if !f.on_change.is_empty() { + o["oc"] = actions(&f.on_change); + } // Authored text in several colours: its pieces, each in its colour (ADR 0085). if !t.fills.is_empty() { let pieces: Vec = t.fill_paths().iter().map(|(c, _, p)| json!([self.path(p), self.paint(&Paint::Solid(*c))])).collect(); diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index dce9c2a0..6736e506 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -459,7 +459,8 @@ var AniCraft = (function () { if (tf.bd) items.push(mk(tf.r, -1, tf.bd, tf.bk || null, clip, null)); for (const it of items) dl.items.push(it); if (!v) return; - if (v.field) v.field({ tf: tf, name: name, m: xf, c: color, clip: clip, group: group, key: key, text: text, focused: focused, items: items }); + // `rich`: the styles changed text is drawn in when a script set them (`htmlText`). + if (v.field) v.field({ tf: tf, name: name, m: xf, c: color, clip: clip, group: group, key: key, text: text, rich: text !== null && fs && fs.rich !== null ? fs.rich : null, focused: focused, items: items }); else for (const it of items) v.item(it); } @@ -513,7 +514,7 @@ var AniCraft = (function () { const MAX_LABEL_CHARS = 256; const PROP_NAMES = { x: "x", y: "y", alpha: "alpha", visible: "visible", rotation: "rotation", scale_x: "scaleX", scale_y: "scaleY" }; const PROP_LABELS = { x: "x", y: "y", alpha: "alpha", visible: "visible", rotation: "rotation", scale_x: "scale x", scale_y: "scale y" }; - const READ_NAMES = { current_frame: "currentFrame", total_frames: "totalFrames", current_label: "currentLabel", mouse_x: "mouseX", mouse_y: "mouseY", name: "name", text: "text", length: "length" }; + const READ_NAMES = { current_frame: "currentFrame", total_frames: "totalFrames", current_label: "currentLabel", mouse_x: "mouseX", mouse_y: "mouseY", name: "name", text: "text", length: "length", html_text: "htmlText", max_chars: "maxChars", restrict: "restrict" }; // Longest text a field holds (code points, as lib.rs `MAX_FIELD_CHARS`). const MAX_FIELD_CHARS = 16384; // How messages name a kind of instance (player.rs `kind_name`). @@ -889,6 +890,21 @@ var AniCraft = (function () { this.lift(this.line, this.w.setText(to.at, String(v))); return v; } + // Another member of a text field (run.rs `LValue::Field`; ADR 0107). + if (to.k === "field") { + let x; + if (to.p === "html_text") { + if (v === null || v === undefined) this.err("`htmlText` is set to text, not " + String(v)); + x = String(v); + } else if (to.p === "max_chars") { + const n = +v; + if (!Number.isFinite(n)) this.err("`maxChars` is set to a number, not " + shown(v)); + x = Math.min(Math.max(Math.trunc(n), 0), 2147483647) + 0; + } else if (to.p === "restrict") x = v === null || v === undefined ? null : String(v); + else this.err("`" + READ_NAMES[to.p] + "` can only be read"); + this.lift(this.line, this.w.setField(to.at, to.p, x)); + return x; + } const n = +v; if (!Number.isFinite(n)) this.err("`" + PROP_NAMES[to.p] + "` is set to a number, not " + shown(v)); this.lift(this.line, this.w.set(to.at, to.p, n)); @@ -1084,6 +1100,19 @@ var AniCraft = (function () { this.r.setFieldText(n.path, text); return undefined; }; + // `field.htmlText = …`, `maxChars`, `restrict` (player.rs `set_field`). + Script.prototype.setField = function (at, p, v) { + if (!this.r.budget()) return null; + const f = this.from(); + if (f.err !== undefined) return f.err; + const i = this.r.place(f.ok, this.ev, at); + if (i.err !== undefined) return i.err; + const n = i.ok === null ? undefined : this.r.nodes[i.ok]; + if (!n) return "the stage isn't a text field"; + if (n.kind !== TEXT) return "“" + n.name + "” is " + kindName(n.kind) + ", not a text field"; + this.r.setFieldMember(n.path, p, v); + return undefined; + }; Script.prototype.trace = function (line) { if (this.r.budget()) this.r.out(line); }; @@ -1180,19 +1209,39 @@ var AniCraft = (function () { return n || null; }; // The viewer changed input field `key`'s text in the page's element: the text the field keeps - // (the element's value as the editor would let it in), or null when there is no such input - // field. No script runs: listeners hear the keys, as they do in the Rust player. + // (the element's value as the editor would let it in: its `maxChars` and `restrict` applied), + // or null when there is no such input field. When the text changed, the field's change event + // runs (ADR 0107) and `this.changed` holds that step's result (its output and sounds), else + // null. Player.prototype.typed = function (key, value) { + this.changed = null; const n = this.fieldNode(key); if (n === null || n.tf.k !== "input") return null; - const v = typedText(n.tf, String(value === null || value === undefined ? "" : value)); let fs = this.st.fields.get(key); if (!fs) { fs = newField(n.path); this.st.fields.set(key, fs); } + const before = fieldValue(fs, n.tf); + const v = typedText(n.tf, String(value === null || value === undefined ? "" : value), fs); + if (fs.rich !== null && v !== before) { + // One edit: the longest common start and end kept (rich_text.rs `diff_chars`). + const a = Array.from(before), b = Array.from(v); + let pre = 0; + while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++; + let suf = 0; + while (suf < Math.min(a.length, b.length) - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++; + fs.rich = { runs: typeIntoRuns(fs.rich.runs, pre, a.length - suf, b.length - suf - pre), paras: editParagraphs(fs.rich.paras, a, pre, a.length - suf, b.slice(pre, b.length - suf)) }; + } fs.text = v; fs.caret = fs.anchor = Array.from(v).length; + if (v !== before) { + const r = new Run(this); + r.refresh(); + r.rememberGraphics(); + r.changed(n.path); + this.changed = r.finish(); + } return v; }; // The keyboard went to field `key` (an input field, or a selectable dynamic one, on the stage @@ -1235,7 +1284,7 @@ var AniCraft = (function () { const kind = (v) => (v === undefined ? "u" : v === null ? "null" : typeof v === "boolean" ? "b" : typeof v === "number" ? "n" : "s"); const vars = Array.from(st.vars.values()).sort((a, b) => comparePaths(a.path, b.path)).map((x) => [x.path, Object.keys(x.v).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).map((k) => [k, kind(x.v[k]) + ":" + String(x.v[k])])]); const stage = st.stage.map((x) => [x.ev, x.owner, x.k]); - const fields = Array.from(st.fields.values()).sort((a, b) => comparePaths(a.path, b.path)).map((f) => [f.path, f.text, f.caret, f.anchor]); + const fields = Array.from(st.fields.values()).sort((a, b) => comparePaths(a.path, b.path)).map((f) => [f.path, f.text, f.caret, f.anchor, f.rich === null ? null : [f.rich.runs.map((r) => [r.n, r.s.font, r.s.size, r.s.bold, r.s.italic, r.s.color, r.s.ls, r.s.u, r.s.url]), f.rich.paras.map((p) => p.al)], f.mx, f.res]); return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, listeners: listeners, stage: stage, vars: vars, hover: st.hover, pressed: st.pressed, down: st.down, fields: fields, focus: st.focus, selecting: st.selecting, shift: st.shift }; }; @@ -1578,13 +1627,24 @@ var AniCraft = (function () { return { ok: "root1" }; case "text": case "length": + case "html_text": + case "max_chars": + case "restrict": return { err: "the main timeline isn't a text field" }; } } - if (p === "text" || p === "length") { + if (p === "text" || p === "length" || p === "html_text" || p === "max_chars" || p === "restrict") { if (n.kind !== TEXT) return { err: "“" + n.name + "” is " + kindName(n.kind) + ", not a text field" }; - const v = fieldValue(st.fields.get(n.key), n.tf); - return { ok: p === "text" ? v : v.length }; + const fs = st.fields.get(n.key); + const v = fieldValue(fs, n.tf); + if (p === "text") return { ok: v }; + if (p === "length") return { ok: v.length }; + if (p === "max_chars") return { ok: fs && fs.mx !== null ? fs.mx : n.tf.mx || 0 }; + if (p === "restrict") return { ok: fs ? fs.res : null }; + // The text's styles as HTML: what a script set, the authored runs while the text is + // the authored one, else the field's own style. + const rich = fieldStyles(fs, n.tf); + return { ok: writeHtml(v, rich.runs, rich.paras) }; } const ov = st.props.get(n.key) || {}; const m = n.local; @@ -1647,9 +1707,9 @@ var AniCraft = (function () { } const node = this.nodes[pl.ok]; if (!node) return; - const ok = event === "enter_frame" ? node.kind !== GRAPHIC : node.kind === BUTTON || node.kind === CLIP; + const ok = event === "enter_frame" ? node.kind !== GRAPHIC : event === "change" ? node.kind === TEXT : node.kind === BUTTON || node.kind === CLIP; if (!ok) { - const why = node.kind === ROOT ? "the main timeline doesn't get pointer events here" : "“" + node.name + "” is " + kindName(node.kind) + "; only buttons and movie clips get pointer events"; + const why = event === "change" ? "“" + node.name + "” is " + kindName(node.kind) + "; only text fields send change events" : node.kind === ROOT ? "the main timeline doesn't get pointer events here" : "“" + node.name + "” is " + kindName(node.kind) + "; only buttons and movie clips get pointer events"; return this.out(what + ": " + why); } let list = st.listeners.get(node.key); @@ -1881,6 +1941,522 @@ var AniCraft = (function () { } }; + + // ----- htmlText (html_text.rs; ADR 0107) ----------------------------------------------------- + // + // A line-by-line port of crates/doc/src/html_text.rs: the small HTML Flash text fields took, + // read into text, runs and paragraphs and written back. A style is { font, size, bold, italic, + // color: [r, g, b] (0 to 255), ls, u, url }; a run { n, s }; a paragraph { al }. Reading is a + // sanitiser: nothing of the input is kept as markup. + const MAX_HTML = 65536; + const MAX_HTML_DEPTH = 64; + const MAX_URL = 2048; + function sameStyle(a, b) { + return a.font === b.font && a.size === b.size && a.bold === b.bold && a.italic === b.italic && a.color[0] === b.color[0] && a.color[1] === b.color[1] && a.color[2] === b.color[2] && a.ls === b.ls && a.u === b.u && a.url === b.url; + } + function copyStyle(s) { + return { font: s.font, size: s.size, bold: s.bold, italic: s.italic, color: [s.color[0], s.color[1], s.color[2]], ls: s.ls, u: s.u, url: s.url }; + } + // A field's own style and first paragraph (the exported `st` and `al`). + function baseStyle(tf) { + const s = tf.st || {}; + const c = s.c || [0, 0, 0]; + return { font: String(s.f || ""), size: Math.fround(s.z || 12), bold: !!s.b, italic: !!s.i, color: [c[0], c[1], c[2]], ls: Math.fround(s.ls || 0), u: !!s.u, url: String(s.url || "") }; + } + function basePara(tf) { + return { al: tf.al || "left" }; + } + function rustTrim(s) { + const cs = Array.from(s); + let a = 0, b = cs.length; + while (a < b && rustSpace(cs[a])) a++; + while (b > a && rustSpace(cs[b - 1])) b--; + return cs.slice(a, b).join(""); + } + const isAlnum = (c) => /^[0-9A-Za-z]$/.test(c); + // rich_text.rs `safe_url`: the link, or null when it could run script. + function safeUrl(url) { + const u = Array.from(rustTrim(url)).filter((c) => !rustControl(c)).slice(0, MAX_URL); + const noSpace = u.filter((c) => !rustSpace(c)); + const colon = noSpace.indexOf(":"); + const scheme = asciiLower((colon < 0 ? noSpace : noSpace.slice(0, colon)).join("")); + const hasScheme = u.indexOf(":") >= 0 && !/[\/?#]/.test(scheme); + return hasScheme && (scheme === "javascript" || scheme === "vbscript" || scheme === "data") ? null : u.join(""); + } + // One entity at the start of `s` (after its `&`): [character or null, characters taken], or + // null when it is no entity. + function htmlEntity(s, from) { + let end = -1; + for (let k = 0; k < 12 && from + k < s.length; k++) { + if (s[from + k] === ";") { + end = k; + break; + } + } + if (end < 0) return null; + const name = s.slice(from, from + end).join(""); + let c; + switch (name) { + case "lt": + c = "<"; + break; + case "gt": + c = ">"; + break; + case "amp": + c = "&"; + break; + case "quot": + c = '"'; + break; + case "apos": + c = "'"; + break; + case "nbsp": + c = " "; + break; + default: { + if (name[0] !== "#") return null; + const digits = name.slice(1); + let code; + if (digits[0] === "x" || digits[0] === "X") { + const hex = digits.slice(1); + if (!/^[0-9A-Fa-f]+$/.test(hex)) return null; + code = parseInt(hex, 16); + } else { + if (!/^[0-9]+$/.test(digits)) return null; + code = Number(digits); + } + if (code > 4294967295) return null; + // A code that isn't a character (or is a control) is dropped, not kept as text. + const ok = code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff); + c = ok ? String.fromCodePoint(code) : null; + if (c !== null && rustControl(c) && c !== "\n" && c !== "\t") c = null; + } + } + return [c, end + 1]; + } + function htmlUnescape(s) { + let out = ""; + let i = 0; + while (i < s.length) { + const c = s[i]; + i += 1; + if (c === "&") { + const e = htmlEntity(s, i); + if (e !== null) { + if (e[0] !== null) out += e[0]; + i += e[1]; + continue; + } + } + out += c; + } + return out; + } + // A tag's name, whether it closes, and its attributes, from what is between `<` and `>`. + function htmlTag(body) { + let i = 0; + const closing = body[0] === "/"; + if (closing) i += 1; + let name = ""; + while (i < body.length && isAlnum(body[i])) { + name += asciiLower(body[i]); + i += 1; + } + const attrs = []; + while (attrs.length < 16) { + while (i < body.length && (rustSpace(body[i]) || body[i] === "/")) i += 1; + let key = ""; + while (i < body.length && !rustSpace(body[i]) && body[i] !== "=" && body[i] !== "/") { + key += asciiLower(body[i]); + i += 1; + } + if (key === "") break; + while (i < body.length && rustSpace(body[i])) i += 1; + const value = []; + if (body[i] === "=") { + i += 1; + while (i < body.length && rustSpace(body[i])) i += 1; + const q = body[i]; + if (q === '"' || q === "'") { + i += 1; + while (i < body.length && body[i] !== q) { + value.push(body[i]); + i += 1; + } + i += 1; + } else { + while (i < body.length && !rustSpace(body[i])) { + value.push(body[i]); + i += 1; + } + } + } + attrs.push([key, htmlUnescape(value)]); + } + return [name, closing, attrs]; + } + // Where a tag's `>` is from `from`: the first one outside a quoted attribute value, or -1. + function htmlTagEnd(src, from) { + let quote = null; + for (let k = from; k < src.length; k++) { + const c = src[k]; + if (quote !== null) { + if (c === quote) quote = null; + } else if (c === '"' || c === "'") quote = c; + else if (c === ">") return k - from; + } + return -1; + } + // A plain decimal number (no exponents, at most 12 characters), as a 32-bit float, or null. + function htmlNumber(str) { + const s = rustTrim(str); + const digits = s[0] === "+" || s[0] === "-" ? s.slice(1) : s; + if (digits === "" || s.length > 12 || !/^[0-9.]+$/.test(digits) || digits.split(".").length > 2 || digits === ".") return null; + const v = Math.fround(Number(s[0] === "+" ? s.slice(1) : s)); + return Number.isFinite(v) ? v : null; + } + function fontTag(style, attrs) { + for (const [k, v] of attrs) { + if (k === "face") { + const face = Array.from(rustTrim(v)).filter((c) => !rustControl(c)).slice(0, 256).join(""); + if (face !== "") style.font = face; + } else if (k === "size") { + const n = htmlNumber(v); + if (n !== null) { + const t = rustTrim(v); + const relative = t[0] === "+" || t[0] === "-"; + style.size = Math.min(Math.max(relative ? Math.fround(style.size + n) : n, 1), 2000); + } + } else if (k === "color") { + const t = rustTrim(v); + if (/^#[0-9A-Fa-f]{6}$/.test(t)) { + const x = parseInt(t.slice(1), 16); + style.color = [(x >> 16) & 255, (x >> 8) & 255, x & 255]; + } + } else if (k === "letterspacing") { + const n = htmlNumber(v); + if (n !== null) style.ls = Math.min(Math.max(n, -1000), 1000); + } + } + } + // html_text.rs `parse`: { text, runs, paras }. + function parseHtml(html, base, para) { + const src = Array.from(html).slice(0, MAX_HTML); + const r = { text: [], runs: [], paras: [], style: copyStyle(base), para: { al: para.al }, closedP: false }; + const push = (c) => { + if (r.text.length >= MAX_FIELD_CHARS) return; + r.text.push(c); + const last = r.runs[r.runs.length - 1]; + if (last && sameStyle(last.s, r.style)) last.n += 1; + else r.runs.push({ n: 1, s: copyStyle(r.style) }); + if (c === "\n") r.paras.push({ al: r.para.al }); + }; + const endParagraph = () => { + if (r.text.length >= MAX_FIELD_CHARS) return; + r.text.push("\n"); + const last = r.runs[r.runs.length - 1]; + if (last) last.n += 1; + else r.runs.push({ n: 1, s: copyStyle(r.style) }); + r.paras.push({ al: r.para.al }); + }; + const textChar = (c) => { + if (c === "\r" || (rustControl(c) && c !== "\n" && c !== "\t")) return; + r.closedP = false; + push(c); + }; + const open = []; + let i = 0; + while (i < src.length) { + const c = src[i]; + i += 1; + if (c === "&") { + const e = htmlEntity(src, i); + if (e !== null) { + i += e[1]; + if (e[0] !== null) textChar(e[0]); + continue; + } + textChar("&"); + continue; + } + if (c !== "<") { + textChar(c); + continue; + } + if (i + 3 <= src.length && src[i] === "!" && src[i + 1] === "-" && src[i + 2] === "-") { + let end = src.length; + for (let k = i + 3; k + 3 <= src.length; k++) { + if (src[k] === "-" && src[k + 1] === "-" && src[k + 2] === ">") { + end = k + 3; + break; + } + } + i = end; + continue; + } + const n0 = src[i]; + const startsTag = n0 !== undefined && (/^[A-Za-z]$/.test(n0) || n0 === "/" || n0 === "!" || n0 === "?"); + const len = startsTag ? htmlTagEnd(src, i) : -1; + if (len < 0) { + textChar("<"); + continue; + } + const [name, closing, attrs] = htmlTag(src.slice(i, i + len)); + i += len + 1; + if ((name === "script" || name === "style") && !closing) { + let end = src.length; + for (let k = i; k < src.length; k++) { + if (src[k] === "<" && src[k + 1] === "/") { + const word = asciiLower(src.slice(k + 2, k + 2 + name.length).join("")); + if (word === name) { + let g = -1; + for (let j = k; j < src.length; j++) { + if (src[j] === ">") { + g = j; + break; + } + } + end = g < 0 ? src.length : g + 1; + break; + } + } + } + i = end; + } else if (name === "br" && !closing) { + r.closedP = false; + push("\n"); + } else if (name === "p" && !closing) { + if (!(r.text.length === 0 || r.text[r.text.length - 1] === "\n")) push("\n"); + r.closedP = false; + r.para = { al: para.al }; + const a = attrs.find((x) => x[0] === "align"); + if (a) { + const v = asciiLower(rustTrim(a[1])); + if (v === "center") r.para.al = "center"; + else if (v === "right") r.para.al = "right"; + else if (v === "left" || v === "justify") r.para.al = "left"; + } + } else if (name === "p") { + endParagraph(); + r.closedP = true; + r.para = { al: para.al }; + } else if (name === "b" || name === "i" || name === "u" || name === "font" || name === "a") { + if (!closing) { + if (open.length >= MAX_HTML_DEPTH) continue; + open.push([name, copyStyle(r.style)]); + if (name === "b") r.style.bold = true; + else if (name === "i") r.style.italic = true; + else if (name === "u") r.style.u = true; + else if (name === "font") fontTag(r.style, attrs); + else { + const a = attrs.find((x) => x[0] === "href"); + const url = safeUrl(a ? a[1] : ""); + r.style.url = url === null ? "" : url; + } + } else { + let k = -1; + for (let j = open.length - 1; j >= 0; j--) { + if (open[j][0] === name) { + k = j; + break; + } + } + if (k >= 0) { + r.style = open[k][1]; + open.length = k; + } + } + } + } + if (r.closedP && r.text[r.text.length - 1] === "\n") { + r.text.pop(); + const last = r.runs[r.runs.length - 1]; + if (last) { + last.n -= 1; + if (last.n === 0) r.runs.pop(); + } + const p = r.paras.pop(); + r.para = p || { al: para.al }; + } + r.paras.push({ al: r.para.al }); + if (r.runs.length === 0) r.runs.push({ n: 0, s: copyStyle(base) }); + return { text: r.text.join(""), runs: r.runs, paras: r.paras }; + } + // A number as HTML attributes hold it: two decimals at most. + function attrNumber(v) { + return rustNum(Math.floor((Number.isFinite(v) ? v : 0) * 100 + 0.5) / 100); + } + function htmlEscape(s, attr) { + let out = ""; + for (const c of s) { + if (c === "<") out += "<"; + else if (c === ">") out += ">"; + else if (c === "&") out += "&"; + else if (c === '"' && attr) out += """; + else if (c === " ") out += " "; + else out += c; + } + return out; + } + const hex2 = (v) => (v < 16 ? "0" : "") + v.toString(16); + // html_text.rs `write`. + function writeHtml(text, runs, paras) { + let out = ""; + const chars = Array.from(text); + const lastStyle = runs.length > 0 ? runs[runs.length - 1].s : baseStyle({}); + let run = 0, left = runs.length > 0 ? runs[0].n : 0; + const nextRun = () => { + while (run < runs.length && left <= 0) { + run += 1; + left = run < runs.length ? runs[run].n : 0; + } + if (run >= runs.length) return Math.max(runs.length - 1, 0); + left -= 1; + return run; + }; + let line = []; + let para = 0; + const flush = () => { + const p = paras[para] || paras[paras.length - 1]; + out += '

      '; + let i = 0; + while (i < line.length) { + const k = line[i][0]; + const st = runs[k] ? runs[k].s : lastStyle; + out += ''; + if (st.bold) out += ""; + if (st.italic) out += ""; + if (st.u) out += ""; + let piece = ""; + while (i < line.length && line[i][0] === k) { + piece += line[i][1]; + i += 1; + } + out += htmlEscape(piece, false); + if (st.u) out += ""; + if (st.italic) out += ""; + if (st.bold) out += ""; + if (st.url !== "") out += ""; + out += ""; + } + out += "

      "; + line = []; + }; + for (const c of chars) { + const k = nextRun(); + if (c === "\n") { + flush(); + para += 1; + } else line.push([k, c]); + } + flush(); + return out; + } + // rich_text.rs: `style_at`, `slice_runs`, `normalize_runs`, `replace_runs`, `type_into_runs`. + function styleAt(runs, at) { + let end = 0; + for (const r of runs) { + end += r.n; + if (at <= end && (at > end - r.n || at === 0)) return r.s; + } + return runs.length > 0 ? runs[runs.length - 1].s : baseStyle({}); + } + function sliceRuns(runs, start, end) { + const out = []; + let at = 0; + for (const r of runs) { + const a = Math.max(at, start), b = Math.min(at + r.n, end); + if (a < b) out.push({ n: b - a, s: r.s }); + at += r.n; + if (at >= end) break; + } + return out; + } + function normalizeRuns(runs, n) { + const fallback = runs.length > 0 ? runs[0].s : baseStyle({}); + // fit_runs: the last runs cut or the last one lengthened. + let at = 0, keep = 0; + const fitted = []; + for (const r of runs) { + if (at >= n && keep > 0) break; + const len = Math.min(r.n, n - at); + fitted.push({ n: len, s: r.s }); + at += len; + keep += 1; + } + if (fitted.length > 0) fitted[fitted.length - 1].n += n - Math.min(at, n); + const out = []; + for (const r of fitted) { + if (r.n === 0) continue; + const last = out[out.length - 1]; + if (last && (sameStyle(last.s, r.s) || out.length >= 10000)) last.n += r.n; + else out.push(r); + } + if (out.length === 0) out.push({ n: n, s: fallback }); + return out; + } + function typeIntoRuns(runs, start, end, inserted) { + const style = styleAt(runs, start); + const total = runs.reduce((s, r) => s + r.n, 0); + const a = Math.min(start, total), b = Math.min(Math.max(end, a), total); + const out = sliceRuns(runs, 0, a).concat([{ n: inserted, s: style }], sliceRuns(runs, b, total)); + const n = out.reduce((s, r) => s + r.n, 0); + return normalizeRuns(out, n); + } + // rich_text.rs `edit_paragraphs` (`old` and `inserted` as arrays of characters). + function editParagraphs(paras, old, start, end, inserted) { + const count = old.filter((c) => c === "\n").length + 1; + const fill = paras.length > 0 ? paras[paras.length - 1] : { al: "left" }; + const full = []; + for (let i = 0; i < count; i++) full.push(paras[i] || fill); + const before = old.slice(0, start).filter((c) => c === "\n").length; + const removed = old.slice(start, Math.max(end, start)).filter((c) => c === "\n").length; + const added = inserted.filter((c) => c === "\n").length; + const here = full[before] || fill; + let out = full.slice(0, before + 1); + for (let i = 0; i < added; i++) out.push(here); + out = out.concat(full.slice(before + 1 + removed)); + return out; + } + // field.rs `allowed`: whether `restrict` lets a viewer type `c`. + function restrictAllows(restrict, c) { + const r = Array.from(restrict).slice(0, 1024); + let ok = r[0] === "^"; + let include = true; + let i = 0; + const item = (k) => { + if (k >= r.length) return null; + if (r[k] === "\\") return k + 1 < r.length ? [r[k + 1], k + 2] : null; + return [r[k], k + 1]; + }; + const cp = c.codePointAt(0); + while (i < r.length) { + if (r[i] === "^") { + include = !include; + i += 1; + continue; + } + const lo = item(i); + if (lo === null) break; + i = lo[1]; + let hi = lo[0]; + if (r[i] === "-") { + const e = item(i + 1); + if (e !== null) { + hi = e[0]; + i = e[1]; + } + } + if (cp >= lo[0].codePointAt(0) && cp <= hi.codePointAt(0)) ok = include; + } + return ok; + } + // ----- text fields (player.rs, field.rs; ADR 0066) ------------------------------------------- // // In the browser the viewer types into a real or