From c1b5941f126522aeac918c0fe23addba01f8033d Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 12:59:03 -0700 Subject: [PATCH 1/4] fix(xfl): one damaged part no longer refuses a .fla, white default stage, the CLI opens Animate files (M8) Since 0.1 the importer reads bitmaps, sounds and the publish settings from the package with `?`, so one entry failing its checksum or the archive's limits refused the whole document (#226). Optional parts are now left out and reported; damage to DOMDocument.xml still refuses the file. Animate omits the default white backgroundColor, which imported as black (#163). anicraft-cli info/render/exports open .fla/.xfl through file.open. Tests: damaged bitmap/symbol parts (fail before the fix), white stage, every entry point (file.open, upper-case .FLA, Open Recent, drop routing, browser vfs) over the corpus, CLI subcommands. --- crates/cli/src/lib.rs | 17 ++++++++++ crates/engine/src/lib.rs | 3 ++ crates/engine/tests/xfl_corpus.rs | 53 +++++++++++++++++++++++++++++++ crates/xfl/src/import.rs | 50 +++++++++++++++++++++++------ crates/xfl/src/tests.rs | 12 +++++++ crates/xfl/tests/fla.rs | 49 ++++++++++++++++++++++++++-- packaging/web/package.sh | 31 ++++++++++++++++++ 7 files changed, 202 insertions(+), 13 deletions(-) create mode 100755 packaging/web/package.sh diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index cb9ef155..d87ab681 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -77,6 +77,12 @@ pub fn open_session(src: Option<&str>) -> Result { match src { None => Ok(Session::default()), Some("--sample") => Ok(Session::new(anicraft_doc::sample::demo())), + // An Animate document imports as File › Open does (#226), untitled. + Some(p) if anicraft_engine::is_animate(std::path::Path::new(p)) => { + let mut s = Session::default(); + s.execute("file.open", &serde_json::json!({"path": p})).map_err(|e| e.to_string())?; + Ok(s) + } Some(p) => { let doc = format::load(std::path::Path::new(p)).map_err(|e| format!("{p}: {e}"))?; let mut s = Session::new(doc); @@ -478,6 +484,17 @@ pub fn serve(s: &mut Session, input: R, out: &mut W) -> st mod tests { use super::*; + /// #226: `info`, `render` and the other subcommands take an Animate document as File › Open + /// does (an import, untitled), not only `.anicraft` files. + #[test] + fn subcommands_open_animate_documents() { + let xfl = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus/shapes/shapes.xfl"); + let s = open_session(Some(&xfl.display().to_string())).unwrap(); + assert!(s.path.is_none() && !s.doc.timeline(0).layers.is_empty()); + let info = run(&["info".to_string(), xfl.display().to_string()]).unwrap(); + assert!(info.contains("\"layers\""), "{info}"); + } + #[test] fn serve_round_trip() { let mut s = Session::default(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3ed9ed55..57336dcf 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -67,6 +67,9 @@ pub use anicraft_plugins as plugins; pub use anicraft_text as text; pub use anicraft_geom as geom; pub use anicraft_render as render; +/// Whether a path is an Animate document (`.fla`, `.xfl`, or an XFL folder) that `file.open` +/// imports. +pub use cmds_file::is_animate; #[derive(Debug, thiserror::Error)] pub enum EngineError { diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index 1ee72873..b94ff16f 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -285,3 +285,56 @@ fn every_package_opens_from_a_fla_with_the_same_golden_frames() { {}", failures.len(), failures.join(" ")); } + +/// #226: each package as a `.fla` opens as the same document through every way in: File › Open, +/// the command line and a document the system hands over (all `file.open`), Open Recent and the +/// start screen's list (`file.open_recent`), a drop anywhere on the window (routed to +/// `file.open`), an upper-case extension, and a file a web browser hands over (`vfs`). +#[test] +fn every_entry_point_opens_the_corpus_as_a_fla() { + use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-entry-points"); + std::fs::create_dir_all(&dir).unwrap(); + for (case, _) in FRAMES { + let mut s = Session::default(); + s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); + let bytes = pack::pack(&pack::package(&corpus().join(case)), &pack::VARIANTS[0]); + let fla = dir.join(format!("{case}.fla")); + std::fs::write(&fla, &bytes).unwrap(); + let upper = dir.join(format!("{case} COPY.FLA")); + std::fs::write(&upper, &bytes).unwrap(); + let open = |path: &Path| { + let mut t = Session::default(); + t.execute("file.open", &json!({"path": path.display().to_string()})).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + t + }; + for path in [&fla, &upper] { + let t = open(path); + assert!(t.doc == s.doc, "{}: opens differently from its folder", path.display()); + assert!(t.path.is_none(), "{case}: imported untitled, so Save never writes over the Animate file"); + } + // Open Recent reopens the Animate file it imported. + let mut t = open(&fla); + t.execute("file.new", &json!({})).unwrap(); + t.execute("file.open_recent", &json!({"index": 0, "confirm": true})).unwrap_or_else(|e| panic!("{case}: Open Recent: {e}")); + assert!(t.doc == s.doc, "{case}: Open Recent opens it the same"); + // A drop anywhere opens it. + for path in [&fla, &upper] { + assert_eq!(kind_of(path), DropKind::Document, "{}", path.display()); + for target in [DropTarget::Stage, DropTarget::Timeline, DropTarget::Library, DropTarget::Window] { + assert_eq!(route(kind_of(path), target), DropAction::Open, "{case} on {target:?}"); + } + } + // In a browser the file arrives in memory, on the thread that opens it (ADR 0036). + let (name, data, want) = (format!("{case}.fla"), bytes.clone(), s.doc.clone()); + std::thread::spawn(move || { + anicraft_engine::vfs::use_memory(); + anicraft_engine::vfs::put(Path::new(&name), data).unwrap(); + let mut w = Session::default(); + w.execute("file.open", &json!({"path": name})).unwrap_or_else(|e| panic!("{name} in a browser: {e}")); + assert!(w.doc == want, "{name}: opens differently in a browser"); + }) + .join() + .unwrap(); + } +} diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 08f0d432..8f76060c 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -713,10 +713,19 @@ impl<'a> Builder<'a> { candidates.push(format!("bin/{data}")); } let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(256).collect(); - let mut found_data = false; + let (mut found_data, mut unreadable) = (false, false); let mut bitmap = None; for path in candidates { - let Some(bytes) = (self.read)(&path)? else { continue }; + let bytes = match (self.read)(&path) { + Ok(Some(bytes)) => bytes, + Ok(None) => continue, + // Damaged or over the archive's limits: this bitmap is left out, not + // the whole document (#226). + Err(_) => { + unreadable = true; + continue; + } + }; found_data = true; if let Ok(b) = Bitmap::from_image(BitmapId(0), short.clone(), bytes) { bitmap = Some(b); @@ -733,6 +742,7 @@ impl<'a> Builder<'a> { self.doc.bitmaps.push(Arc::new(b)); } None if found_data => self.report.skip("bitmaps stored in Animate's own format"), + None if unreadable => self.report.skip("bitmaps whose files couldn't be read"), None => self.report.skip("missing bitmap files"), } } @@ -754,10 +764,19 @@ impl<'a> Builder<'a> { candidates.push(format!("bin/{data}")); } let short: String = name.rsplit('/').next().unwrap_or(name).chars().take(256).collect(); - let mut found_data = false; + let (mut found_data, mut unreadable) = (false, false); let mut sound = None; for path in candidates { - let Some(bytes) = (self.read)(&path)? else { continue }; + let bytes = match (self.read)(&path) { + Ok(Some(bytes)) => bytes, + Ok(None) => continue, + // Damaged or over the archive's limits: this sound is left out, not + // the whole document (#226). + Err(_) => { + unreadable = true; + continue; + } + }; found_data = true; if let Ok(s) = anicraft_doc::Sound::from_data(anicraft_doc::SoundId(0), short.clone(), bytes) { sound = Some(s); @@ -772,6 +791,7 @@ impl<'a> Builder<'a> { self.doc.sounds.push(Arc::new(s)); } None if found_data => self.report.skip("sounds stored in Animate's own format"), + None if unreadable => self.report.skip("sounds whose files couldn't be read"), None => self.report.skip("missing sound files"), } } @@ -812,11 +832,19 @@ impl<'a> Builder<'a> { if !seen.insert(href.to_string()) { continue; } - let Some(bytes) = (self.read)(&format!("LIBRARY/{href}"))? else { - self.report.skip("missing library files"); - continue; + // 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, + Ok(None) => { + self.report.skip("missing library files"); + continue; + } + Err(_) | Ok(Some(Err(_))) => { + self.report.skip("library files that couldn't be read"); + continue; + } }; - let item = xml::parse(&bytes)?; if item.name != "DOMSymbolItem" { continue; } @@ -879,7 +907,8 @@ impl<'a> Builder<'a> { /// used, else the first. A missing or unreadable file changes nothing: it is settings, not /// content. fn publish_settings(&mut self) -> Result<(), XflError> { - let Some(bytes) = (self.read)("PublishSettings.xml")? else { return Ok(()) }; + // 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); @@ -964,7 +993,8 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do width: root.f32("width").unwrap_or(550.0).clamp(1.0, 8192.0) as u32, height: root.f32("height").unwrap_or(400.0).clamp(1.0, 8192.0) as u32, fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0), - background: color(&root, "backgroundColor", "__none"), + // Animate leaves the default, white, out of the file (#163). + background: if root.attr("backgroundColor").is_some() { color(&root, "backgroundColor", "__none") } else { Rgba::WHITE }, }; b.register_folders(&root); b.register_bitmaps(&root)?; diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 362ef090..a4b78ad2 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -565,3 +565,15 @@ fn sounds_in_the_package_come_across_on_frames_and_buttons_states() { let s = input(&doc, &s.state, &[Event::Move(anicraft_geom::Vec2::new(10.0, 10.0))], &mut NoScripts); assert_eq!(s.sounds.iter().map(|x| x.sound.sound).collect::>(), [click]); } + +/// #163: Animate leaves the default stage colour (white) out of `DOMDocument.xml`, so a file +/// without `backgroundColor` has a white stage, not a black one. +#[test] +fn a_document_without_a_background_colour_has_a_white_stage() { + let read = |p: &str| -> Result>, XflError> { + Ok((p == "DOMDocument.xml").then(|| br#""#.to_vec())) + }; + let (doc, _) = import_with(&read).unwrap(); + assert_eq!(doc.stage.background, Rgba::WHITE); + assert_eq!((doc.stage.width, doc.stage.height), (550, 400), "Animate's default size, also left out"); +} diff --git a/crates/xfl/tests/fla.rs b/crates/xfl/tests/fla.rs index 5953447f..5f716804 100644 --- a/crates/xfl/tests/fla.rs +++ b/crates/xfl/tests/fla.rs @@ -102,6 +102,46 @@ fn an_old_binary_fla_says_what_to_do() { assert_eq!(e, "not a zip archive (no end-of-directory record)"); } +/// #226: one damaged part the document can do without (a bitmap's file, a library symbol) is +/// left out and reported, and everything else opens, as it did before AniCraft read those +/// parts; damage to `DOMDocument.xml` still refuses the file. +#[test] +fn damaged_parts_are_left_out_not_the_whole_document() { + let fonts = no_fonts(); + let open = |case: &str, damage: &dyn Fn(&mut pack::Raw) -> bool| { + let files = pack::package(&corpus().join(case)); + let (whole, _) = from_folder(&files, &fonts); + let mut entries = pack::entries(&files, &pack::VARIANTS[0]); + let hit = entries.iter_mut().map(damage).filter(|d| *d).count(); + assert_eq!(hit, 1, "{case}: one entry damaged"); + (whole, import_fla_with_fonts(&pack::write(&entries, false), &fonts)) + }; + let named = |e: &pack::Raw, f: &dyn Fn(&str) -> bool| f(&String::from_utf8_lossy(&e.name)); + + // A bitmap whose bytes fail their checksum. + let (whole, got) = open("bitmaps", &|e| named(e, &|n| n.ends_with("checker.png")) && e.crc.replace(1).is_none()); + let (doc, report) = got.expect("the document opens without the damaged bitmap"); + assert_eq!(doc.bitmaps.len() + 1, whole.bitmaps.len(), "only the damaged bitmap is left out"); + assert_eq!(report.skipped.get("bitmaps whose files couldn't be read"), Some(&1), "{:?}", report.skipped); + assert!(report.summary().contains("bitmaps whose files couldn't be read"), "{}", report.summary()); + + // A library symbol whose file is cut short (malformed XML), and one that lies about its size. + for (how, damage) in [ + ("malformed", &(|e: &mut pack::Raw| named(e, &|n| n.ends_with("Dot.xml")) && { e.body.truncate(e.body.len() / 2); true }) as &dyn Fn(&mut pack::Raw) -> bool), + ("a lying size", &|e: &mut pack::Raw| named(e, &|n| n.ends_with("Dot.xml")) && e.size.replace(3).is_none()), + ] { + let (whole, got) = open("symbols", damage); + let (doc, report) = got.unwrap_or_else(|e| panic!("{how}: the document opens without the damaged symbol: {e}")); + assert_eq!(doc.library.len() + 1, whole.library.len(), "{how}"); + assert_eq!(report.skipped.get("library files that couldn't be read"), Some(&1), "{how}: {:?}", report.skipped); + assert_eq!(doc.scenes.len(), whole.scenes.len(), "{how}"); + } + + // The document itself damaged: refused, with a readable reason. + let (_, got) = open("symbols", &|e| named(e, &|n| n == "DOMDocument.xml") && e.crc.replace(1).is_none()); + assert!(got.err().unwrap().to_string().contains("checksum")); +} + /// A small deterministic generator (xorshift64*). struct Rng(u64); impl Rng { @@ -223,6 +263,9 @@ fn hostile_fla_archives_never_panic_and_fail_readably() { // Built hostile: names that leave the package, duplicates, overlaps, lying sizes. let mut entries = pack::entries(&files, &pack::VARIANTS[0]); let last = entries.len() - 1; + // Damage to the document itself refuses the archive; damage to an optional part (a + // bitmap, a symbol) leaves only that part out (`damaged_parts_are_left_out_…`). + let doc = entries.iter().position(|e| e.name == b"DOMDocument.xml").unwrap(); let edits: Vec<(&str, Edit)> = vec![ ("a .. name", Box::new(move |e| e[last].name = b"LIBRARY/../../../x.xml".to_vec())), ("an absolute name", Box::new(move |e| e[last].name = b"/etc/x.xml".to_vec())), @@ -239,9 +282,9 @@ fn hostile_fla_archives_never_panic_and_fail_readably() { d.share = Some(1); e.push(d); })), - ("a lying size", Box::new(|e| e[1].size = Some(3))), - ("a lying checksum", Box::new(|e| e[1].crc = Some(1))), - ("a ratio bomb", Box::new(|e| e[1].size = Some(200 << 20))), + ("a lying size", Box::new(move |e| e[doc].size = Some(3))), + ("a lying checksum", Box::new(move |e| e[doc].crc = Some(1))), + ("a ratio bomb", Box::new(move |e| e[doc].size = Some(200 << 20))), ("deep folders", Box::new(|e| e[1].name = "d/".repeat(200).into_bytes())), ]; for (what, edit) in &edits { diff --git a/packaging/web/package.sh b/packaging/web/package.sh new file mode 100755 index 00000000..813c8c8e --- /dev/null +++ b/packaging/web/package.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# The web editor as a release download (#210, ADR 0036, docs/web.md): +# +# $DIST/anicraft-web-.zip +# +# a static site (index.html, the loader, the module, the icon and the user guide) to unzip onto +# any web server. This is the app's side of the family release workflow's web job +# (storytold/craft-common-actions, `has-web`), which runs this script and uploads +# dist/release/*; the Web CI job runs it too, so it never breaks unnoticed. +# +# Builds with scripts/build-web.sh; installs the wasm-bindgen CLI at the version Cargo.lock pins +# when it is missing (the release runner has only Rust and the wasm32 target). +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +cd "$ROOT" + +WANT="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)" +if ! command -v wasm-bindgen >/dev/null || [[ "$(wasm-bindgen --version | awk '{ print $2 }')" != "$WANT" ]]; then + cargo install wasm-bindgen-cli --version "$WANT" --locked +fi + +scripts/build-web.sh +for f in index.html anicraft.js anicraft_bg.wasm anicraft.png guide/index.html; do + [[ -s "web/$f" ]] || { echo "error: web/$f is missing or empty" >&2; exit 1; } +done + +ZIP="$DIST/anicraft-web-$VERSION.zip" +rm -f "$ZIP" +(cd web && zip -q -r -X "$ZIP" .) +echo "$ZIP: $(( $(wc -c <"$ZIP" | tr -d ' ') / 1024 )) KB" From 1d5b9e1e0cbe2aeb56a97295346a0c88411225ad Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 12:59:04 -0700 Subject: [PATCH 2/4] fix(ui): start-up falls back instead of exiting, a start-up log, window graphics choice, full selection shading (M8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit wgpu automatic, DX12 on the low-power GPU on Windows, OpenGL), each under catch_unwind; a crash marker makes the next start try a way that died in a driver last; Logs/anicraft.log records attempts, adapter, driver, panics and slow starts; a message box names it when nothing works. --renderer dx12, vulkan and metal now select that interface (#255), also in Preferences › Stage › Window graphics. A command-line file that can't open says why in the status bar (#226). row by row from the top, so a big or zoomed-in shape stopped being shaded part way down. Fills and wide strokes are now exact per-row spans (active edge list, fill rule aware) textured with a repeating dot tile: a full 4K view is 721 spans instead of ~920 000 dots. --- src/app.rs | 13 ++ src/dialogs.rs | 20 ++++ src/gpu_stage.rs | 11 +- src/i18n/tests.rs | 2 + src/main.rs | 102 +++++++++++----- src/platform.rs | 65 ++++++++-- src/prefs.rs | 43 +++++++ src/stage.rs | 296 ++++++++++++++++++++++++++++++++++----------- src/startup.rs | 297 ++++++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 740 insertions(+), 109 deletions(-) create mode 100644 src/startup.rs diff --git a/src/app.rs b/src/app.rs index abd4f206..546da656 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1059,6 +1059,17 @@ impl App { crate::movie_explorer::expand_to(self, 3); } Some("about") => self.show_about = true, + Some("selectzoom") => { + // #204: a raw rectangle with a wide outline, selected and zoomed in far past the + // window: the selection pattern covers all of it, down to the bottom. + self.run("layer.new", json!({})); + self.run("draw.rect", json!({"x": 60, "y": 40, "w": 840, "h": 460, "fill": "#e8594f", "stroke": "#7a1f1a", "stroke_width": 24, "object": false})); + self.run("edit.select_all", json!({})); + self.tool = Tool::Select; + self.view.fit = false; + self.view.zoom = 4.0; + self.view.pan = egui::vec2(1820.0, 1030.0); + } Some("zoom") => { // 300% on the ball: many tiles, edges cross shapes (seam check). self.view.fit = false; @@ -2850,6 +2861,8 @@ impl eframe::App for App { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.frame(ui); + // A few frames drawn: the window started (#207). + crate::startup::frame(); } } diff --git a/src/dialogs.rs b/src/dialogs.rs index 25440bcf..927d25d8 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -511,6 +511,26 @@ fn preferences(app: &mut App, ctx: &egui::Context) { form_note(ui, LW, text(Type::Caption, s)); } } + // How the window itself is drawn (#207, #255): read when AniCraft starts. + let backends = crate::platform::window_backends(crate::platform::OS); + if !backends.is_empty() { + ui.add_space(4.0); + form_row(ui, LW, tr!("Window graphics"), |ui| { + ui.vertical(|ui| { + for &choice in backends { + let (name, tip) = choice.describe(); + crate::theme::radio_value(ui, &mut p.window_backend, choice, text(Type::Body, crate::i18n::t(name))); + form_note(ui, toggle_indent, text(Type::Caption, crate::i18n::t(tip))); + ui.add_space(2.0); + } + }); + }); + form_note(ui, LW, text(Type::Caption, tr!("A change takes effect the next time AniCraft starts. If a way doesn't work, AniCraft starts with the next one."))); + if let Some(log) = crate::startup::log_path() { + form_note(ui, LW, text(Type::Caption, tr!("If AniCraft has trouble starting, this start-up log says why (attach it to a bug report):"))); + form_note(ui, LW, text(Type::Path, log.display().to_string())); + } + } }); section(ui, "prefs_timeline", Section::Rule, tr!("Timeline"), None, |ui| { diff --git a/src/gpu_stage.rs b/src/gpu_stage.rs index fc7ea519..142dde27 100644 --- a/src/gpu_stage.rs +++ b/src/gpu_stage.rs @@ -157,14 +157,21 @@ mod imp { { self.starting = None; match r { - Ok(g) => self.renderer = Some(Arc::new(g)), - Err(e) => self.state = State::Failed(e), + Ok(g) => { + crate::startup::line(&format!("stage on the GPU: {}", g.adapter)); + self.renderer = Some(Arc::new(g)); + } + Err(e) => { + crate::startup::line(&format!("the stage is drawn on the CPU: {e}")); + self.state = State::Failed(e); + } } } if let Some(g) = &self.renderer && let Some(e) = g.broken() { self.renderer = None; + crate::startup::line(&format!("the GPU stage stopped, the CPU draws: {e}")); self.state = State::Failed(e); } if want && self.renderer.is_none() && self.starting.is_none() && !matches!(self.state, State::Failed(_)) { diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 2e952094..5b08021d 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -55,6 +55,8 @@ fn without_tests(src: &str) -> String { const NOT_UI: &[&str] = &[ "eprintln!(", "println!(", "print!(", "panic!(", "assert", "unreachable!(", "Id::new(", "id_salt(", "persistent_id(", "json!(", "execute(", "perform(", "invoke(", ".run(", "find_command(", "#[", "env!(", "include_str!(", "include_bytes!(", "concat!(", "var(", "contains(", "starts_with(", "ends_with(", "strip_prefix(", "strip_suffix(", "matches!(", "== ", "!= ", + // The start-up log (`startup::line`): English, like console messages, for bug reports. + "line(&", "write(&format!(", ]; /// Whether a prose literal outside the macros is allowed: not interface text by its context, diff --git a/src/main.rs b/src/main.rs index 0330beaf..d772932d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -62,6 +62,7 @@ mod shape_hints; mod stage; mod stage_a11y; mod start; +mod startup; mod templates; mod test_movie; mod theme; @@ -75,24 +76,37 @@ use anicraft_engine::Session; #[cfg(not(target_arch = "wasm32"))] use std::path::{Path, PathBuf}; -/// The session to start with: the file given on the command line (through `file.open`, so -/// `.fla` / `.xfl` import works the same as from the menu), else the sample. Also the import -/// report of an Animate document, for the status bar. +/// What opening the command line's file said, for the status bar. #[cfg(not(target_arch = "wasm32"))] -fn open_session(file: Option<&Path>) -> (Session, Option) { - let Some(p) = file else { return (Session::new(anicraft_engine::doc::sample::demo()), None) }; +#[derive(Debug, PartialEq)] +enum Opened { + /// Nothing to report (no file, or an AniCraft document). + Quiet, + /// The import report of an Animate document. + Imported(String), + /// It didn't open (the sample is there instead): the file's name and why. + Failed(String, String), +} + +/// The session to start with: the file given on the command line (through `file.open`, so +/// `.fla` / `.xfl` import works the same as from the menu), else the sample. A file that can't +/// be opened says why in the window (#226: a release build has no console, so the reason used +/// to go nowhere and a double-clicked document seemed to open as the sample). +#[cfg(not(target_arch = "wasm32"))] +fn open_session(file: Option<&Path>) -> (Session, Opened) { + let Some(p) = file else { return (Session::new(anicraft_engine::doc::sample::demo()), Opened::Quiet) }; let mut s = Session::default(); match s.execute("file.open", &serde_json::json!({"path": p.display().to_string()})) { - Ok(v) => { - let report = v.get("report").and_then(|r| r.as_str()).map(str::to_string); - if let Some(r) = &report { - println!("{r}"); + Ok(v) => match v.get("report").and_then(|r| r.as_str()) { + Some(r) => { + startup::line(&format!("imported {}: {r}", p.display())); + (s, Opened::Imported(r.to_string())) } - (s, report) - } + None => (s, Opened::Quiet), + }, Err(e) => { - eprintln!("could not open {}: {e}; starting with the sample", p.display()); - (Session::new(anicraft_engine::doc::sample::demo()), None) + startup::line(&format!("could not open {}: {e}; starting with the sample", p.display())); + (Session::new(anicraft_engine::doc::sample::demo()), Opened::Failed(crate::recent::display_name(p), e.to_string())) } } } @@ -112,12 +126,11 @@ struct Look { } #[cfg(not(target_arch = "wasm32"))] -fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, open: Option, look: Look) -> eframe::Result { - let options = eframe::NativeOptions { +fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option, open: Option, look: Look) -> eframe::Result { + let options = attempt.options(eframe::NativeOptions { viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])), - renderer, ..Default::default() - }; + }); // The embedded interface font joins the text library before anything lays text out: // opening an Animate document from the command line lays its text out right here. anicraft_engine::text::Fonts::register(theme::embedded_fonts()); @@ -131,6 +144,7 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o Box::new(move |cc| { // A document the system hands over while AniCraft is idle wakes it (ADR 0062). platform::wake_on_requests(&cc.egui_ctx); + startup::log_adapter(cc.wgpu_render_state.as_ref()); let starting_fresh = file_given.is_none() && shot.is_none(); let mut a = app::App::new(cc, session, shot); if let Some(s) = a.shot.as_mut() { @@ -145,9 +159,11 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o } a.preview_look(&cc.egui_ctx, look.theme, look.scale); a.open_panel(open.as_deref()); - // An imported document says what came across, as opening it from the menu does. - if let Some(r) = report { - a.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)); + match report { + // An imported document says what came across, as opening it from the menu does. + Opened::Imported(r) => a.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)), + Opened::Failed(name, e) => a.status_err(tr!("Could not open {name}: {e}", name = name, e = e)), + Opened::Quiet => {} } Ok(Box::new(a)) }), @@ -227,8 +243,8 @@ 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|softmask|pathtext|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\ +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|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|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\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\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ @@ -269,17 +285,32 @@ fn main() -> eframe::Result { // from before the event loop starts until it ends (ADR 0062). let _documents = platform::listen_for_documents(); - // wgpu first (Vulkan/Metal/DX12). If it cannot start (old GPU, VM, missing drivers, common - // on some Linux setups) retry once with OpenGL, unless the user forced a backend. - let forced = platform::forced_renderer(renderer.as_deref()); - let first = forced.unwrap_or(eframe::Renderer::Wgpu); - match run(first, file.as_deref(), shot.clone(), open.clone(), look.clone()) { - Err(e) if forced.is_none() && first == eframe::Renderer::Wgpu => { - eprintln!("GPU backend (wgpu) failed to start: {e}. Retrying with OpenGL."); - run(eframe::Renderer::Glow, file.as_deref(), shot, open, look) + // The window: the graphics asked for, then this platform's order down to OpenGL. A way that + // fails or panics before the window is up falls through to the next; a start that died + // inside a driver last time tries that way last (#207, `startup`). + let died_in = startup::begin(platform::log_dir()); + let attempts = startup::plan(platform::forced_backend(renderer.as_deref()), prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), died_in.as_deref()); + let mut why = String::from("no attempt"); // i18n-exempt: log text + for (n, attempt) in attempts.iter().enumerate() { + startup::trying(attempt, n + 1, attempts.len()); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone()))); + why = match result { + Ok(Ok(())) => { + startup::line("closed"); + return Ok(()); + } + Ok(Err(e)) => e.to_string(), + Err(p) => format!("{} panicked: {}", attempt.label(), startup::panic_text(p.as_ref())), // i18n-exempt: a log line + }; + startup::line(&format!("{} failed: {why}", attempt.label())); + // It ran and then stopped: not a start-up problem, and opening a second window would + // surprise (autosave offers the work back next time). + if startup::started() { + return Err(eframe::Error::AppCreation(why.into())); } - other => other, } + startup::give_up(&why); + Err(eframe::Error::AppCreation(why.into())) } #[cfg(test)] @@ -317,8 +348,15 @@ mod args_tests { assert_eq!(opened.path.as_deref(), Some(path.as_path())); assert!(opened.doc == s.doc, "the document on the command line, not the sample"); // A file that isn't there: the sample, never a crash. - let (fallback, _) = open_session(Some(&dir.join("missing.anicraft"))); + let (fallback, said) = open_session(Some(&dir.join("missing.anicraft"))); assert!(fallback.path.is_none()); + // #226: and the window says why (a release build has no console to print it on). + assert!(matches!(&said, Opened::Failed(name, why) if name == "missing.anicraft" && !why.is_empty()), "{said:?}"); + // An Animate document double-clicked or opened with AniCraft imports, with its report. + let xfl = Path::new(env!("CARGO_MANIFEST_DIR")).join("crates/xfl/tests/corpus/shapes/shapes.xfl"); + let (imported, said) = open_session(Some(&xfl)); + assert!(matches!(said, Opened::Imported(_)), "{said:?}"); + assert!(imported.path.is_none() && !imported.doc.timeline(0).layers.is_empty()); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/src/platform.rs b/src/platform.rs index d1ca41c5..b4a1dce8 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -5,6 +5,7 @@ //! The web build (ADR 0036) is one more platform: the browser's file picker and downloads take //! the dialogs' place, its storage the settings folder's, and the glue lives in `web.rs`. +use crate::prefs::WindowBackend; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; @@ -539,17 +540,52 @@ pub fn is_system_argument(arg: &str) -> bool { arg.starts_with("-psn_") } -/// Renderer requested by `--renderer` / `ANICRAFT_RENDERER` (`wgpu` or `gl`), if any. +/// The window's graphics asked for by `--renderer` / `ANICRAFT_RENDERER`, if any: `gl`, +/// `wgpu` (automatic), `vulkan`, `dx12` or `metal`. Before #207 the last three all meant `wgpu`. #[cfg(not(target_arch = "wasm32"))] -pub fn forced_renderer(arg: Option<&str>) -> Option { +pub fn forced_backend(arg: Option<&str>) -> Option { let v = arg.map(str::to_owned).or_else(|| std::env::var("ANICRAFT_RENDERER").ok())?; - match v.to_ascii_lowercase().as_str() { - "gl" | "glow" | "opengl" => Some(eframe::Renderer::Glow), - "wgpu" | "vulkan" | "metal" | "dx12" => Some(eframe::Renderer::Wgpu), + match v.trim().to_ascii_lowercase().as_str() { + "gl" | "glow" | "opengl" => Some(WindowBackend::OpenGl), + "wgpu" | "auto" => Some(WindowBackend::Auto), + "vulkan" => Some(WindowBackend::Vulkan), + "dx12" | "d3d12" | "directx" => Some(WindowBackend::Dx12), + "metal" => Some(WindowBackend::Metal), _ => None, } } +/// The ways to open the window on `os`, in the order Automatic tries them (`startup`, #207): +/// each a graphics interface and whether to ask for the low-power GPU. On a laptop with two +/// GPUs (a Surface Book, most gaming laptops) the integrated one drives the display, so the +/// second try is the system's own interface on it; OpenGL is the last resort everywhere. +pub fn window_attempts(os: Os) -> Vec<(WindowBackend, bool)> { + match os { + Os::Windows => vec![(WindowBackend::Auto, false), (WindowBackend::Dx12, true), (WindowBackend::OpenGl, false)], + Os::Mac => vec![(WindowBackend::Auto, false), (WindowBackend::Metal, true), (WindowBackend::OpenGl, false)], + _ => vec![(WindowBackend::Auto, false), (WindowBackend::Vulkan, true), (WindowBackend::OpenGl, false)], + } +} + +/// The window graphics Preferences offers on `os`. +pub fn window_backends(os: Os) -> &'static [WindowBackend] { + match os { + Os::Windows => &[WindowBackend::Auto, WindowBackend::Dx12, WindowBackend::Vulkan, WindowBackend::OpenGl], + Os::Mac => &[WindowBackend::Auto, WindowBackend::Metal, WindowBackend::OpenGl], + Os::Web => &[], + _ => &[WindowBackend::Auto, WindowBackend::Vulkan, WindowBackend::OpenGl], + } +} + +/// Where the start-up log goes (#207): `Logs` in the settings folder. `ANICRAFT_LOG_DIR` +/// points it elsewhere (tests, portable installs). +pub fn log_dir() -> Option { + match std::env::var_os("ANICRAFT_LOG_DIR").filter(|v| !v.is_empty()) { + Some(d) => Some(PathBuf::from(d)), + None => config_dir().map(|d| d.join("Logs")), // i18n-exempt: a folder name + } +} + // ----- native file dialogs ---------------------------------------------------------------------- /// File type filters per command: the filter's name (English, translated where it is shown) @@ -730,7 +766,22 @@ mod tests { #[test] fn renderer_override() { - assert_eq!(forced_renderer(Some("gl")), Some(eframe::Renderer::Glow)); - assert_eq!(forced_renderer(Some("WGPU")), Some(eframe::Renderer::Wgpu)); + assert_eq!(forced_backend(Some("gl")), Some(WindowBackend::OpenGl)); + assert_eq!(forced_backend(Some("WGPU")), Some(WindowBackend::Auto)); + // #207: each interface is its own choice now, not just "wgpu". + assert_eq!(forced_backend(Some("dx12")), Some(WindowBackend::Dx12)); + assert_eq!(forced_backend(Some("vulkan")), Some(WindowBackend::Vulkan)); + assert_eq!(forced_backend(Some("metal")), Some(WindowBackend::Metal)); + } + + #[test] + fn every_platform_falls_back_to_opengl_and_offers_what_it_tries() { + for os in [Os::Windows, Os::Mac, Os::Linux, Os::Other] { + let tries = window_attempts(os); + assert_eq!(tries.first(), Some(&(WindowBackend::Auto, false)), "{os:?}"); + assert_eq!(tries.last(), Some(&(WindowBackend::OpenGl, false)), "{os:?}: OpenGL is the last resort"); + assert!(tries.iter().all(|(b, _)| window_backends(os).contains(b)), "{os:?}: Preferences offers each"); + } + assert!(window_attempts(Os::Windows).contains(&(WindowBackend::Dx12, true)), "DirectX 12 on the integrated GPU"); } } diff --git a/src/prefs.rs b/src/prefs.rs index 7bad24bc..5554569d 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -47,6 +47,39 @@ pub enum StageRenderer { Cpu, } +/// How the window itself is drawn (#207, #255): AniCraft picks, or one graphics interface the user +/// chose for this computer. Takes effect the next time AniCraft starts; whichever is chosen, a +/// failure falls back to the next way that works (`startup`). Read leniently, so a value a +/// newer build wrote never resets the other preferences. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum WindowBackend { + /// The platform's order (`platform::window_attempts`). + #[default] + Auto, + Vulkan, + /// Windows' own (Direct3D 12). + Dx12, + Metal, + OpenGl, +} + +impl WindowBackend { + /// The choice's name and what it is for, as Preferences lists it (English keys). + pub fn describe(self) -> (&'static str, &'static str) { + match self { + WindowBackend::Auto => (tr_noop!("Automatic"), tr_noop!("AniCraft tries the best way for this computer first, and the next one if a way doesn't work.")), + WindowBackend::Vulkan => (tr_noop!("Vulkan"), tr_noop!("Try this if the window flickers or goes black with another choice.")), + WindowBackend::Dx12 => (tr_noop!("DirectX 12"), tr_noop!("Windows' own graphics: try this if the window flickers or goes black with another choice.")), + WindowBackend::Metal => (tr_noop!("Metal"), tr_noop!("The Mac's own graphics.")), + WindowBackend::OpenGl => (tr_noop!("OpenGL"), tr_noop!("Older and slower, but works with most graphics drivers. The stage is drawn on the CPU or on a graphics device of its own.")), + } + } +} + +fn lenient_backend<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::from_value(serde_json::Value::deserialize(d)?).unwrap_or_default()) +} + impl StageRenderer { pub const ALL: [(StageRenderer, &'static str, &'static str); 2] = [ (StageRenderer::Gpu, tr_noop!("Graphics card (GPU)"), tr_noop!("Draws the stage on the graphics card, and on the CPU when there is no card that can. The picture is the same either way.")), @@ -78,6 +111,9 @@ pub struct Prefs { /// the choice), so that key is not read. #[serde(rename = "stage")] pub stage_renderer: StageRenderer, + /// How the window is drawn, from the next start (#207, #255). + #[serde(deserialize_with = "lenient_backend")] + pub window_backend: WindowBackend, /// Native open/save dialogs; off = a built-in path field (for Linux setups without an XDG /// desktop portal). pub native_dialogs: bool, @@ -162,6 +198,7 @@ impl Default for Prefs { ui_scale: 1.0, render_mode: RenderMode::Auto, stage_renderer: StageRenderer::Gpu, + window_backend: WindowBackend::Auto, native_dialogs: true, timeline_start_gap: 0.0, timeline_short_rows: false, @@ -387,6 +424,12 @@ mod tests { assert_eq!(p.stage_renderer, StageRenderer::Gpu, "the GPU draws the stage unless the CPU is chosen"); assert_eq!(Prefs::from_json(r#"{"stage_renderer": "Cpu"}"#).stage_renderer, StageRenderer::Gpu, "the old default, written by every earlier build, is not a choice"); assert_eq!(Prefs::from_json(r#"{"stage": "Cpu"}"#).stage_renderer, StageRenderer::Cpu); + // The window's graphics: automatic unless chosen, and a value this build doesn't know + // (a newer build's) leaves it automatic without resetting anything else. + assert_eq!(p.window_backend, WindowBackend::Auto); + assert_eq!(Prefs::from_json(r#"{"window_backend": "Dx12"}"#).window_backend, WindowBackend::Dx12); + let newer = Prefs::from_json(r#"{"window_backend": "Hologram", "stage": "Cpu"}"#); + assert_eq!((newer.window_backend, newer.stage_renderer), (WindowBackend::Auto, StageRenderer::Cpu)); let chosen = Prefs { stage_renderer: StageRenderer::Cpu, ..Prefs::default() }; assert_eq!(Prefs::from_json(&serde_json::to_string(&chosen).unwrap()).stage_renderer, StageRenderer::Cpu, "a choice survives saving"); let p = Prefs::from_json(r#"{"shortcuts": {"tool.pen": ["F10", "Ctrl+K"], "nope": ["F2"]}}"#); diff --git a/src/stage.rs b/src/stage.rs index d3786191..35f572ad 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -67,11 +67,13 @@ pub struct Cache { pub gpu: crate::gpu_stage::GpuStage, /// Who drew the newest visible tiles: the GPU, or the CPU and why (status bar). pub drawn_by: Option<(bool, Option)>, + /// The selection pattern's texture and the colour it was made in (`selection_pattern`). + pattern: Option<(Color32, egui::TextureHandle)>, } impl Default for Cache { fn default() -> Self { - Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), service: None, shown_state: None, gpu: Default::default(), drawn_by: None } + Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), service: None, shown_state: None, gpu: Default::default(), drawn_by: None, pattern: None } } } @@ -999,12 +1001,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Selected raw shapes (ADR 0031) show Animate's dot pattern over themselves, with no box. if app.tool == Tool::Select { let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); - let mut mesh = egui::Mesh::default(); + let (mut spans, mut dots) = (Vec::new(), egui::Mesh::default()); let mut budget = MAX_DOTS; for item in app.s.display_list().items.iter().filter(|i| app.s.selection.contains(i.layer, i.element) && raw.contains(&(i.layer, i.element))) { - selection_dots(&mut mesh, item, &to_px.mul(&item.transform), canvas, &mut budget); + selection_pattern(&mut spans, &mut dots, item, &to_px.mul(&item.transform), canvas, &mut budget); } - painter.add(egui::Shape::mesh(mesh)); + if !spans.is_empty() { + let mut mesh = egui::Mesh::with_texture(pattern_texture(&mut app.stage_cache.pattern, ui.ctx())); + pattern_mesh(&mut mesh, &spans); + painter.add(egui::Shape::mesh(mesh)); + } + painter.add(egui::Shape::mesh(dots)); } if multi { let hover = pointer.filter(|p| canvas.contains(*p) && !panning && !app.modal_open() && app.palette.is_none() && matches!(app.tool, Tool::Select | Tool::Transform)).map(to_stage); @@ -1277,14 +1284,80 @@ fn raw_ids(app: &App) -> std::collections::HashSet<(anicraft_engine::doc::LayerI layers.into_iter().flat_map(|l| app.s.elements_on(l).into_iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).map(move |e| (l, e.id))).collect() } -/// Most selection dots drawn in a frame. +/// Spacing of the selection pattern's dots (points). +const GAP: f32 = 3.0; +/// Most single dots drawn in a frame along hairline strokes (wider strokes and fills are spans). const MAX_DOTS: usize = 60_000; +/// Most pattern spans in a frame: far more than a full-screen drawing needs (a 4K view is ~720 +/// rows), so the pattern never stops part way down a shape; it only bounds a pathological one. +const MAX_SPANS: usize = 400_000; + +/// The selection pattern's tile: two by two dot cells, dark and light in a checker, at four +/// texels a point so the 1.5-point dots stay crisp. Drawn repeating, on the screen grid. +fn pattern_image(dark: Color32) -> egui::ColorImage { + const PER_PT: usize = 4; + let cell = (GAP as usize) * PER_PT; + let size = 2 * cell; + let (lo, hi) = (cell / 4, cell - cell / 4); + let pixels = (0..size * size) + .map(|i| { + let (x, y) = (i % size, i / size); + let inside = (lo..hi).contains(&(x % cell)) && (lo..hi).contains(&(y % cell)); + match inside { + false => Color32::TRANSPARENT, + true if (x / cell + y / cell).is_multiple_of(2) => dark, + true => Color32::WHITE, + } + }) + .collect(); + egui::ColorImage::new([size, size], pixels) +} + +/// The pattern texture for the theme's selection colour (made again when the theme changes). +fn pattern_texture(cache: &mut Option<(Color32, egui::TextureHandle)>, ctx: &egui::Context) -> egui::TextureId { + let dark = T.selection; + if let Some((c, t)) = cache.as_ref() + && *c == dark + { + return t.id(); + } + let t = ctx.load_texture("selection-pattern", pattern_image(dark), egui::TextureOptions::NEAREST_REPEAT); + let id = t.id(); + *cache = Some((dark, t)); + id +} + +/// Adds the pattern over `spans` to `mesh` (textured with [`pattern_texture`]). The texture +/// coordinates come from screen positions, so the dots sit on a fixed screen grid and don't +/// crawl when the view pans; a dot's centre is on a multiple of [`GAP`]. +fn pattern_mesh(mesh: &mut egui::Mesh, spans: &[Rect]) { + let tile = 2.0 * GAP; + let uv = |p: Pos2| pos2((p.x + GAP * 0.5) / tile, (p.y + GAP * 0.5) / tile); + for r in spans { + mesh.add_rect_with_uv(*r, Rect::from_min_max(uv(r.min), uv(r.max)), Color32::WHITE); + } +} /// Animate's selection look for raw shapes: fine dots over the selected fill or stroke, light and -/// dark in a checker so they show on any colour. They sit on a fixed screen grid, so they don't -/// crawl when the view pans; `m` maps the item's path to the screen. -fn selection_dots(mesh: &mut egui::Mesh, item: &anicraft_engine::doc::DisplayItem, m: &Affine, clip: Rect, budget: &mut usize) { - const GAP: f32 = 3.0; +/// dark in a checker so they show on any colour. `m` maps the item's path to the screen. Fills +/// and strokes wider than the dot spacing become `spans` (one rectangle per row of dots per run +/// inside them, for the pattern texture), so a shape filling the view costs a few hundred +/// rectangles however far it is zoomed in (#204: single dots under one budget ran out part way +/// down a big or zoomed-in shape, and the shading stopped there). Hairline strokes get one row of +/// dots along them in `mesh`. +fn selection_pattern(spans: &mut Vec, mesh: &mut egui::Mesh, item: &anicraft_engine::doc::DisplayItem, m: &Affine, clip: Rect, budget: &mut usize) { + use anicraft_engine::geom::FillRule; + if item.fill.is_some() { + pattern_spans(&item.path.flatten(m, 0.5), item.fill_rule, clip, spans); + } + let Some(st) = &item.stroke else { return }; + let half = (st.reach() * m.mean_scale()).max(0.5); + if half >= GAP { + // The stroke's own outline (caps, joins and dashes as drawn), filled non-zero. + let outline = anicraft_engine::render::stroke::stroke_outline(&item.path, m, st, 0.5); + pattern_spans(&outline.flatten(&Affine::IDENTITY, 0.5), FillRule::NonZero, clip, spans); + return; + } let mut dot = |p: Pos2| { if clip.contains(p) && *budget > 0 { *budget -= 1; @@ -1293,73 +1366,160 @@ fn selection_dots(mesh: &mut egui::Mesh, item: &anicraft_engine::doc::DisplayIte } *budget > 0 }; - let lines = item.path.flatten(m, 0.5); - if item.fill.is_some() { - let b = item.path.bounds().transformed(m); - let mut y = (b.min.y.max(clip.top()) / GAP).ceil() * GAP; - let bottom = b.max.y.min(clip.bottom()); - let mut xs: Vec = Vec::new(); - while y <= bottom { - // Where this row crosses the outline; pairs of crossings are inside (even-odd: raw - // fills never overlap themselves). - xs.clear(); - for pl in &lines { - let n = pl.points.len(); - for i in 0..n { - let (a, c) = (pl.points[i], pl.points[(i + 1) % n]); - if (a.y > y) != (c.y > y) { - xs.push(a.x + (y - a.y) * (c.x - a.x) / (c.y - a.y)); - } - } + // Along the stroke; segments off the screen are skipped. + let near = clip.expand(half + GAP); + for pl in &item.path.flatten(m, 0.5) { + let n = pl.points.len(); + let segs = if pl.closed { n } else { n.saturating_sub(1) }; + let mut carry = 0.0; + for i in 0..segs { + let (Some(&a), Some(&c)) = (pl.points.get(i), pl.points.get((i + 1) % n)) else { continue }; + let d = c - a; + let len = d.length(); + if len <= 1e-6 { + continue; } - xs.sort_by(f32::total_cmp); - for [x0, x1] in xs.as_chunks::<2>().0 { - let mut x = (x0.max(clip.left()) / GAP).ceil() * GAP; - while x <= x1.min(clip.right()) { - if !dot(pos2(x, y)) { - return; - } - x += GAP; - } + if !near.intersects(Rect::from_two_pos(pos2(a.x, a.y), pos2(c.x, c.y))) { + carry = (carry - len).rem_euclid(GAP); + continue; } - y += GAP; + let dir = d * (1.0 / len); + let mut t = carry; + while t < len { + let p = a + dir * t; + if !dot(pos2(p.x, p.y)) { + return; + } + t += GAP; + } + carry = t - len; } } - if let Some(st) = &item.stroke { - // Along the stroke, in rows across its width; segments off the screen are skipped. - let half = (st.reach() * m.mean_scale()).max(0.5); - let rows = (half / GAP).floor() as i32; - let near = clip.expand(half + GAP); - for pl in &lines { - let n = pl.points.len(); - let segs = if pl.closed { n } else { n.saturating_sub(1) }; - let mut carry = 0.0; - for i in 0..segs { - let (a, c) = (pl.points[i], pl.points[(i + 1) % n]); - let d = c - a; - let len = d.length(); - if len <= 1e-6 { - continue; - } - if !near.intersects(Rect::from_two_pos(pos2(a.x, a.y), pos2(c.x, c.y))) { - carry = (carry - len).rem_euclid(GAP); - continue; - } - let (dir, normal) = (d * (1.0 / len), d.perp() * (1.0 / len)); - let mut t = carry; - while t < len { - let p = a + dir * t; - for k in -rows..=rows { - let q = p + normal * (k as f32 * GAP); - if !dot(pos2(q.x, q.y)) { - return; - } +} + +/// The runs inside the closed outlines `lines` (screen space, filled by `rule`) along each row +/// of dots, as rectangles one row of dots tall, clipped to `clip`. Rows are scanned with an +/// active edge list, so the cost follows the outline's edges and the rows on screen, not the +/// area covered. +pub(crate) fn pattern_spans(lines: &[anicraft_engine::geom::Polyline], rule: anicraft_engine::geom::FillRule, clip: Rect, out: &mut Vec) { + use anicraft_engine::geom::FillRule; + // Every non-horizontal edge near the view, as (top, bottom, x at top, dx/dy, winding). + let mut edges: Vec<(f32, f32, f32, f32, i32)> = Vec::new(); + for pl in lines { + let n = pl.points.len(); + if n < 2 { + continue; + } + for i in 0..n { + let (Some(&a), Some(&c)) = (pl.points.get(i), pl.points.get((i + 1) % n)) else { continue }; + if a.y == c.y || !(a.is_finite() && c.is_finite()) { + continue; + } + let (top, bottom, w) = if a.y < c.y { (a, c, 1) } else { (c, a, -1) }; + if bottom.y < clip.top() - GAP || top.y > clip.bottom() + GAP { + continue; + } + edges.push((top.y, bottom.y, top.x, (bottom.x - top.x) / (bottom.y - top.y), w)); + } + } + if edges.is_empty() { + return; + } + edges.sort_by(|a, b| a.0.total_cmp(&b.0)); + let last = edges.iter().fold(f32::NEG_INFINITY, |m, e| m.max(e.1)).min(clip.bottom() + GAP * 0.5); + let mut y = (edges.first().map_or(0.0, |e| e.0).max(clip.top() - GAP * 0.5) / GAP).ceil() * GAP; + let inside = |w: i32| match rule { + FillRule::NonZero => w != 0, + FillRule::EvenOdd => w % 2 != 0, + }; + let (mut next, mut active, mut xs): (usize, Vec, Vec<(f32, i32)>) = (0, Vec::new(), Vec::new()); + while y <= last && out.len() < MAX_SPANS { + while edges.get(next).is_some_and(|e| e.0 <= y) { + active.push(next); + next += 1; + } + // Half-open in y, so a vertex shared by two edges counts once. + active.retain(|&i| edges.get(i).is_some_and(|e| e.1 > y)); + xs.clear(); + xs.extend(active.iter().filter_map(|&i| edges.get(i)).map(|e| (e.2 + (y - e.0) * e.3, e.4))); + xs.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (top, bottom) = ((y - GAP * 0.5).max(clip.top()), (y + GAP * 0.5).min(clip.bottom())); + let (mut w, mut from) = (0, 0.0); + for &(x, d) in &xs { + let was = inside(w); + w += d; + match (was, inside(w)) { + (false, true) => from = x, + (true, false) => { + let (x0, x1) = (from.max(clip.left()), x.min(clip.right())); + if x1 > x0 && bottom > top { + out.push(Rect::from_min_max(pos2(x0, top), pos2(x1, bottom))); } - t += GAP; } - carry = t - len; + _ => {} } } + y += GAP; + } +} + +#[cfg(test)] +mod pattern_tests { + use super::*; + use anicraft_engine::geom::{FillRule, Path}; + + fn area(spans: &[Rect]) -> f32 { + spans.iter().map(|r| r.area()).sum() + } + + /// #204: a shape far bigger than the view (zoomed in) is shaded all the way down, not just its + /// top rows, and costs one span per row rather than one quad per dot. + #[test] + fn a_zoomed_in_shape_is_shaded_to_the_bottom_of_the_view() { + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(3840.0, 2160.0)); + let mut spans = Vec::new(); + let big = Path::rect(-5000.0, -4000.0, 20000.0, 15000.0); + pattern_spans(&big.flatten(&Affine::IDENTITY, 0.5), FillRule::NonZero, clip, &mut spans); + let bottom = spans.iter().fold(0.0f32, |m, r| m.max(r.max.y)); + assert_eq!(bottom, clip.bottom(), "the pattern reaches the bottom of the view"); + assert!((area(&spans) - clip.area()).abs() < 1.0, "the whole view is covered: {} of {}", area(&spans), clip.area()); + assert_eq!(spans.len(), 721, "one span per row of dots"); + // The single-dot overlay this replaced stopped after 60 000 dots: 46 rows of 1 280. + assert!(clip.area() / (GAP * GAP) > 60_000.0 * 10.0); + } + + /// Holes stay unshaded (even-odd and non-zero), and the spans follow the outline. + #[test] + fn spans_follow_the_fill_rule_and_the_outline() { + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 400.0)); + let mut ring = Path::rect(0.0, 0.0, 300.0, 300.0); + ring.cmds.extend(Path::rect(100.0, 100.0, 100.0, 100.0).cmds); + for rule in [FillRule::EvenOdd, FillRule::NonZero] { + let mut spans = Vec::new(); + pattern_spans(&ring.flatten(&Affine::IDENTITY, 0.5), rule, clip, &mut spans); + let in_hole = spans.iter().any(|r| r.contains(pos2(150.0, 150.0))); + assert_eq!(in_hole, rule == FillRule::NonZero, "{rule:?}: both squares wind the same way"); + assert!(spans.iter().all(|r| r.min.x >= 0.0 && r.max.x <= 300.0 && r.max.y <= 301.5)); + assert!(spans.iter().any(|r| r.contains(pos2(50.0, 150.0)))); + } + } + + /// The tile's dots sit on the screen grid in the old checker: dark where the row and column + /// numbers add up to an even number. + #[test] + fn the_pattern_tile_is_a_checker_of_dots() { + let img = pattern_image(Color32::BLUE); + let size = img.size[0]; + let at = |pt: (f32, f32)| { + // Screen point → texel, as `pattern_mesh` maps it. + let u = ((pt.0 + GAP * 0.5) / (2.0 * GAP)).rem_euclid(1.0); + let v = ((pt.1 + GAP * 0.5) / (2.0 * GAP)).rem_euclid(1.0); + img.pixels[(v * size as f32) as usize * size + (u * size as f32) as usize] + }; + assert_eq!(at((0.0, 0.0)), Color32::BLUE); + assert_eq!(at((3.0, 0.0)), Color32::WHITE); + assert_eq!(at((3.0, 3.0)), Color32::BLUE); + assert_eq!(at((1.4, 0.0)), Color32::TRANSPARENT, "space between dots"); } } diff --git a/src/startup.rs b/src/startup.rs new file mode 100644 index 00000000..9f4ef198 --- /dev/null +++ b/src/startup.rs @@ -0,0 +1,297 @@ +//! Starting the window whatever the graphics driver does (#207, ADR 0006), and the start-up log +//! users can attach to a bug report. +//! +//! The window is opened by a list of attempts ([`plan`]): the interface asked for (`--renderer`, +//! `ANICRAFT_RENDERER`, or Preferences › Stage › Window graphics), then the platform's order +//! ([`crate::platform::window_attempts`]), ending with OpenGL. An attempt that returns an error +//! or panics before the window has drawn falls through to the next one; when none works, a +//! system message box says so and where the log is, so AniCraft never just disappears. +//! +//! A driver can also crash the process or hang, which nothing inside it can catch. Each attempt +//! leaves a marker in the log folder until the window has drawn a few frames; if the next start +//! finds one, the previous start died in that attempt, so it goes last this time. The log (the +//! previous run's is kept beside it) records each attempt, the graphics adapter and driver, +//! panics, and a note when the window is still not up after a while. + +use crate::prefs::WindowBackend; +use std::io::Write; +use std::path::PathBuf; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; + +/// One way to open the window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Attempt { + pub backend: WindowBackend, + /// Ask for the low-power (integrated) GPU rather than the fastest one. + pub low_power: bool, +} + +impl Attempt { + /// A stable name for the log and the crash marker (English: it is a log). + pub fn label(&self) -> String { + let name = match self.backend { + WindowBackend::Auto => "wgpu (automatic)", // i18n-exempt: log text + WindowBackend::Vulkan => "wgpu Vulkan", // i18n-exempt: log text + WindowBackend::Dx12 => "wgpu DirectX 12", // i18n-exempt: log text + WindowBackend::Metal => "wgpu Metal", // i18n-exempt: log text + WindowBackend::OpenGl => "OpenGL", // i18n-exempt: log text + }; + if self.low_power && self.backend != WindowBackend::OpenGl { format!("{name}, low-power GPU") } else { name.to_string() } + } + + /// `base` set up for this attempt. + #[cfg(not(target_arch = "wasm32"))] + pub fn options(&self, mut base: eframe::NativeOptions) -> eframe::NativeOptions { + use eframe::egui_wgpu::{WgpuSetup, WgpuSetupCreateNew, wgpu}; + if self.backend == WindowBackend::OpenGl { + base.renderer = eframe::Renderer::Glow; + return base; + } + base.renderer = eframe::Renderer::Wgpu; + let mut setup = WgpuSetupCreateNew::without_display_handle(); + match self.backend { + WindowBackend::Vulkan => setup.instance_descriptor.backends = wgpu::Backends::VULKAN, + WindowBackend::Dx12 => setup.instance_descriptor.backends = wgpu::Backends::DX12, + WindowBackend::Metal => setup.instance_descriptor.backends = wgpu::Backends::METAL, + WindowBackend::Auto | WindowBackend::OpenGl => {} + } + if self.low_power { + setup.power_preference = wgpu::PowerPreference::LowPower; + } + base.wgpu_options.wgpu_setup = WgpuSetup::CreateNew(setup); + base + } +} + +/// The attempts in order: `forced` (the command line) or else `chosen` (Preferences) first, then +/// the platform's order `platform`, each once. The attempt named `died_in` (the previous start +/// crashed or hung in it) goes last. +pub fn plan(forced: Option, chosen: WindowBackend, platform: &[(WindowBackend, bool)], died_in: Option<&str>) -> Vec { + let mut out: Vec = Vec::new(); + let first = forced.unwrap_or(chosen); + if first != WindowBackend::Auto { + out.push(Attempt { backend: first, low_power: false }); + } + for &(backend, low_power) in platform { + let a = Attempt { backend, low_power }; + if !out.iter().any(|o| o.label() == a.label()) { + out.push(a); + } + } + if out.is_empty() { + out.push(Attempt { backend: WindowBackend::Auto, low_power: false }); + } + if let Some(dead) = died_in + && let Some(i) = out.iter().position(|a| a.label() == dead) + && out.len() > 1 + { + let a = out.remove(i); + out.push(a); + } + out +} + +/// Longest log written in one run: enough for any start-up, bounded however long AniCraft runs. +const MAX_LOG_BYTES: u64 = 1024 * 1024; +/// Frames the window draws before the start counts as working. +const STARTED_AFTER: u32 = 3; +/// A note goes in the log when the window still isn't up after this long. +const SLOW_START_SECS: u64 = 20; + +const LOG_NAME: &str = "anicraft.log"; +const PREVIOUS_LOG_NAME: &str = "anicraft.previous.log"; +const MARKER_NAME: &str = "starting"; + +struct Log { + dir: PathBuf, + file: Option, + since: std::time::Instant, + written: u64, +} + +static LOG: Mutex> = Mutex::new(None); +static FRAMES: AtomicU32 = AtomicU32::new(0); + +/// Opens the log in `dir` for this run (the previous run's becomes `anicraft.previous.log`) and +/// returns the attempt the previous start died in, if its marker is still there. Panics are +/// written to the log from now on. +pub fn begin(dir: Option) -> Option { + let dir = dir?; + let _ = std::fs::create_dir_all(&dir); + let died_in = std::fs::read_to_string(dir.join(MARKER_NAME)).ok().map(|s| s.trim().chars().take(200).collect::()).filter(|s| !s.is_empty()); + let _ = std::fs::rename(dir.join(LOG_NAME), dir.join(PREVIOUS_LOG_NAME)); + let file = std::fs::File::create(dir.join(LOG_NAME)).ok(); + if let Ok(mut g) = LOG.lock() { + *g = Some(Log { dir, file, since: std::time::Instant::now(), written: 0 }); + } + FRAMES.store(0, Ordering::Relaxed); + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + // Never waits: the panic may have happened while the log was being written. + write(&format!("panic: {info}"), false); + previous(info); + })); + let unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); + line(&format!("AniCraft {} ({}), {} {}, started at {unix} (Unix time)", env!("CARGO_PKG_VERSION"), crate::app::RELEASE_STAGE, std::env::consts::OS, std::env::consts::ARCH)); + if let Some(d) = &died_in { + line(&format!("the previous start stopped while opening the window with {d}: trying it last")); + } + died_in +} + +/// Adds a line to the log (and the console in debug builds), with the seconds since it began. +pub fn line(text: &str) { + write(text, true); +} + +fn write(text: &str, wait: bool) { + #[cfg(debug_assertions)] + eprintln!("{text}"); + let Ok(mut g) = (if wait { LOG.lock().map_err(|_| ()) } else { LOG.try_lock().map_err(|_| ()) }) else { return }; + let Some(log) = g.as_mut() else { return }; + let Some(f) = log.file.as_mut() else { return }; + if log.written > MAX_LOG_BYTES { + return; + } + let entry = format!("[{:8.3} s] {}\n", log.since.elapsed().as_secs_f64(), text.chars().take(4000).collect::()); + log.written += entry.len() as u64; + // Flushed at once: the next thing may be the driver taking the process down. + let _ = f.write_all(entry.as_bytes()).and_then(|()| f.flush()); +} + +/// Where the log is, when there is one. +pub fn log_path() -> Option { + LOG.lock().ok()?.as_ref().map(|l| l.dir.join(LOG_NAME)) +} + +/// About to try `a`: logged, and the marker says so until the window has drawn. A watchdog +/// notes in the log if the window is still not up after a while (a driver that hangs). +pub fn trying(a: &Attempt, n: usize, of: usize) { + line(&format!("opening the window with {} (attempt {n} of {of})", a.label())); + let marker = LOG.lock().ok().and_then(|g| g.as_ref().map(|l| l.dir.join(MARKER_NAME))); + if let Some(m) = marker { + let _ = std::fs::write(m, a.label()); + } + FRAMES.store(0, Ordering::Relaxed); + let label = a.label(); + let _ = std::thread::Builder::new().name("anicraft-start-watch".into()).spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(SLOW_START_SECS)); + if FRAMES.load(Ordering::Relaxed) == 0 { + line(&format!("the window has not drawn after {SLOW_START_SECS} s with {label} (a graphics driver that hangs?)")); + } + }); +} + +/// Called once a frame by the window: after a few frames the start counts as working and the +/// marker goes. +pub fn frame() { + if FRAMES.fetch_add(1, Ordering::Relaxed) + 1 == STARTED_AFTER { + line(&format!("the window is up ({STARTED_AFTER} frames drawn)")); + let marker = LOG.lock().ok().and_then(|g| g.as_ref().map(|l| l.dir.join(MARKER_NAME))); + if let Some(m) = marker { + let _ = std::fs::remove_file(m); + } + } +} + +/// Whether the window of the current attempt has drawn (then a failure is not retried: it ran). +pub fn started() -> bool { + FRAMES.load(Ordering::Relaxed) >= STARTED_AFTER +} + +/// The adapter and driver the window got (wgpu), for the log. +#[cfg(not(target_arch = "wasm32"))] +pub fn log_adapter(rs: Option<&eframe::egui_wgpu::RenderState>) { + match rs { + Some(rs) => { + let i = rs.adapter.get_info(); + line(&format!("window graphics: {} ({:?}, {:?}), driver {} {}", i.name, i.backend, i.device_type, i.driver, i.driver_info)); + } + None => line("window graphics: OpenGL"), // i18n-exempt: log text + } +} + +/// The text of a panic's payload. +pub fn panic_text(p: &(dyn std::any::Any + Send)) -> String { + p.downcast_ref::<&str>().map(|s| (*s).to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_else(|| "a panic".into()) // i18n-exempt: log text +} + +/// Every attempt failed: the log says why, and a system message box says so (the window +/// can't), with where the log is. +#[cfg(not(target_arch = "wasm32"))] +pub fn give_up(why: &str) { + line(&format!("no way to open the window worked; last: {why}")); + let log = log_path().map_or_else(String::new, |p| p.display().to_string()); + let text = if log.is_empty() { + tr!("AniCraft couldn't open its window with this computer's graphics driver ({why}). Updating the graphics driver usually helps.", why = why).to_string() + } else { + tr!("AniCraft couldn't open its window with this computer's graphics driver ({why}). Updating the graphics driver usually helps. If it doesn't, please attach this file to a bug report: {log}", why = why, log = log).to_string() + }; + let _ = rfd::MessageDialog::new().set_level(rfd::MessageLevel::Error).set_title(tr!("AniCraft couldn't start")).set_description(text).set_buttons(rfd::MessageButtons::Ok).show(); +} + +#[cfg(test)] +mod tests { + use super::*; + use WindowBackend::*; + + const WINDOWS: &[(WindowBackend, bool)] = &[(Auto, false), (Dx12, true), (OpenGl, false)]; + + fn labels(v: &[Attempt]) -> Vec { + v.iter().map(Attempt::label).collect() + } + + #[test] + fn automatic_tries_the_platform_order_ending_with_opengl() { + assert_eq!(labels(&plan(None, Auto, WINDOWS, None)), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); + } + + #[test] + fn a_chosen_or_forced_interface_goes_first_and_still_falls_back() { + assert_eq!(labels(&plan(None, Vulkan, WINDOWS, None)), ["wgpu Vulkan", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); + // The command line wins over Preferences; OpenGL isn't tried twice. + assert_eq!(labels(&plan(Some(OpenGl), Dx12, WINDOWS, None)), ["OpenGL", "wgpu (automatic)", "wgpu DirectX 12, low-power GPU"]); + assert_eq!(labels(&plan(Some(Auto), Dx12, WINDOWS, None)), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"], "--renderer wgpu is automatic"); + } + + /// #207: when the last start died inside a driver (nothing to catch), that way goes last. + #[test] + fn the_way_the_last_start_died_in_goes_last() { + assert_eq!(labels(&plan(None, Auto, WINDOWS, Some("wgpu (automatic)"))), ["wgpu DirectX 12, low-power GPU", "OpenGL", "wgpu (automatic)"]); + assert_eq!(labels(&plan(None, Auto, WINDOWS, Some("something else"))), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"]); + assert_eq!(labels(&plan(None, Auto, &[], None)), ["wgpu (automatic)"], "never nothing to try"); + } + + /// The log, the crash marker and the previous run's log, in a folder of their own. + #[test] + fn the_log_keeps_the_previous_run_and_finds_a_crashed_start() { + let dir = std::env::temp_dir().join(format!("anicraft-startup-log-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(begin(Some(dir.clone())), None, "a first start"); + trying(&Attempt { backend: Dx12, low_power: true }, 1, 3); + line("hello"); + // Killed here (a driver crash): the marker stays, and the next start finds it. + assert_eq!(begin(Some(dir.clone())).as_deref(), Some("wgpu DirectX 12, low-power GPU")); + let previous = std::fs::read_to_string(dir.join(PREVIOUS_LOG_NAME)).unwrap(); + assert!(previous.contains("opening the window with wgpu DirectX 12, low-power GPU (attempt 1 of 3)") && previous.contains("hello"), "{previous}"); + let now = std::fs::read_to_string(dir.join(LOG_NAME)).unwrap(); + assert!(now.contains("the previous start stopped while opening the window with wgpu DirectX 12"), "{now}"); + // This time the window comes up: the marker goes. + trying(&Attempt { backend: OpenGl, low_power: false }, 1, 1); + for _ in 0..STARTED_AFTER { + frame(); + } + assert!(started()); + assert!(!dir.join(MARKER_NAME).exists()); + assert_eq!(log_path(), Some(dir.join(LOG_NAME))); + // A panic is written down. + let _ = std::panic::catch_unwind(|| panic!("the driver said no")); + assert!(std::fs::read_to_string(dir.join(LOG_NAME)).unwrap().contains("the driver said no")); + // Closed, so the folder can go (Windows keeps open files). + if let Ok(mut g) = LOG.lock() { + *g = None; + } + let _ = std::fs::remove_dir_all(&dir); + } +} From 04a85d5e50421e66b6bc858bc521a9382b0130f8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 12:59:04 -0700 Subject: [PATCH 3/4] docs: start-up, file and display fixes in the guide, changelog and roadmap; web release zip script (M8) packaging/web/package.sh is the app side of the family release workflow's web job (#210) and runs in the Web CI job; releases keep has-web off until hosting is decided. --- .github/workflows/release.yml | 3 ++- .github/workflows/web.yml | 9 +++---- CHANGELOG.md | 23 ++++++++++++++++++ README.md | 2 +- docs/guide/opening-animate-files.md | 6 +++++ .../preferences-shortcuts-accessibility.md | 6 +++++ docs/guide/troubleshooting-and-faq.md | 24 +++++++++++++------ docs/roadmap.md | 6 ++--- docs/web.md | 4 +++- packaging/web/package.sh | 1 + 10 files changed, 67 insertions(+), 17 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4c08976b..304f6cbd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,8 @@ jobs: app-name: anicraft app-title: AniCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 - # No WebAssembly build of the editor yet (roadmap M8). + # The web editor builds (ADR 0036) and packaging/web/package.sh makes its zip (#210), but + # releases don't carry it until the team decides where it is hosted: off for now. has-web: false secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index 132201c4..bbf2a232 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -1,7 +1,7 @@ # The web build (ADR 0036, docs/web.md), so it never regresses: every crate of the workspace # builds for wasm32-unknown-unknown, the engine's tests/wasm.rs runs inside WebAssembly in Node # (what a build can't catch: clock, thread and file calls that compile but trap), and -# scripts/build-web.sh produces the web/ bundle. Nothing is deployed. +# packaging/web/package.sh produces the web/ bundle and its release zip. Nothing is deployed. name: Web on: @@ -52,7 +52,8 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner run: cargo test -p anicraft-engine --target wasm32-unknown-unknown --test wasm --locked - - name: The web editor bundle + # The release download too (#210): what the release workflow's web job runs. + - name: The web editor bundle and its release zip run: | - scripts/build-web.sh - ls -l web + packaging/web/package.sh + ls -l web dist/release diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c727baa..d99141b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,29 @@ ## Unreleased +* **Fixed: start-up, files and display, from user reports** (M8). + * Fixed: Flash files that opened in 0.1 no longer opening (#226). One damaged or unreadable + part of a `.fla` (a bitmap, a sound, a library symbol) no longer stops the whole file from + opening: the rest opens and the report says what was left out. A file double-clicked or + opened with **Open With** that can't be opened now says why in the status bar instead of + quietly showing the sample, and `anicraft-cli info`, `render` and the export commands open + `.fla` and `.xfl` files too. + * Fixed: Animate documents opening on a black stage instead of white (#163). + * Fixed: AniCraft not opening at all on some laptops with two graphics chips, such as the + Surface Book 2 (#207). If a way of drawing the window fails, AniCraft now tries the next one + (on Windows: DirectX 12 on the built-in chip, then OpenGL) instead of exiting, and a start that + crashed inside a graphics driver tries that way last next time. If nothing works, a message + says so. A start-up log in the settings folder (`Logs/anicraft.log`) records what was tried, + to attach to a bug report. + * New: **Preferences › Stage › Window graphics** chooses how the window is drawn (Automatic, + DirectX 12, Vulkan, Metal or OpenGL), for windows that flicker or flash black (#255). + `--renderer dx12`, `vulkan` and `metal` now pick that interface; before, they all meant the + default. + * Fixed: the selection shading on shapes stopping part way down when zoomed in or on a big + shape (#204). The dot pattern now covers the whole shape and its outline at any zoom, and + costs the same however much of the screen it covers. + * The web version's download is now built by `packaging/web/package.sh` and checked in CI; the + README no longer suggests releases carry it yet (#210). * **Soft masks and text on a path** (ADR 0070, M4). * **Soft masks**: Layer Properties › **Mask type** on a mask layer: *Shape* (as in Animate), *Alpha* (the mask's opacity reveals: a gradient to transparent fades the artwork out) or diff --git a/README.md b/README.md index 98ecb417..eb6390d7 100644 --- a/README.md +++ b/README.md @@ -273,7 +273,7 @@ RISC-V (riscv64): `anicraft--linux-riscv64.tar.gz`, a tarball only. | Build | File | Notes | |---|---|---| -| Static site | `anicraft-web-.zip` | Runs in a modern browser; host it on any static server | +| Static site | `anicraft-web-.zip` | Not in the releases yet: build it yourself with `packaging/web/package.sh` ([docs/web.md](docs/web.md)), then host it on any static server | ## The Crafting Apps diff --git a/docs/guide/opening-animate-files.md b/docs/guide/opening-animate-files.md index 2b56f0ee..26fda242 100644 --- a/docs/guide/opening-animate-files.md +++ b/docs/guide/opening-animate-files.md @@ -125,6 +125,12 @@ computers without the font. * Archives made by different zip tools open, large ones included. * A **damaged or suspicious** file fails with one sentence that names the problem, and never crashes AniCraft. Nothing from it is ever unpacked onto your disk. +* When only **part** of a file is damaged (one bitmap, one sound or one library symbol), the rest + opens and the report counts what was left out, such as "1 bitmaps whose files couldn't be + read". +* A document that opens without a stage colour gets Animate's default, white. +* A document you double-click, or open with **Open With**, that can't be opened says why in the + status bar. ## Tips diff --git a/docs/guide/preferences-shortcuts-accessibility.md b/docs/guide/preferences-shortcuts-accessibility.md index 3f853c1d..97272917 100644 --- a/docs/guide/preferences-shortcuts-accessibility.md +++ b/docs/guide/preferences-shortcuts-accessibility.md @@ -45,6 +45,12 @@ bottom says which system you are on and where your settings are kept. Both settings are also in **View › Stage Rendering**, so you can switch without opening Preferences. +* **Window graphics**: how the whole window is drawn. **Automatic** (the default) tries the best + way for your computer first and the next one if it doesn't work. If the window flickers or + goes black, choose another way: **DirectX 12**, **Vulkan** or **OpenGL** on Windows, **Metal** + or **OpenGL** on a Mac, **Vulkan** or **OpenGL** on Linux. A change takes effect the next time + AniCraft starts. The note below names the start-up log to attach to a bug report. + ### Timeline, Test Movie, Files and Safety * **Timeline › Extra start gap** adds room before frame 1, on top of the room the playhead needs. diff --git a/docs/guide/troubleshooting-and-faq.md b/docs/guide/troubleshooting-and-faq.md index fd247bf0..76c8aac2 100644 --- a/docs/guide/troubleshooting-and-faq.md +++ b/docs/guide/troubleshooting-and-faq.md @@ -8,17 +8,26 @@ On macOS, press ⌘ where this guide says Ctrl, and ⌥ where it says Alt. ## The window won't open, or stays blank AniCraft draws its window with your graphics card through a modern graphics interface (Vulkan, -Metal or Direct3D 12). If that fails to start, which happens on some older cards, virtual -machines and Linux setups, AniCraft tries once more with OpenGL by itself. +Metal or DirectX 12). If that fails to start, which happens on some older cards, laptops with two +graphics chips, virtual machines and Linux setups, AniCraft tries the next way by itself: on +Windows, DirectX 12 on the built-in graphics chip, and then OpenGL everywhere. If a graphics +driver crashes or hangs while AniCraft starts, the next start tries that way last. -If the window still opens blank or garbled, force OpenGL from a terminal: +If no way works, AniCraft says so in a message and names its **start-up log**, a text file that +records each way it tried and why it failed. Please attach it to your bug report. It is +`anicraft.log` in the `Logs` folder of the [settings folder](#where-settings-live), with the +previous run's beside it as `anicraft.previous.log`. + +If the window opens but flickers, goes black for a moment or looks garbled, choose another way +in **Preferences › Stage › Window graphics** (for example **DirectX 12** or **OpenGL** on +Windows) and restart AniCraft. From a terminal, the same choice is: ```sh -anicraft --renderer gl +anicraft --renderer gl # or dx12, vulkan, metal ``` -To make that stick, set the environment variable `ANICRAFT_RENDERER=gl` for your account. -`--renderer wgpu` (or `ANICRAFT_RENDERER=wgpu`) goes back to the default. +To make it stick without Preferences, set the environment variable `ANICRAFT_RENDERER` for your +account. `--renderer wgpu` (or `ANICRAFT_RENDERER=wgpu`) goes back to the automatic choice. ## The stage is slow, flickers or looks wrong @@ -102,7 +111,8 @@ in one settings folder. Its path is shown at the bottom of the Preferences windo | Web version | the browser's storage for the site | Inside it: `prefs.json` (preferences and shortcuts), `Recovery` (autosaved copies), `Templates` -(your templates), `plugins` (installed plug-ins) and `Thumbnails` (start screen pictures). +(your templates), `plugins` (installed plug-ins), `Thumbnails` (start screen pictures) and `Logs` +(the start-up log). To start over with default preferences, quit AniCraft and rename or delete `prefs.json`. A damaged preferences file never stops AniCraft from starting: it falls back to the defaults. diff --git a/docs/roadmap.md b/docs/roadmap.md index bebb2384..37623f69 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -16,12 +16,12 @@ 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; 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. | | 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. | +| 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`): 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. | | 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. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | -| Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. | +| Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. **Robust start-up** (#207): the window opens through a list of ways (the one chosen in Preferences › Stage › Window graphics or `--renderer gl|wgpu|vulkan|dx12|metal`, then wgpu automatic, DirectX 12 on the low-power GPU on Windows, OpenGL), falling through on an error or a panic; a start that died inside a driver tries that way last next time; a start-up log (`Logs/anicraft.log` in the settings folder, the previous run's kept) records each way, the adapter and driver, panics and slow starts; a system message names it when nothing works. Not yet: verified on a hybrid-GPU laptop, the log from the Help menu. | | Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. **Opening documents on macOS** (ADR 0062): a double-click in Finder, a drop on the Dock icon or Open With opens the document, at launch or while running (the open-documents Apple Event through `platform.rs`, by `fmv-macos-events`, so no `unsafe` of ours), through the unsaved-changes guard; the Dock's Quit asks to save too; Windows and Linux command-line hand-over covered by a test. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, AppImage desktop integration, portable mode, store listings, video export inside the Flatpak. | | Documentation | **User guide, first slice** (ADR 0069, `docs/guide/`): eighteen chapters for artists (getting started to troubleshooting, and Coming from Animate), a command reference and a shortcut reference (Windows/Linux and macOS) generated from the registry and checked for freshness by tests, every link, anchor and picture checked, eight screenshots from `scripts/guide-shots.sh`. Help › User Guide opens the book bundled in the app, offline, in the browser; the web build serves it beside the editor; `anicraft-cli guide --out ` writes it. Not yet: translated guides, search, a PDF edition, context help from panels, macOS and Linux screenshots. | | Languages | **First slice** (ADR 0040, `docs/localisation.md`): every shell string goes through `tr!`/`trn!` (keyed by its English; placeholders; CLDR plurals for whole numbers), menus translate the registry's labels when drawn (ids, CLI, MCP and the file format stay English), screen-reader names too. Catalogs are craft-i18n's TSV, read by our own parser and embedded from `CRAFT_I18N_DIR` (fallback app → shared → base language → English). Preferences › Appearance › Language (system language by default) and `--lang`. A **pseudo-locale** (`--lang pseudo`: accented, a third longer, bracketed) tests layout; checked by a source guideline test and a pseudo-locale accessibility audit; `scripts/i18n-extract.sh` writes the translators' template and per-locale coverage. Not yet: a real language (craft-i18n has no `anicraft.tsv` yet), engine messages and confirmation bodies (`@msg`), default document names, right to left (needs bidi and shaping in egui upstream), CJK and Georgian (need a font), shaped scripts. | @@ -41,7 +41,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **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); ~~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 later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~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: spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | -| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), 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), next: live screen-reader passes on each platform, a light 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). | +| **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); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, 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), next: live screen-reader passes on each platform, a light 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). | ## Releases diff --git a/docs/web.md b/docs/web.md index e3511da7..62b0688a 100644 --- a/docs/web.md +++ b/docs/web.md @@ -2,7 +2,9 @@ AniCraft also runs in a web browser: the same program, built for WebAssembly (`wasm32-unknown-unknown`), drawing into a page with WebGL2. How it is built, and why, is in -[ADR 0036](adr/0036-web-build.md). Nothing is hosted yet; you build it and serve it yourself. +[ADR 0036](adr/0036-web-build.md). Nothing is hosted yet and the releases don't carry it yet; you +build it and serve it yourself. `packaging/web/package.sh` builds it and zips it as the release +download `dist/release/anicraft-web-.zip`, the static site to unzip onto a web server. ## Build diff --git a/packaging/web/package.sh b/packaging/web/package.sh index 813c8c8e..0b33ebd4 100755 --- a/packaging/web/package.sh +++ b/packaging/web/package.sh @@ -14,6 +14,7 @@ set -euo pipefail # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" cd "$ROOT" +command -v zip >/dev/null || { echo "error: zip not found (apt install zip)" >&2; exit 1; } WANT="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)" if ! command -v wasm-bindgen >/dev/null || [[ "$(wasm-bindgen --version | awk '{ print $2 }')" != "$WANT" ]]; then From 21540d8b371b45a92108cca02fa9d2ed867153cf Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 13:24:46 -0700 Subject: [PATCH 4/4] test(ui): the selection pattern in a headless window, strokes and hairlines, and each start-up attempt's window setup (M8) --- src/stage.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/startup.rs | 30 ++++++++++++++++++++++ 2 files changed, 98 insertions(+) diff --git a/src/stage.rs b/src/stage.rs index 35f572ad..c8a99b0c 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -1504,6 +1504,74 @@ mod pattern_tests { } } + fn item(path: Path, fill: bool, stroke: Option) -> anicraft_engine::doc::DisplayItem { + use anicraft_engine::doc::{ColorTransform, DisplayItem, ElementId, LayerId, Paint, Rgba, Stroke}; + DisplayItem { + path: std::sync::Arc::new(path), + transform: Affine::IDENTITY, + fill: fill.then_some(Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0))), + stroke: stroke.map(|w| Stroke::new(Rgba::new(0.0, 0.0, 0.0, 1.0), w)), + fill_rule: FillRule::NonZero, + color: ColorTransform::IDENTITY, + layer: LayerId(0), + element: ElementId(0), + outline: None, + clip: None, + masks: None, + guide: false, + group: None, + image: None, + smooth: true, + } + } + + /// A wide stroke is shaded over its whole outline (beyond the fill), a hairline gets dots + /// along it, and nothing off the view is drawn. + #[test] + fn strokes_are_shaded_wide_as_spans_and_hairlines_as_dots() { + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 400.0)); + let square = || Path::rect(100.0, 100.0, 200.0, 200.0); + let (mut spans, mut dots, mut budget) = (Vec::new(), egui::Mesh::default(), MAX_DOTS); + selection_pattern(&mut spans, &mut dots, &item(square(), false, Some(20.0)), &Affine::IDENTITY, clip, &mut budget); + assert!(spans.iter().any(|r| r.min.x < 100.0) && !spans.iter().any(|r| r.contains(pos2(200.0, 200.0))), "the outline only, its outer half included"); + assert!(dots.vertices.is_empty()); + let mut spans = Vec::new(); + selection_pattern(&mut spans, &mut dots, &item(square(), true, Some(0.5)), &Affine::IDENTITY, clip, &mut budget); + assert!(spans.iter().any(|r| r.contains(pos2(200.0, 200.0))), "the fill"); + let n = dots.vertices.len() / 4; + assert!((250..=290).contains(&n), "a dot every {GAP} along the 800-long hairline: {n}"); + // Wholly off the view: nothing. + let (mut spans, mut dots) = (Vec::new(), egui::Mesh::default()); + selection_pattern(&mut spans, &mut dots, &item(Path::rect(900.0, 900.0, 50.0, 50.0), true, Some(0.5)), &Affine::IDENTITY, clip, &mut budget); + assert!(spans.is_empty() && dots.vertices.is_empty()); + // The pattern mesh maps each span to the repeating tile. + let mut mesh = egui::Mesh::default(); + pattern_mesh(&mut mesh, &[Rect::from_min_max(pos2(-1.5, -1.5), pos2(4.5, 1.5))]); + assert_eq!(mesh.vertices.first().map(|v| v.uv), Some(pos2(0.0, 0.0))); + assert_eq!(mesh.vertices.last().map(|v| v.uv), Some(pos2(1.0, 0.5))); + } + + /// The whole window, headless, with a big selected raw shape zoomed in (`--open selectzoom`): + /// the pattern is drawn with its texture, made once for the theme's colour. + #[test] + fn a_selected_raw_shape_draws_its_pattern_in_the_window() { + 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.open_panel(Some("selectzoom")); + assert!(!app.s.selection.is_empty() && app.view.zoom == 4.0); + let input = || egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() }; + for _ in 0..2 { + let mut out = ctx.run_ui(input(), |ui| app.frame(ui)); + out.textures_delta.clear(); + } + let first = app.stage_cache.pattern.as_ref().map(|(c, t)| (*c, t.id())); + assert_eq!(first.map(|f| f.0), Some(T.selection)); + let mut out = ctx.run_ui(input(), |ui| app.frame(ui)); + out.textures_delta.clear(); + assert_eq!(app.stage_cache.pattern.as_ref().map(|(c, t)| (*c, t.id())), first, "made once"); + } + /// The tile's dots sit on the screen grid in the old checker: dark where the row and column /// numbers add up to an even number. #[test] diff --git a/src/startup.rs b/src/startup.rs index 9f4ef198..d0f3b4c8 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -255,6 +255,36 @@ mod tests { assert_eq!(labels(&plan(Some(Auto), Dx12, WINDOWS, None)), ["wgpu (automatic)", "wgpu DirectX 12, low-power GPU", "OpenGL"], "--renderer wgpu is automatic"); } + /// Each attempt sets the window up as it says: OpenGL through glow, the others through + /// wgpu on their interface and GPU. + #[test] + fn each_attempt_sets_up_the_window_as_it_says() { + use eframe::egui_wgpu::{WgpuSetup, wgpu}; + let setup = |a: Attempt| { + let o = a.options(eframe::NativeOptions::default()); + let wgpu = match o.wgpu_options.wgpu_setup { + WgpuSetup::CreateNew(c) => Some((c.instance_descriptor.backends, c.power_preference)), + _ => None, + }; + (o.renderer, wgpu) + }; + assert_eq!(setup(Attempt { backend: OpenGl, low_power: false }).0, eframe::Renderer::Glow); + assert_eq!(setup(Attempt { backend: Dx12, low_power: true }), (eframe::Renderer::Wgpu, Some((wgpu::Backends::DX12, wgpu::PowerPreference::LowPower)))); + assert_eq!(setup(Attempt { backend: Vulkan, low_power: false }).1.map(|w| w.0), Some(wgpu::Backends::VULKAN)); + assert_eq!(setup(Attempt { backend: Metal, low_power: false }).1.map(|w| w.0), Some(wgpu::Backends::METAL)); + assert_eq!(setup(Attempt { backend: Auto, low_power: false }).0, eframe::Renderer::Wgpu); + assert_eq!(Attempt { backend: OpenGl, low_power: true }.label(), "OpenGL", "OpenGL has no GPU choice"); + } + + #[test] + fn panics_read_as_text() { + assert_eq!(panic_text(&"static"), "static"); + assert_eq!(panic_text(&String::from("owned")), "owned"); + assert_eq!(panic_text(&42), "a panic"); + // No window: logged as OpenGL, never a panic (nothing is logged without `begin`). + log_adapter(None); + } + /// #207: when the last start died inside a driver (nothing to catch), that way goes last. #[test] fn the_way_the_last_start_died_in_goes_last() {