From 167a090afee3c3171509488de5c01c276c6c0303 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 27 Nov 2026 23:11:04 -0700 Subject: [PATCH 1/6] fix(web): same-named files open, sequences arrive whole, the editor's keys stay the editor's (M8) In a real browser (headless Chrome): a picked file with the name of an open document was refused as already open; a PNG or SVG sequence lost most of its frames to the browser's limit on a run of downloads (now one ZIP); F5, Ctrl+R and other editor shortcuts were acted on by the browser (F5 reloaded the page). --- Cargo.toml | 2 +- src/app.rs | 26 +++++++++++- src/menus.rs | 6 +++ src/platform.rs | 94 +++++++++++++++++++++++++++++++++++++++++++- src/publish_panel.rs | 15 ++----- src/tabs.rs | 4 ++ src/web.rs | 47 ++++++++++++++++++++++ 7 files changed, 180 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f0869945..94e8bb22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -184,7 +184,7 @@ js-sys = "0.3" cpal = { version = "0.18", optional = true, features = ["wasm-bindgen"] } # In the browser the page's language (navigator.languages) is the system's. sys-locale = { version = "0.3", features = ["js"] } -web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] } +web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "KeyboardEvent", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] } [dev-dependencies] # Plug-in fixtures for the shell's plug-in tests, in WebAssembly text (Apache-2.0 WITH diff --git a/src/app.rs b/src/app.rs index 33bd4218..36041329 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1095,7 +1095,13 @@ impl App { if platform::WEB && id.starts_with("file.") { // In a browser, what a save or an export wrote is in memory: hand it to the // browser as downloads (ADR 0036). - platform::deliver(anicraft_engine::vfs::take_written()); + // Several files (a sequence) leave as one ZIP: a browser drops most of a run of + // downloads. + let (files, failed) = platform::as_one_download(anicraft_engine::vfs::take_written(), None); + platform::deliver(files); + if let Some(e) = failed { + self.status_err(tr!("Could not make the archive: {e}", e = e)); + } } match result { Ok(v) => { @@ -1337,6 +1343,22 @@ impl App { pub fn refresh_keymap(&mut self) { self.keymap = keymap::Keymap::new(&self.prefs.shortcuts); self.shortcuts = self.keymap.table(); + #[cfg(target_arch = "wasm32")] + crate::web::claim_keys(self.browser_keys(), platform::menu_bar_keys()); + } + + /// Every chord the editor acts on that a browser would act on first (`platform::claims_key` + /// decides per key press): the shortcut table, the fixed ones `handle_shortcuts` takes, and + /// the menu bar's (ADR 0064). + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub fn browser_keys(&self) -> Vec<(Modifiers, Key)> { + let mut keys: Vec<(Modifiers, Key)> = self.shortcuts.iter().map(|(m, k, _)| (*m, *k)).collect(); + keys.extend([(Modifiers::NONE, Key::F1), (Modifiers::COMMAND, Key::K), (Modifiers::COMMAND | Modifiers::SHIFT, Key::P), (Modifiers::COMMAND, Key::U), (Modifiers::COMMAND, Key::Comma)]); + if platform::menu_bar_keys() { + keys.push((Modifiers::NONE, Key::F10)); + keys.extend(crate::menus::top_access_keys().into_iter().map(|k| (Modifiers::ALT, k))); + } + keys } pub fn save_prefs(&mut self) { @@ -3755,6 +3777,8 @@ impl App { let done = trn!("Exported {path} ({n} frame, {layers} layers).", "Exported {path} ({n} frames, {layers} layers).", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), layers = v["layers"]); self.status_ok(format!("{done}{report}")); } + // In a browser a sequence's frames arrive as one archive named after the folder. + "file.export_png_sequence" | "file.export_svg_sequence" if platform::WEB => self.status_ok(tr!("Exported {path}.zip to your downloads", path = v.get("dir").and_then(Value::as_str).unwrap_or(""))), "file.export_png" | "file.export_png_sequence" | "file.export_svg_sequence" | "file.export_gif" | "file.export_svg" | "file.export_video" => self.status_ok(tr!("Exported {path}", path = v.get("written").or_else(|| v.get("dir")).and_then(Value::as_str).unwrap_or(""))), // Undo labels are the engine's English, translated when a catalog has them. "edit.undo" => self.status_ok(tr!("Undid {action}", action = crate::i18n::t_dyn(v["undone"].as_str().unwrap_or("")))), diff --git a/src/menus.rs b/src/menus.rs index 365137d5..0af6861d 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -71,6 +71,12 @@ fn top_labels() -> Vec { TOP_MENUS.iter().map(|t| crate::i18n::t(t).to_string()).collect() } +/// The keys that open the top menus with Alt, in the interface language. +pub fn top_access_keys() -> Vec { + let labels = top_labels(); + access_keys(&labels.iter().map(String::as_str).collect::>()).into_iter().filter_map(|k| egui::Key::from_name(&k?.1.to_string())).collect() +} + /// Each top menu's access key: `(character index, letter)`, the first letter of its title that /// no menu before it took (word starts first); ASCII letters only, so a title without one has /// none. diff --git a/src/platform.rs b/src/platform.rs index 864a6251..b3cfc496 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -211,6 +211,34 @@ pub fn menu_bar_keys() -> bool { keys_os() != Os::Mac } +/// In a browser: whether the editor takes this key press from the browser, which would +/// otherwise act on it (F5 reloads the page, Ctrl+R too, Ctrl+D bookmarks it, Alt+F opens the +/// browser's menu). `bound` is every chord the editor acts on; `alt_menus` says Alt reaches the +/// menu bar (ADR 0064). +/// +/// A key is taken only when the editor uses it, so the browser keeps the rest (F12, Ctrl+T, +/// Alt+D: the ways out of the page by keyboard). Plain typing keys are never taken (that would +/// stop text reaching a text field), nor are cut, copy and paste, which arrive as the +/// browser's clipboard events. +#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +pub fn claims_key(bound: &[(egui::Modifiers, egui::Key)], alt_menus: bool, pressed: egui::Modifiers, key: Option) -> bool { + use egui::Key; + let Some(key) = key else { + // Alt by itself focuses the browser's own menu; here it focuses the editor's. + return alt_menus && pressed.alt && !pressed.ctrl && !pressed.command && !pressed.shift; + }; + let chorded = pressed.ctrl || pressed.command || pressed.alt; + if chorded && !pressed.alt && matches!(key, Key::C | Key::X | Key::V) { + return false; + } + let function = matches!(key, Key::F1 | Key::F2 | Key::F3 | Key::F4 | Key::F5 | Key::F6 | Key::F7 | Key::F8 | Key::F9 | Key::F10 | Key::F11 | Key::F12); + if !chorded && !function { + return false; + } + // As egui matches a shortcut: extra Shift or Alt held still presses it. + bound.iter().any(|(m, k)| *k == key && pressed.matches_logically(*m)) +} + pub fn set_mac_glyphs(available: bool) { MAC_GLYPHS.store(available, Ordering::Relaxed); } @@ -1249,15 +1277,43 @@ pub fn picked_file() -> Option { None } +/// Files a command wrote: each one's path and bytes. +pub type Written = Vec<(PathBuf, Vec)>; + /// In a browser: offers each file a command saved or exported as a download. #[cfg_attr(not(target_arch = "wasm32"), allow(unused_variables))] -pub fn deliver(files: Vec<(PathBuf, Vec)>) { +pub fn deliver(files: Written) { #[cfg(target_arch = "wasm32")] for (path, data) in files { crate::web::download(&path, &data); } } +/// In a browser: what one command wrote, as one download. A single file goes as it is; several +/// (a PNG or SVG sequence, a sprite sheet with its data, a publish) go in one ZIP, because a +/// browser lets a page start only a few downloads in a row and silently drops the rest (Chrome +/// kept 10 to 18 of a 48-frame sequence). The archive is named `name`, or after the folder the +/// files share, or after the first file. When they don't fit a ZIP the files come back as they +/// were, to send one by one after all, with why. +#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +pub fn as_one_download(files: Written, name: Option<&str>) -> (Written, Option) { + use std::path::Component; + if files.len() < 2 { + return (files, None); + } + let folder = |p: &Path| match (p.components().next(), p.components().nth(1)) { + (Some(Component::Normal(f)), Some(_)) => Some(f.to_string_lossy().into_owned()), + _ => None, + }; + let shared = files.first().and_then(|(p, _)| folder(p)).filter(|f| files.iter().all(|(p, _)| folder(p).as_ref() == Some(f))); + let first = files.first().and_then(|(p, _)| p.file_stem()).map(|s| s.to_string_lossy().into_owned()); + let name = name.map(str::to_string).or(shared).or(first).filter(|n| !n.is_empty()).unwrap_or_else(|| "export".to_string()); // i18n-exempt: a file name + match anicraft_engine::publish::zip(&files) { + Ok(z) => (vec![(PathBuf::from(format!("{name}.zip")), z)], None), + Err(e) => (files, Some(e)), + } +} + /// In a browser: whether leaving the page asks first (there are unsaved changes). #[cfg_attr(not(target_arch = "wasm32"), allow(unused_variables))] pub fn set_unsaved(unsaved: bool) { @@ -1412,6 +1468,42 @@ mod tests { assert_eq!(split_suggestion(&gone.display().to_string()).0, None, "a folder that isn't there is not offered"); } + /// The web editor takes from the browser exactly the keys it acts on: F5 must insert a + /// frame, not reload the page, while typing, the clipboard and the browser's own keys stay. + #[test] + fn the_browser_keeps_every_key_the_editor_does_not_use() { + use egui::{Key, Modifiers}; + let bound = [(Modifiers::NONE, Key::F5), (Modifiers::COMMAND, Key::R), (Modifiers::NONE, Key::V), (Modifiers::COMMAND | Modifiers::SHIFT, Key::V), (Modifiers::ALT, Key::F)]; + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let claims = |m: Modifiers, k: Key| claims_key(&bound, true, m, Some(k)); + assert!(claims(Modifiers::NONE, Key::F5) && claims(ctrl, Key::R) && claims(Modifiers::ALT, Key::F)); + assert!(claims(Modifiers::SHIFT, Key::F5), "as egui matches it: Shift held still presses F5"); + assert!(!claims(Modifiers::NONE, Key::F12) && !claims(ctrl, Key::T) && !claims(Modifiers::ALT, Key::D), "unused keys are the browser's"); + assert!(!claims(Modifiers::NONE, Key::V), "a tool letter is typing in a text field"); + assert!(!claims(ctrl, Key::V) && !claims(ctrl | Modifiers::SHIFT, Key::V), "paste arrives as the browser's event"); + assert!(claims_key(&bound, true, Modifiers::ALT, None), "Alt alone is the editor's menu bar"); + assert!(!claims_key(&bound, false, Modifiers::ALT, None), "but not on a Mac, where Alt opens no menu"); + } + + /// One command's files leave the browser as one download: a browser drops most of a run + /// of downloads, so a sequence must be one archive holding every frame. + #[test] + fn several_exported_files_are_one_archive() { + let file = |p: &str| (PathBuf::from(p), p.as_bytes().to_vec()); + let one = as_one_download(vec![file("movie.gif")], None).0; + assert_eq!(one, vec![file("movie.gif")], "a single file is not wrapped"); + let frames: Vec<_> = (0..48).map(|i| file(&format!("frames/frame_{i:05}.png"))).collect(); + let (zipped, failed) = as_one_download(frames.clone(), None); + assert_eq!(failed, None); + assert_eq!(zipped.len(), 1); + assert_eq!(zipped[0].0, PathBuf::from("frames.zip"), "named after the folder the frames share"); + let listed = |name: &str| zipped[0].1.windows(name.len()).any(|w| w == name.as_bytes()); + assert!(frames.iter().all(|(p, _)| listed(&p.display().to_string().replace('\\', "/"))), "every frame is in it"); + let sheet = as_one_download(vec![file("sprites.png"), file("sprites.json")], None).0; + assert_eq!(sheet[0].0, PathBuf::from("sprites.zip"), "no shared folder: after the first file"); + assert_eq!(as_one_download(frames, Some("walk")).0[0].0, PathBuf::from("walk.zip")); + } + #[test] fn the_desktop_runs_every_command() { assert!(anicraft_engine::commands().iter().all(|c| unavailable(c.id).is_none())); diff --git a/src/publish_panel.rs b/src/publish_panel.rs index ebc34847..49442d7d 100644 --- a/src/publish_panel.rs +++ b/src/publish_panel.rs @@ -240,17 +240,10 @@ fn finish(app: &mut App, job: Job) { if crate::platform::WEB { // In a browser the files are in memory: they go to the downloads, in one ZIP when there // are several (ADR 0060). - let written = anicraft_engine::vfs::take_written(); - if written.len() > 1 { - match publish::zip(&written) { - Ok(z) => crate::platform::deliver(vec![(std::path::PathBuf::from(format!("{}.zip", job.name)), z)]), - Err(e) => { - app.status_err(tr!("Could not make the archive: {e}", e = e)); - crate::platform::deliver(written); - } - } - } else { - crate::platform::deliver(written); + let (files, failed) = crate::platform::as_one_download(anicraft_engine::vfs::take_written(), Some(&job.name)); + crate::platform::deliver(files); + if let Some(e) = failed { + app.status_err(tr!("Could not make the archive: {e}", e = e)); } } let (ok, failed, skipped) = (report.count(Status::Published), report.count(Status::Failed), report.count(Status::Skipped)); diff --git a/src/tabs.rs b/src/tabs.rs index 239281d0..4c592670 100644 --- a/src/tabs.rs +++ b/src/tabs.rs @@ -417,6 +417,10 @@ fn already_open(app: &App, id: &str, params: &Value) -> Option { return None; } let path = match id { + // In a browser an opened file is one just picked or dropped, known only by its name: + // a second file may share it (a backup from another folder), and even the same file + // may have changed on disk since. It always opens, in a tab of its own. + "file.open" if platform::WEB => return None, "file.open" => PathBuf::from(params.get("path")?.as_str()?), "file.open_recent" => match (params.get("index").and_then(Value::as_u64), params.get("path").and_then(Value::as_str)) { (Some(i), _) => app.s.recent.entries().get(usize::try_from(i).ok()?)?.path.clone(), diff --git a/src/web.rs b/src/web.rs index 73d41d32..cd525ae1 100644 --- a/src/web.rs +++ b/src/web.rs @@ -53,6 +53,9 @@ thread_local! { /// Dropped files read so far, by ticket: each file's name and bytes. static DROPPED: RefCell> = const { RefCell::new(Vec::new()) }; static TICKET: Cell = const { Cell::new(0) }; + /// The chords the editor acts on, and whether Alt reaches its menu bar: the key presses + /// taken from the browser (`platform::claims_key`). + static KEYS: RefCell<(Vec<(egui::Modifiers, egui::Key)>, bool)> = const { RefCell::new((Vec::new(), false)) }; } /// Starts the editor on the page's canvas. @@ -60,6 +63,7 @@ pub fn start() { let mac = web_sys::window().and_then(|w| w.navigator().user_agent().ok()).is_some_and(|ua| ua.contains("Mac")); crate::platform::set_web_on_mac(mac); guard_leaving(); + guard_keys(); wasm_bindgen_futures::spawn_local(async { match run().await { Ok(()) => { @@ -299,6 +303,49 @@ fn guard_leaving() { } } +// ----- keys ------------------------------------------------------------------------------------- + +/// Tells the page which chords the editor acts on (its shortcut table changed). +pub fn claim_keys(bound: Vec<(egui::Modifiers, egui::Key)>, alt_menus: bool) { + KEYS.with(|k| *k.borrow_mut() = (bound, alt_menus)); +} + +/// Keeps the browser from acting on the editor's shortcuts: F5 inserts a frame instead of +/// reloading the page, Ctrl+R imports instead of reloading, Alt+F opens the editor's File menu. +/// eframe stops only a few (Ctrl+S, Ctrl+O, Ctrl+P, Tab, the arrows) and leaves F5 and Ctrl+R +/// to the browser on purpose. The key still reaches the editor: only the browser's own action +/// is called off, and only for keys the editor uses (`platform::claims_key`). +fn guard_keys() { + let Some(window) = web_sys::window() else { return }; + let on_key = Closure::::new(|e: web_sys::KeyboardEvent| { + // The same reading of the event as eframe's, so both see one key. + // (Alt's own release no longer counts it as held.) + let pressed = egui::Modifiers { alt: e.alt_key() || e.key() == "Alt", ctrl: e.ctrl_key(), shift: e.shift_key(), mac_cmd: e.meta_key(), command: e.ctrl_key() || e.meta_key() }; + let name = e.key(); + let key = egui::Key::from_name(&name).or_else(|| egui::Key::from_name(&e.code())); + // AltGr types a character (€, @ on many layouts): never a shortcut to take. + if (key.is_none() && name != "Alt") || e.get_modifier_state("AltGraph") { // i18n-exempt: DOM key names + return; + } + if KEYS.with(|k| { + let k = k.borrow(); + crate::platform::claims_key(&k.0, k.1, pressed, key) + }) { + e.prevent_default(); + } + }); + // In the capture phase, on the window: before eframe's listeners on the canvas, which stop + // the event from going further. + let mut held = false; + for kind in ["keydown", "keyup"] { + held |= window.add_event_listener_with_callback_and_bool(kind, on_key.as_ref().unchecked_ref(), true).is_ok(); + } + if held { + // Lives as long as the page. + on_key.forget(); + } +} + // ----- storage ---------------------------------------------------------------------------------- fn storage() -> Option { From f87ad99b5aaacd5a3cef1e9ee3818d191a8c50d6 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 27 Nov 2026 23:11:05 -0700 Subject: [PATCH 2/6] test(web): the web editor in a real browser, end to end (M8) --- tests/web_browser.rs | 492 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 492 insertions(+) create mode 100644 tests/web_browser.rs diff --git a/tests/web_browser.rs b/tests/web_browser.rs new file mode 100644 index 00000000..0688153e --- /dev/null +++ b/tests/web_browser.rs @@ -0,0 +1,492 @@ +//! The web editor in a real browser (ADR 0137, docs/web.md): what an artist does there, end to +//! end, in headless Chrome or Edge driven over the DevTools protocol. It serves the built +//! `web/` folder on this computer, then starts the editor, saves (a download), opens a file +//! (the browser's file picker), imports, exports a sequence, presses the editor's shortcuts, and +//! reloads to see preferences and autosave kept. Every check reads what the browser itself +//! shows: the downloads folder, the site's storage, whether the page was reloaded. +//! +//! It needs the built bundle and a browser, so it is not part of `cargo test`: +//! `scripts/web-check.sh` builds `web/` and runs it. `ANICRAFT_WEB_DIR` names another bundle +//! (an unzipped release asset), `ANICRAFT_BROWSER` the browser, and `ANICRAFT_BROWSER_ARGS` +//! adds arguments (`--no-sandbox` in a container). +//! +//! Only the standard library: a few lines of HTTP for the site and of WebSocket (RFC 6455) for +//! the protocol, both to 127.0.0.1 only. +#![cfg(not(target_arch = "wasm32"))] + +use serde_json::{Value, json}; +use std::collections::VecDeque; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::time::{Duration, Instant}; + +// ----- the site --------------------------------------------------------------------------------- + +/// Serves `root` on 127.0.0.1 for as long as the test runs; returns its address. +fn serve(root: PathBuf) -> String { + let listener = TcpListener::bind("127.0.0.1:0").expect("a local port"); + let addr = listener.local_addr().expect("its address"); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let root = root.clone(); + std::thread::spawn(move || answer(stream, &root)); + } + }); + format!("http://{addr}/") +} + +fn answer(mut stream: TcpStream, root: &Path) { + let mut reader = BufReader::new(stream.try_clone().expect("a second handle")); + let mut first = String::new(); + if reader.read_line(&mut first).is_err() { + return; + } + // The rest of the request: headers up to the empty line. + let mut line = String::new(); + while reader.read_line(&mut line).is_ok_and(|n| n > 2) { + line.clear(); + } + let path = first.split_whitespace().nth(1).unwrap_or("/").split(['?', '#']).next().unwrap_or("/"); + let mut file = root.to_path_buf(); + for part in path.split('/').filter(|p| !p.is_empty() && *p != "." && *p != "..") { + file.push(part); + } + if file.is_dir() { + file.push("index.html"); + } + let kind = match file.extension().and_then(|e| e.to_str()) { + Some("html") => "text/html; charset=utf-8", + Some("js") => "text/javascript", + Some("wasm") => "application/wasm", + Some("png") => "image/png", + Some("css") => "text/css", + _ => "application/octet-stream", + }; + let _ = match std::fs::read(&file) { + Ok(body) => stream.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()).and_then(|()| stream.write_all(&body)), + Err(_) => stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"), + }; +} + +// ----- the browser ------------------------------------------------------------------------------ + +fn find_browser() -> PathBuf { + if let Some(b) = std::env::var_os("ANICRAFT_BROWSER") { + return PathBuf::from(b); + } + let fixed = [ + r"C:\Program Files\Google\Chrome\Application\chrome.exe", + r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", + r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", + r"C:\Program Files\Microsoft\Edge\Application\msedge.exe", + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + ]; + let named = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"]; + let on_path = std::env::var_os("PATH").into_iter().flat_map(|p| std::env::split_paths(&p).collect::>()).flat_map(|dir| named.map(|n| dir.join(n))); + fixed.iter().map(PathBuf::from).chain(on_path).find(|p| p.is_file()).expect("no Chrome, Chromium or Edge found: set ANICRAFT_BROWSER to one") +} + +/// The browser process; it and its profile folder go when the test ends, passed or failed. +struct Browser { + child: Child, + dir: PathBuf, +} + +impl Drop for Browser { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + // The browser lets go of its profile a moment after it dies. + for _ in 0..20 { + if std::fs::remove_dir_all(&self.dir).is_ok() { + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + } +} + +/// Starts the browser headless with a fresh profile under `dir`; returns it and the address of +/// its DevTools WebSocket. +fn launch(dir: &Path) -> (Browser, String) { + let exe = find_browser(); + let extra: Vec = std::env::var("ANICRAFT_BROWSER_ARGS").map(|a| a.split_whitespace().map(str::to_string).collect()).unwrap_or_default(); + let mut child = Command::new(&exe) + .args(["--headless=new", "--remote-debugging-port=0", "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--window-size=1400,900"]) + // WebGL2 without a graphics card (a CI runner). + .arg("--enable-unsafe-swiftshader") + .arg(format!("--user-data-dir={}", dir.join("profile").display())) + .args(extra) + .arg("about:blank") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap_or_else(|e| panic!("could not start {}: {e}", exe.display())); + let stderr = child.stderr.take().expect("the browser's stderr"); + let (tx, rx) = channel(); + // Read to the end, so the browser never blocks on a full pipe. + std::thread::spawn(move || { + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if let Some(url) = line.strip_prefix("DevTools listening on ") { + let _ = tx.send(url.trim().to_string()); + } + } + }); + let browser = Browser { child, dir: dir.to_path_buf() }; + let url = rx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| panic!("{} did not say where its DevTools port is", exe.display())); + (browser, url) +} + +// ----- the DevTools protocol over a WebSocket --------------------------------------------------- + +/// One connection to the browser: calls go out, answers and events come back as JSON. +struct DevTools { + out: TcpStream, + incoming: Receiver, + next: u64, + session: Option, + /// Events not yet looked at, oldest first. + events: VecDeque, +} + +impl DevTools { + fn connect(url: &str) -> DevTools { + let rest = url.strip_prefix("ws://").expect("a ws:// address"); + let (host, path) = rest.split_once('/').expect("a path after the host"); + let mut out = TcpStream::connect(host).expect("the DevTools port"); + // The opening handshake (RFC 6455 §4.1); the key is any 16 bytes in base64. + write!(out, "GET /{path} HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: QW5pQ3JhZnRXZWJDaGVjaw==\r\nSec-WebSocket-Version: 13\r\n\r\n").expect("the handshake"); + let mut reader = BufReader::new(out.try_clone().expect("a second handle")); + let mut status = String::new(); + reader.read_line(&mut status).expect("the handshake's answer"); + assert!(status.contains("101"), "the browser refused the WebSocket: {status}"); + let mut line = String::new(); + while reader.read_line(&mut line).is_ok_and(|n| n > 2) { + line.clear(); + } + let (tx, incoming) = channel(); + std::thread::spawn(move || { + while let Some(text) = read_message(&mut reader) { + if let Ok(v) = serde_json::from_slice::(&text) + && tx.send(v).is_err() + { + break; + } + } + }); + DevTools { out, incoming, next: 0, session: None, events: VecDeque::new() } + } + + /// Calls `method` and waits for its answer; events that arrive meanwhile are kept. + fn call(&mut self, method: &str, params: Value) -> Value { + self.next += 1; + let id = self.next; + let mut msg = json!({"id": id, "method": method, "params": params}); + if let Some(s) = &self.session { + msg["sessionId"] = json!(s); + } + send_text(&mut self.out, msg.to_string().as_bytes()); + let until = Instant::now() + Duration::from_secs(60); + loop { + let v = match self.incoming.recv_timeout(until.saturating_duration_since(Instant::now())) { + Ok(v) => v, + Err(RecvTimeoutError::Timeout) => panic!("{method} got no answer in a minute"), + Err(RecvTimeoutError::Disconnected) => panic!("the browser closed the connection during {method}"), + }; + if v["id"].as_u64() == Some(id) { + assert!(v.get("error").is_none(), "{method} failed: {}", v["error"]); + return v["result"].clone(); + } + if v.get("method").is_some() { + self.events.push_back(v); + } + } + } + + /// Takes in what arrived, for up to `wait`. + fn pump(&mut self, wait: Duration) { + let until = Instant::now() + wait; + while let Ok(v) = self.incoming.recv_timeout(until.saturating_duration_since(Instant::now())) { + if v.get("method").is_some() { + self.events.push_back(v); + } + } + } + + /// The first kept event named `method`, taken out; waits up to `wait` for one. + fn event(&mut self, method: &str, wait: Duration) -> Option { + let until = Instant::now() + wait; + loop { + if let Some(i) = self.events.iter().position(|e| e["method"] == method) { + return self.events.remove(i); + } + if Instant::now() >= until { + return None; + } + self.pump(Duration::from_millis(50)); + } + } + + /// The value of a JavaScript expression in the page. + fn eval(&mut self, expression: &str) -> Value { + let r = self.call("Runtime.evaluate", json!({"expression": expression, "returnByValue": true})); + assert!(r.get("exceptionDetails").is_none(), "{expression} threw: {}", r["exceptionDetails"]); + r["result"]["value"].clone() + } + + /// Presses and lets go of a key. `text` is what it types, for keys that type. + fn key(&mut self, key: &str, code: &str, vk: u32, ctrl: bool, text: Option<&str>) { + let mut down = json!({"type": if text.is_some() { "keyDown" } else { "rawKeyDown" }, "key": key, "code": code, "windowsVirtualKeyCode": vk, "nativeVirtualKeyCode": vk, "modifiers": if ctrl { 2 } else { 0 }}); + if let Some(t) = text { + down["text"] = json!(t); + } + let mut up = down.clone(); + up["type"] = json!("keyUp"); + self.call("Input.dispatchKeyEvent", down); + self.call("Input.dispatchKeyEvent", up); + // A frame or two for the editor to act on it. + self.pump(Duration::from_millis(400)); + } + + fn ctrl(&mut self, letter: char) { + let upper = letter.to_ascii_uppercase(); + self.key(&letter.to_string(), &format!("Key{upper}"), upper as u32, true, None); + } + + fn enter(&mut self) { + self.key("Enter", "Enter", 13, false, Some("\r")); + } + + /// Answers the file picker the page just opened with `file`. + fn choose(&mut self, file: &Path) { + let opened = self.event("Page.fileChooserOpened", Duration::from_secs(10)).expect("the browser's file picker did not open"); + self.call("DOM.setFileInputFiles", json!({"files": [file.display().to_string()], "backendNodeId": opened["params"]["backendNodeId"]})); + self.pump(Duration::from_millis(1500)); + } +} + +/// Sends one masked text frame (RFC 6455 §5.2; a client must mask, the key may be anything). +fn send_text(out: &mut TcpStream, payload: &[u8]) { + let mut frame = vec![0x81]; + match payload.len() { + n if n < 126 => frame.push(0x80 | n as u8), + n if n < 65_536 => { + frame.push(0x80 | 126); + frame.extend_from_slice(&(n as u16).to_be_bytes()); + } + n => { + frame.push(0x80 | 127); + frame.extend_from_slice(&(n as u64).to_be_bytes()); + } + } + let mask = [0x41, 0x6e, 0x69, 0x43]; + frame.extend_from_slice(&mask); + frame.extend(payload.iter().zip(mask.iter().cycle()).map(|(b, m)| b ^ m)); + out.write_all(&frame).expect("the browser took the message"); +} + +/// Reads one whole message (its frames joined); `None` when the connection closes. +fn read_message(reader: &mut impl Read) -> Option> { + let mut message = Vec::new(); + loop { + let mut head = [0u8; 2]; + reader.read_exact(&mut head).ok()?; + let len = match head[1] & 0x7f { + 126 => { + let mut b = [0u8; 2]; + reader.read_exact(&mut b).ok()?; + u64::from(u16::from_be_bytes(b)) + } + 127 => { + let mut b = [0u8; 8]; + reader.read_exact(&mut b).ok()?; + u64::from_be_bytes(b) + } + n => u64::from(n), + }; + let mut payload = vec![0u8; usize::try_from(len).ok()?]; + reader.read_exact(&mut payload).ok()?; + match head[0] & 0x0f { + // A close frame. + 8 => return None, + // Pings and pongs carry nothing for us. + 9 | 10 => continue, + _ => message.extend_from_slice(&payload), + } + if head[0] & 0x80 != 0 { + return Some(message); + } + } +} + +// ----- the run ---------------------------------------------------------------------------------- + +/// The downloads the page started since the last call, each finished: its name and bytes. +/// Counted from the browser's own download events, so a file is read only once it is whole and +/// nothing else in the folder is mistaken for one. Waits for the first to start. +fn downloaded(dir: &Path, t: &mut DevTools) -> Vec<(String, Vec)> { + let mut begun: Vec<(String, String)> = Vec::new(); + let mut done: Vec = Vec::new(); + let until = Instant::now() + Duration::from_secs(120); + // A run of downloads takes a moment to all start (or to be dropped by the browser). + let mut quiet = Instant::now() + Duration::from_secs(90); + while Instant::now() < until && (Instant::now() < quiet || begun.iter().any(|(guid, _)| !done.contains(guid))) { + while let Some(e) = t.event("Browser.downloadWillBegin", Duration::ZERO) { + let p = &e["params"]; + begun.push((p["guid"].as_str().unwrap_or_default().to_string(), p["suggestedFilename"].as_str().unwrap_or_default().to_string())); + quiet = Instant::now() + Duration::from_millis(1500); + } + while let Some(e) = t.event("Browser.downloadProgress", Duration::ZERO) { + let p = &e["params"]; + assert_ne!(p["state"], "canceled", "the browser cancelled a download"); + if p["state"] == "completed" { + done.push(p["guid"].as_str().unwrap_or_default().to_string()); + } + } + t.pump(Duration::from_millis(100)); + } + assert!(begun.iter().all(|(guid, _)| done.contains(guid)), "a download did not finish: {begun:?}"); + begun.into_iter().map(|(_, name)| (name.clone(), std::fs::read(dir.join(&name)).unwrap_or_else(|e| panic!("the download {name}: {e}")))).collect() +} + +/// Waits until the editor runs on the page (its loading text is gone), and gives it the keyboard. +fn started(t: &mut DevTools) { + let until = Instant::now() + Duration::from_secs(180); + loop { + let text = t.eval("document.getElementById('anicraft_loading')?.textContent ?? null"); + match text.as_str() { + None => break, + Some(s) if s.contains("could not start") => panic!("{s}"), + Some(_) => assert!(Instant::now() < until, "the editor did not start in three minutes"), + } + t.pump(Duration::from_millis(250)); + } + t.pump(Duration::from_millis(1000)); + t.eval("document.getElementById('anicraft_canvas').focus(); true"); + // Leave the start screen for the document (the sample animation). + t.key("Escape", "Escape", 27, false, None); +} + +fn names(files: &[(String, Vec)]) -> Vec<&str> { + files.iter().map(|(n, _)| n.as_str()).collect() +} + +/// How many files a ZIP archive lists (its end record, PKWARE APPNOTE 4.3.16). +fn zip_entries(zip: &[u8]) -> usize { + zip.windows(4).rposition(|w| w == b"PK\x05\x06").and_then(|at| zip.get(at + 10..at + 12)).map_or(0, |n| usize::from(u16::from_le_bytes([n[0], n[1]]))) +} + +#[test] +#[ignore = "needs the built web/ folder and Chrome, Chromium or Edge: run scripts/web-check.sh"] +fn an_artist_can_work_in_a_real_browser() { + let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let web = std::env::var_os("ANICRAFT_WEB_DIR").map_or_else(|| repo.join("web"), PathBuf::from); + for f in ["index.html", "anicraft.js", "anicraft_bg.wasm"] { + assert!(web.join(f).is_file(), "{} is missing: build the web editor first (scripts/build-web.sh)", web.join(f).display()); + } + let dir = std::env::temp_dir().join(format!("anicraft-web-check-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let got = dir.join("downloads"); + std::fs::create_dir_all(&got).expect("a folder for the downloads"); + let site = serve(web); + let (_browser, ws) = launch(&dir); + let mut t = DevTools::connect(&ws); + let target = t.call("Target.createTarget", json!({"url": "about:blank"}))["targetId"].clone(); + t.call("Browser.setDownloadBehavior", json!({"behavior": "allow", "downloadPath": got.display().to_string(), "eventsEnabled": true})); + let session = t.call("Target.attachToTarget", json!({"targetId": target, "flatten": true}))["sessionId"].as_str().expect("a session").to_string(); + t.session = Some(session); + for domain in ["Page.enable", "Runtime.enable", "DOM.enable"] { + t.call(domain, json!({})); + } + t.call("Page.setInterceptFileChooserDialog", json!({"enabled": true})); + t.call("Emulation.setDeviceMetricsOverride", json!({"width": 1400, "height": 900, "deviceScaleFactor": 1, "mobile": false})); + t.call("Page.navigate", json!({"url": site})); + started(&mut t); + + // Save: the name is asked once, then the document arrives in the downloads (#55). + t.ctrl('s'); + t.enter(); + let first = downloaded(&got, &mut t); + assert_eq!(first.len(), 1, "Save downloads the document: {:?}", names(&first)); + let (name, saved) = &first[0]; + let sample: Value = serde_json::from_slice(saved).expect("the saved document is the .anicraft JSON"); + + // Preferences are kept in the site's storage (#56): the saved file is now a recent one. + let prefs = t.eval("localStorage.getItem('anicraft.prefs')"); + assert!(prefs.as_str().is_some_and(|p| p.contains(name.as_str())), "the preferences in the site's storage list the saved file as recent: {prefs}"); + + // Open (#55): another document that happens to have the open one's name, as a backup in + // another folder does. It opens; saving it downloads it, not the first one again. + let other = dir.join("other").join(name); + std::fs::create_dir_all(other.parent().expect("its folder")).expect("a folder"); + std::fs::copy(repo.join("crates/engine/tests/fixtures/armature-v3-shape.anicraft"), &other).expect("the fixture document"); + t.ctrl('o'); + t.choose(&other); + t.ctrl('s'); + let second = downloaded(&got, &mut t); + assert_eq!(second.len(), 1, "saving the opened document downloads it: {:?}", names(&second)); + let reopened: Value = serde_json::from_slice(&second[0].1).expect("a document"); + assert_ne!(reopened, sample, "the picked file opened, though a document with its name was open"); + + // Import to Stage (Ctrl+R, which a browser would reload the page on): the picture is in + // the document that is saved next. + t.eval("window.anicraftCheck = true"); + let picture = repo.join("assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png"); + t.ctrl('r'); + t.choose(&picture); + t.ctrl('s'); + let third = downloaded(&got, &mut t); + assert_eq!(third.len(), 1, "saving after the import: {:?}", names(&third)); + assert!(third[0].1.len() > second[0].1.len(), "the imported picture is in the saved document"); + + // F5 inserts a frame, as in the desktop app; it must not reload the page (the document is + // saved, so nothing would even ask). + t.key("F5", "F5", 116, false, None); + t.pump(Duration::from_millis(1500)); + assert_eq!(t.eval("window.anicraftCheck === true"), json!(true), "F5 and Ctrl+R are the editor's keys: the page was not reloaded"); + + // Export a PNG sequence from the command palette: every frame arrives, as one archive (a + // browser drops most of a run of downloads). + t.ctrl('k'); + t.call("Input.insertText", json!({"text": "Export PNG Sequence"})); + t.pump(Duration::from_millis(500)); + t.enter(); + t.enter(); + let frames = downloaded(&got, &mut t); + assert_eq!(frames.len(), 1, "a sequence is one download: {:?}", names(&frames)); + assert!(frames[0].0.ends_with(".zip"), "an archive: {:?}", names(&frames)); + let entries = zip_entries(&frames[0].1); + assert!(entries > 1, "the archive holds the frames: {entries}"); + + // Preferences are read back when the page loads (#56): with autosave set to every edit, + // one edit after a reload leaves a recovery copy in the site's storage at once. + t.eval("(() => { const p = JSON.parse(localStorage.getItem('anicraft.prefs')); p.autosave_edits = 1; localStorage.setItem('anicraft.prefs', JSON.stringify(p)); return true; })()"); + t.call("Page.reload", json!({})); + // Unsaved work (the inserted frame) asks before leaving: the browser's own question. + assert!(t.event("Page.javascriptDialogOpening", Duration::from_secs(10)).is_some(), "leaving with unsaved work asks first"); + t.call("Page.handleJavaScriptDialog", json!({"accept": true})); + t.pump(Duration::from_millis(1000)); + started(&mut t); + assert_eq!(t.eval("window.anicraftCheck ?? null"), Value::Null, "the page was reloaded"); + let recovery = "Object.keys(localStorage).filter((k) => k.startsWith('anicraft.recovery.')).length"; + assert_eq!(t.eval(recovery), json!(0), "nothing to recover before an edit"); + t.key("F5", "F5", 116, false, None); + let until = Instant::now() + Duration::from_secs(20); + while t.eval(recovery) == json!(0) && Instant::now() < until { + // The pointer moving keeps frames coming, as an artist at work does. + t.call("Input.dispatchMouseEvent", json!({"type": "mouseMoved", "x": 700, "y": 300})); + t.pump(Duration::from_millis(300)); + } + assert_ne!(t.eval(recovery), json!(0), "the reloaded editor read autosave-every-edit from its preferences and kept a recovery copy"); + assert_eq!(t.eval("JSON.parse(localStorage.getItem('anicraft.prefs')).autosave_edits"), json!(1), "and the preference is still what was set"); + + // Nothing went wrong on the way that the page reported. + t.pump(Duration::from_millis(300)); + let errors: Vec = t.events.iter().filter(|e| e["method"] == "Runtime.exceptionThrown" || (e["method"] == "Runtime.consoleAPICalled" && e["params"]["type"] == "error")).map(Value::to_string).collect(); + assert!(errors.is_empty(), "the page reported errors: {errors:?}"); +} From 70aa47c07fe8fbd307bede3cf09f9f6b7d8ad12f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 27 Nov 2026 23:39:34 -0700 Subject: [PATCH 3/6] docs(web): ADR 0137, the browser check's script, the web guide and roadmap P-007 (M8) --- CHANGELOG.md | 16 +++ ...web-editor-is-checked-in-a-real-browser.md | 121 ++++++++++++++++++ docs/guide/exporting-and-publish.md | 4 +- docs/guide/troubleshooting-and-faq.md | 6 +- docs/roadmap.md | 4 +- docs/web.md | 58 +++++++-- scripts/web-check.ps1 | 14 ++ scripts/web-check.sh | 20 +++ tests/web_browser.rs | 2 +- 9 files changed, 226 insertions(+), 19 deletions(-) create mode 100644 docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md create mode 100644 scripts/web-check.ps1 create mode 100755 scripts/web-check.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 3410d4d8..c110e1b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +* **The web editor, tried in a real browser** (M8, backlog P-007, ADR 0137; #55, #56). We ran + the browser build in Chrome the way an artist would and fixed what broke. + * **F5 inserts a frame instead of reloading the page.** The browser used to act on the + editor's shortcuts first: F5 and Ctrl+R (Import to Stage) reloaded the page, Ctrl+D + bookmarked it, Alt+F opened the browser's menu. The editor now keeps the keys it uses; + the rest (F12, Ctrl+T, Alt+D) stay the browser's. Ctrl+N and Ctrl+W can't be had by any + page: use the File menu or the command palette. + * **A PNG or SVG sequence arrives whole, as one ZIP.** It used to be one download per frame, + and the browser quietly dropped most of them (10 to 18 of 48). A sprite sheet with its + frame map is one ZIP too. + * **A file with the name of an open document opens**, in its own tab. It was refused as + "already open", so a backup from another folder couldn't be opened. + * Saving, opening, importing and exporting (#55) and preferences kept across a reload (#56) + are now checked in headless Chrome by `scripts/web-check.sh`. Releases don't carry the web + build yet (#316): the zip is made, the release workflow has to be told to attach it. + ## 0.3.0 (2026-11-28) The first release since 0.2.1 (2026-11-12). It carries everything listed below, from the Flash 8 to diff --git a/docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md b/docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md new file mode 100644 index 00000000..72caf19f --- /dev/null +++ b/docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md @@ -0,0 +1,121 @@ +# ADR 0137: The web editor is checked in a real browser, and keeps its keys and its files there + +* Status: accepted (2026-11-27) +* Relates to: backlog item P-007 (`docs/roadmap.md`), issues + [#55](https://github.com/storytold/anicraft/issues/55), + [#56](https://github.com/storytold/anicraft/issues/56), + [#316](https://github.com/storytold/anicraft/issues/316) and + [#210](https://github.com/storytold/anicraft/issues/210), ADR 0036 (the web build), ADR 0015 + (autosave), ADR 0060 (publish), ADR 0064 (the menu bar from the keyboard), ADR 0112 (several + documents), `docs/web.md` + +## Context + +ADR 0036 built the editor for the browser and tested it everywhere but in one: every crate +builds for wasm32, the engine's tests run inside WebAssembly in Node, and the file commands run +natively against the in-memory store. `docs/web.md` said so: "There was no browser on the build +machine." #55 ("import, export and save do not work") and #56 ("preferences are not saved") +were filed before that slice, and nobody could say from a test whether they still held. + +So we ran the optimized bundle in headless Chrome 158 and did what an artist does. Most of it +worked: the editor starts (1.7 to 1.9 s to the first frame here), Save downloads the document, +Open and the imports use the browser's picker, ten of the eleven exports on the menu download +(the sample's sprite sheet is past its pixel limit and says so; video is dimmed), preferences +survive a reload, and a reload after the autosave interval offers the copy. Three +things did not, and none of them could have been seen without a browser: + +* **A file with the name of an open document would not open.** The shell asks "is this file + already open?" by path, and in a browser a picked file's path is its name. Picking + `animation.anicraft` while a document of that name was open showed "already open" and threw + the picked bytes away: a backup from another folder, or the same file edited since, could + not be opened at all. +* **Sequences lost most of their frames.** A PNG or SVG sequence went out as one download per + frame. A browser lets a page start only a few downloads in a row and drops the rest without + telling the page: of a 48-frame sequence Chrome kept 18 PNG files in one run and 10 SVG + files in the next, and the status bar said the export had worked. +* **The browser acted on the editor's shortcuts.** eframe keeps a handful of keys from the + browser (Ctrl+S, Ctrl+O, Ctrl+P, Tab, the arrows) and leaves the rest, F5 and Ctrl+R by + name. F5 is Insert Frame, the key an animator presses most: in the web editor it reloaded + the page, at once when the document was saved. Ctrl+R (Import to Stage) did the same, and + Ctrl+D, Ctrl+G, Ctrl+L, Ctrl+U, F6, F7 and Alt+F went to bookmarks, find, the address bar, + the page source, the browser's toolbar and its menu. + +## Decision + +1. **The web editor has a check that runs it in a real browser** (`tests/web_browser.rs`, run + by `scripts/web-check.sh` after `scripts/build-web.sh`). It serves the built `web/` folder + on 127.0.0.1, starts Chrome, Chromium or Edge headless with a fresh profile, and drives the + page over the DevTools protocol: start, Save, Open (a file with the open document's name), + Import to Stage, F5, a PNG sequence from the command palette, then a reload to see that + preferences are read back and autosave keeps a copy. + * **Rust, standard library only.** Rule 11 keeps the repository free of handwritten + JavaScript, and the protocol needs little: an HTTP answer per file and a WebSocket client + (RFC 6455) that sends masked text frames and joins the frames it reads, about a hundred + lines, to this computer only. No new dependency. + * **It reads only what the browser itself shows**: the downloads the page started (from the + browser's download events, read when complete), the site's storage, the file picker + opening, the leave-page question, whether the page was reloaded, and errors the page + reports. It never reads pixels and never clicks at a coordinate: every step is a key an + artist presses (Ctrl+S, Ctrl+O, Ctrl+R, F5, Ctrl+K and a command's name), so a change to + the layout does not break it. + * **It is not part of `cargo test`.** It needs a six-minute wasm build and a browser, so it + is marked `#[ignore]` with the reason and the script runs it; a missing bundle or browser + fails with what to do, never passes quietly. `ANICRAFT_WEB_DIR` points it at any bundle, + so the same check runs on an unzipped release asset. + +2. **In a browser a picked or dropped file always opens, in a tab of its own.** `file.open` + there never counts as "already open": the name is all the page knows of the file. Open + Recent still shows the open tab, since that is the copy the page holds. + +3. **What one command writes leaves as one download**: the file itself, or one ZIP when there + are several (`platform::as_one_download`, the archive Publish already made, ADR 0060). A + sequence arrives as `frames.zip` with its folder inside, a sprite sheet with its frame map + as `sprites.zip`. The archive is named after the folder the files share, else the first + file. If the files don't fit a ZIP (65,535 files, 4 GB) they go one by one after all and + the status bar says why. + +4. **The editor takes from the browser the keys it acts on, and only those** + (`platform::claims_key`, called from a key listener on the window in `web.rs`). The list is + the shortcut table as the user set it, the fixed keys (F1, Ctrl+K, Ctrl+U, Ctrl+,), and on + Windows and Linux F10, Alt alone and Alt with a menu's letter (ADR 0064). The browser's own + action is called off; the key reaches the editor as before. + * **Everything else stays the browser's**, so the keyboard is never trapped in the page: + F12, Ctrl+T, Ctrl+Tab, Alt+D and whatever the user unbinds. + * **Typing is never taken**: a key without Ctrl, ⌘ or Alt that is not a function key is + left alone (calling it off would stop text reaching a text field), as is anything typed + with AltGr. **Cut, copy and paste are never taken**: they arrive as the browser's + clipboard events. + * A browser does not let any page have Ctrl+N, Ctrl+T or Ctrl+W (⌘ on a Mac): New and Close + are in the File menu and the command palette there, and `docs/web.md` says so. + +5. **Release packaging stays the team's.** The app side is done: `packaging/web/package.sh` + makes `dist/release/anicraft-web-.zip` and the Web CI job runs it on every PR. + What the workflows need, each in a PR of its own (rule 17): `has-web: true` in + `.github/workflows/release.yml`, which makes the family release workflow run that script + and attach the zip (#316, #210); and one line in `.github/workflows/web.yml` after the + packaging step, `ANICRAFT_WEB_DIR=web cargo test -p anicraft --test web_browser --locked -- + --ignored` (on a runner that has Chrome or Chromium; in a container add + `ANICRAFT_BROWSER_ARGS=--no-sandbox`). + +## Consequences + +* #55 and #56 are answered by a test instead of a reading of the code: Save, Open, Import and + Export work in Chrome, and preferences are written to and read from the site's storage. +* The check takes 21 s once the bundle is built (five runs in a row here, all green). Against + the bundle built from the code before this change it fails at the second step, with the + first document saved again in place of the picked one. +* A sequence in the browser is now always an archive, even a short one. One more step to + unpack it, and no frame is lost. +* An artist who pressed F5 to reload the page uses the browser's button; the editor says + nothing about it because nothing happens that needs saying: a frame is inserted, as on the + desktop. + +## Not in this slice + +* The check runs by hand and from the script; CI runs it once the workflow line above is in. +* Firefox and Safari: the check drives Chromium browsers only (the DevTools protocol). The + key listener and the ZIP use nothing specific to one browser. +* A copy written when the tab is hidden or closed (autosave still waits for its interval or + its count of edits), a real "Save" to a chosen file through the File System Access API, + IndexedDB for large recovery copies, and the size of the download (21.5 MB here, 6.8 MB + gzipped, built without the craft-fonts faces). diff --git a/docs/guide/exporting-and-publish.md b/docs/guide/exporting-and-publish.md index a7c1a554..66435653 100644 --- a/docs/guide/exporting-and-publish.md +++ b/docs/guide/exporting-and-publish.md @@ -206,8 +206,8 @@ One failing format doesn't stop the others. Exports and Publish download their files. Publish sends several files as one ZIP named after the document. Video export isn't available in a browser, because it needs ffmpeg; export a GIF, -animated PNG or WebP, a PNG sequence or an HTML page instead. A PNG sequence downloads each -frame on its own, and your browser may ask once to allow several downloads. +animated PNG or WebP, a PNG sequence or an HTML page instead. A PNG or SVG sequence, like any +export of several files, downloads as one ZIP named after its folder (`frames.zip`). ## From the command line diff --git a/docs/guide/troubleshooting-and-faq.md b/docs/guide/troubleshooting-and-faq.md index b81de620..1f4e18c9 100644 --- a/docs/guide/troubleshooting-and-faq.md +++ b/docs/guide/troubleshooting-and-faq.md @@ -195,8 +195,10 @@ The web version is the same program running in a browser, with some limits: | Large autosaves | The browser keeps only a few MB per site: save often. | | The stage on the graphics card, and parallel rendering | Large scenes and exports are slower. | -Saving and exporting download the file, usually to your Downloads folder. A PNG sequence -downloads frame by frame, and your browser may ask once to allow several downloads. +Saving and exporting download the file, usually to your Downloads folder. A PNG or SVG +sequence downloads as one ZIP. The shortcuts are the desktop ones (F5 inserts a frame; to +reload the page use the browser's button), except Ctrl+N and Ctrl+W, which every browser keeps +for itself: use File › New and File › Close. ## Reporting a bug diff --git a/docs/roadmap.md b/docs/roadmap.md index ce7362da..515b7279 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -49,7 +49,7 @@ the changelog. | P-004 | Memory and frame time stay flat, what is left ([ADR 0132](adr/0132-memory-and-frame-time-stay-flat.md) did the picture cache, zoom gestures, look-ahead order and off-tile edges for [#314](https://github.com/storytold/anicraft/issues/314) and [#477](https://github.com/storytold/anicraft/issues/477), each with a budget test): in the web build a drag still redraws the whole view on every pointer move (key tiles by what they show, so only the tiles the dragged thing touches are drawn again); a tile's preparation still visits every segment of a path it touches (a spatial index); played frames are kept uncompressed, about 12 MB a frame of a 1600 × 940 view, so a short movie fills the 768 MB budget (store flat and repeated tiles once, and decide the budget); deep-zoom timings of the GPU stage on more graphics cards | Workspace | M | | render | | P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), which did not reproduce on Windows 10 (the curved pointer shows outside a corner in the real window; the headless press-and-drag tests pass) and needs the reporter's build number and steps. Done: handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117), tested end to end), and [#193](https://github.com/storytold/anicraft/issues/193) decided by [ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md) with the rule in the guide | Tools | S | the reporter's answer | stage | | P-006 | Animate files open right. Left: confirm the cause of the lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)) with the reporter's file or its import report, and confirm on a Mac that a `.fla` opens ([#347](https://github.com/storytold/anicraft/issues/347): the release it was reported on did not take documents the system hands over, `main` does since [ADR 0062](adr/0062-test-movie-window-and-macos-document-opening.md)); the same recovery in the shared reader (storytold/craft-libs#3282). Done ([ADR 0133](adr/0133-an-animate-shape-is-never-cut-down-quietly.md)): strokes of an unknown kind are drawn solid, an unreadable outline command costs only its own run, and everything left out of a shape is counted in the report; the `unknowns` corpus package. Each fixed file joins the corpus | Import | S | the reporters' files or reports | xfl | -| P-007 | The web build is usable: import, export and save ([#55](https://github.com/storytold/anicraft/issues/55)), preferences kept ([#56](https://github.com/storytold/anicraft/issues/56)), a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210)), a run in a real browser in CI | Preferences, platforms | M | | platform | +| P-007 | The web build is usable, what is left ([ADR 0137](adr/0137-the-web-editor-is-checked-in-a-real-browser.md) ran it in headless Chrome: import, export and save work ([#55](https://github.com/storytold/anicraft/issues/55)) and preferences are kept ([#56](https://github.com/storytold/anicraft/issues/56)), and it fixed same-named files, sequences cut short and the browser taking F5 and other shortcuts): a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210): the app's `packaging/web/package.sh` is ready, the release workflow needs `has-web: true`), `scripts/web-check.sh` run by the Web workflow (one line), Firefox and Safari checked, a recovery copy written when the tab closes | Preferences, platforms | M | | platform | | P-008 | Text reads right: mixed directions (outside PR [#39](https://github.com/storytold/anicraft/issues/39)), then letters from a fallback face (outside PR [#40](https://github.com/storytold/anicraft/issues/40)) | Text | M | [#39](https://github.com/storytold/anicraft/issues/39) before [#40](https://github.com/storytold/anicraft/issues/40) | text | | P-010 | Panel bugs still open: a side dock that grows under the pointer ([#159](https://github.com/storytold/anicraft/issues/159): not reproduced on `main`, which a test now pins at the reported interface scales; needs the reporters to retest a current build) and the flicker in [#255](https://github.com/storytold/anicraft/issues/255) (needs the machine; Preferences › Window graphics is the way round it). Fixed: [#513](https://github.com/storytold/anicraft/issues/513), [#246](https://github.com/storytold/anicraft/issues/246) | Workspace | S each | the reporters | shell | | P-011 | Shape tweens morph a raw shape's outline with its fill (outside PR [#238](https://github.com/storytold/anicraft/issues/238)) | Tweens | S | | doc | @@ -291,7 +291,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | 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. **Documents too large to draw** ([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)): a frame, a bounds query and a Test Movie step each have an allowance of work that no nesting of symbols gets past; a frame cut short says so in the status bar, in the results of the commands that write frames, in `info` and in the MCP picture's caption. Not yet: the same note from the Lottie and HTML exporters and exporter plug-ins, a notice inside the Test Movie window when its picture is cut short, how much was left out. | -| 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 (Follow system, Dark (Graphite), Light or High contrast; ADR 0077), 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 for the next five starts, then 25 and 100 if it dies again (#335, ADR 0105); stage work on the window's device is submitted only inside a frame, which removes the `Surface::configure` "Failed to wait for GPU to come idle" error behind 0.2.1 closing at start-up and on resizing (#264, #309; ADR 0105); 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, restarting by itself when a driver hangs at start-up. | +| 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. **Checked in a real browser** (ADR 0137): `scripts/web-check.sh` builds the bundle and `tests/web_browser.rs` drives headless Chrome, Chromium or Edge over the DevTools protocol by keyboard (start, save, open, import, F5, a sequence, preferences and autosave across a reload; about 20 s; Rust and the standard library only). A picked file always opens, also under an open document's name; several exported files leave as one ZIP (a browser kept 10 to 18 of 48 separate frame downloads); the editor's shortcuts are kept from the browser (F5 reloaded the page), and only those. Not yet: the check in CI, Firefox and Safari, a web asset on releases, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Follow system, Dark (Graphite), Light or High contrast; ADR 0077), 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 for the next five starts, then 25 and 100 if it dies again (#335, ADR 0105); stage work on the window's device is submitted only inside a frame, which removes the `Surface::configure` "Failed to wait for GPU to come idle" error behind 0.2.1 closing at start-up and on resizing (#264, #309; ADR 0105); 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, restarting by itself when a driver hangs at start-up. | | 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. **Portable mode and AppImage desktop integration** (ADR 0094): an `anicraft-portable` marker (shipped in the Windows zip and the Linux tar.gz; also honoured beside `AniCraft.app` and an `.AppImage`) keeps preferences, autosave, logs, plug-ins, templates, recent files, brushes, filter presets and workspaces in `data/` beside the app, through one switch in `platform.rs`, falling back visibly when that folder can't be written; Preferences › About shows the mode and every folder; on first start from an AppImage a non-modal card offers once to add AniCraft to the applications menu (`desktop.integrate/remove/status`: desktop entry with a quoted `Exec`, MIME types and icons under `$XDG_DATA_HOME` only, idempotent, removable from About, following a moved or updated AppImage); a store-readiness job checks the Flatpak manifests, AppStream (`appstreamcli validate`), the desktop entry and any winget/MSIX manifests. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, store submissions and winget/MSIX manifests, self-update inside a portable copy, 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. | diff --git a/docs/web.md b/docs/web.md index 51f7978c..9aeb8a92 100644 --- a/docs/web.md +++ b/docs/web.md @@ -2,8 +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 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 +[ADR 0036](adr/0036-web-build.md), and how it is checked in a real browser in +[ADR 0137](adr/0137-the-web-editor-is-checked-in-a-real-browser.md). Nothing is hosted yet and the +releases don't carry it yet (see [Releases](#releases)); 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 @@ -27,7 +28,7 @@ scripts\build-web.ps1 # Windows PowerShell |---|---| | `index.html` | the page (from `packaging/web/index.html`) | | `anicraft.js` | wasm-bindgen's loader | -| `anicraft_bg.wasm` | the editor, about 9 MB (3.3 MB gzipped) | +| `anicraft_bg.wasm` | the editor, about 21.5 MB (6.8 MB gzipped) | | `anicraft.png` | the page icon | | `guide/` | the user guide as HTML pages (`anicraft-cli guide`), opened by Help › User Guide | @@ -51,7 +52,12 @@ autosave) work. On another host, serve over HTTPS for the same reason. Compressi * **Opening and importing** use the browser's file picker. **Saving and exporting** download the file: Save asks for the file name the first time, then downloads under that name. The - browser picks the folder, usually Downloads. + browser picks the folder, usually Downloads. An export of several files (a PNG or SVG + sequence, a sprite sheet with its frame map, a publish) arrives as one ZIP named after its + folder, `frames.zip`: a browser drops most of a run of separate downloads. +* **A file you open always opens**, in a tab of its own, even when a document of the same name + is open: the browser tells the page a file's name and nothing else, so two different files + can share one. * **Autosave** keeps recovery copies in the browser's storage for the site. If a tab closes or crashes with unsaved work, the next start offers to restore it, as the desktop app does after a crash. Copies of tabs that are still open are never offered. Browsers keep only a few MB per @@ -64,7 +70,12 @@ autosave) work. On another host, serve over HTTPS for the same reason. Compressi screen's pictures. A recent file reopens while the page still holds it; after a reload it shows as missing (the browser never gives its path back): open it again with Open. * **Leaving the page** with unsaved changes asks first. -* **Shortcuts** are the desktop ones; on a Mac they use ⌘. +* **Shortcuts** are the desktop ones; on a Mac they use ⌘. The editor's keys are the editor's: + F5 inserts a frame and Ctrl+R imports, where a page would reload, and Alt+F opens the + editor's File menu. Keys the editor doesn't use stay the browser's (F12, Ctrl+T, Alt+D), and + so do the keys you unbind in Edit › Keyboard Shortcuts. No page can have Ctrl+N, Ctrl+T or + Ctrl+W (⌘ on a Mac): the browser keeps them, so use File › New and File › Close, or the + command palette (Ctrl+K). To reload the page, use the browser's button. * **Sound playback** uses Web Audio (ADR 0095): playback, scrubbing, previews and Test Movie, with the playhead following the sound. The browser opens sound on the first play (a click). Where a browser has no Web Audio, playback is silent with a notice. @@ -78,13 +89,41 @@ autosave) work. On another host, serve over HTTPS for the same reason. Compressi | Installing plug-ins | Plug-ins live in a folder on the computer. Use the desktop app. | | Fonts on your computer | A page can't see them. Text uses the bundled faces. | | XFL folders | A browser can't hand over a folder. Open the `.fla` instead. | -| PNG sequence as one file | Each frame downloads on its own. Your browser may ask once to allow several downloads. | | Large autosaves | Limited by the browser's storage (about 5 MB). | | Parallel rendering | The web has no threads here, so exports render one frame at a time. | +## Releases + +`packaging/web/package.sh` makes `dist/release/anicraft-web-.zip`, the static site to +unzip onto a web server, and the Web CI job runs it on every pull request. Releases will carry +it once `has-web` is switched on in `.github/workflows/release.yml` (the family release workflow +then runs that script and attaches the zip); that is a workflow change of its own +([#316](https://github.com/storytold/anicraft/issues/316)). + ## What was verified, and how -There was no browser on the build machine. These checks ran instead: +**In a real browser** ([ADR 0137](adr/0137-the-web-editor-is-checked-in-a-real-browser.md)): +`scripts/web-check.sh` (`.ps1` on Windows) builds `web/` and runs `tests/web_browser.rs`, which +serves the folder on this computer and drives headless Chrome, Chromium or Edge as an artist +would, by keyboard: the editor starts; Save downloads the document; a file with the open +document's name opens through the browser's picker; Import to Stage (Ctrl+R) brings a picture +in; F5 inserts a frame and the page is not reloaded; a PNG sequence from the command palette +arrives as one ZIP; after a reload (which asks first, with unsaved work) the preferences are +read back and one edit leaves a recovery copy in the site's storage; and the page reported no +error. It takes about 20 s after the build. + +```sh +scripts/web-check.sh # build, then check +ANICRAFT_WEB_DIR=unzipped-release scripts/web-check.sh # check a bundle you already have +ANICRAFT_BROWSER=/usr/bin/chromium scripts/web-check.sh +``` + +Not checked by it: Firefox and Safari, sound, drag and drop from the desktop, and how the +canvas looks. To check those by hand: build, serve, then in the page open a `.anicraft` file, +draw, save (a download arrives), close the tab with unsaved work, reopen it (Restore is +offered), and export a GIF. + +**Without a browser**, as before: * every crate builds for wasm32, and clippy is clean for it; * `crates/engine/tests/wasm.rs` runs inside WebAssembly in Node: a frame renders with no @@ -95,11 +134,6 @@ There was no browser on the build machine. These checks ran instead: * natively, `crates/engine/src/web_tests.rs` runs every file command against the in-memory store the browser uses. -Only a browser can confirm the canvas, the picker, downloads, storage, Web Locks and the -leave-page prompt. To check them by hand: build, serve, then in the page open a `.anicraft` file, -draw, save (a download arrives), close the tab with unsaved work, reopen it (Restore is -offered), and export a GIF. - Run the WebAssembly tests yourself (Node and the wasm-bindgen CLI installed): ```sh diff --git a/scripts/web-check.ps1 b/scripts/web-check.ps1 new file mode 100644 index 00000000..bbc0e521 --- /dev/null +++ b/scripts/web-check.ps1 @@ -0,0 +1,14 @@ +# Runs the web editor in a real browser (ADR 0137, docs/web.md): builds web/ and drives it in +# headless Chrome or Edge through tests/web_browser.rs. The PowerShell twin of web-check.sh. +# +# scripts\web-check.ps1 # build web\, then check it +# $env:ANICRAFT_WEB_DIR = 'unzipped'; scripts\web-check.ps1 # check a bundle already built +# $env:ANICRAFT_BROWSER = 'C:\path\to\chrome.exe' # choose the browser +$ErrorActionPreference = 'Stop' +Set-Location -LiteralPath (Split-Path -Parent $PSScriptRoot) +if (-not $env:ANICRAFT_WEB_DIR) { + & (Join-Path $PSScriptRoot 'build-web.ps1') + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +} +cargo test -p anicraft --test web_browser -- --ignored --nocapture +exit $LASTEXITCODE diff --git a/scripts/web-check.sh b/scripts/web-check.sh new file mode 100755 index 00000000..a1e5334d --- /dev/null +++ b/scripts/web-check.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Runs the web editor in a real browser (ADR 0137, docs/web.md): builds web/ and drives it in +# headless Chrome, Chromium or Edge through tests/web_browser.rs (start, save, open, import, +# export a sequence, the editor's shortcuts, preferences and autosave across a reload). +# +# scripts/web-check.sh # build web/, then check it +# ANICRAFT_WEB_DIR=unzipped scripts/web-check.sh # check a bundle already built (a release zip, unzipped) +# ANICRAFT_BROWSER=/path/to/chrome scripts/web-check.sh # choose the browser +# ANICRAFT_BROWSER_ARGS=--no-sandbox scripts/web-check.sh # in a container +# +# Nothing keeps running afterwards: the test serves the folder on 127.0.0.1 and closes the +# browser itself. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +[[ $# -eq 0 ]] || { echo "usage: scripts/web-check.sh" >&2; exit 2; } +if [[ -z "${ANICRAFT_WEB_DIR:-}" ]]; then + scripts/build-web.sh +fi +cargo test -p anicraft --test web_browser -- --ignored --nocapture diff --git a/tests/web_browser.rs b/tests/web_browser.rs index 0688153e..8bf60fd5 100644 --- a/tests/web_browser.rs +++ b/tests/web_browser.rs @@ -431,7 +431,7 @@ fn an_artist_can_work_in_a_real_browser() { let second = downloaded(&got, &mut t); assert_eq!(second.len(), 1, "saving the opened document downloads it: {:?}", names(&second)); let reopened: Value = serde_json::from_slice(&second[0].1).expect("a document"); - assert_ne!(reopened, sample, "the picked file opened, though a document with its name was open"); + assert!(reopened != sample, "the picked file opened, though a document with its name was open (the first document was saved again instead)"); // Import to Stage (Ctrl+R, which a browser would reload the page on): the picture is in // the document that is saved next. From 2cf3a36de380604d852685d3544fa9c3c0a2dfc7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 28 Nov 2026 00:24:15 -0700 Subject: [PATCH 4/6] fix(web): Alt alone reaches the menu bar, and the status names what was downloaded (M8) Review: a standalone Alt was read as its physical key and left to the browser; a one-frame sequence was announced as a ZIP; an archive that could not be made was announced as a success. --- ...web-editor-is-checked-in-a-real-browser.md | 2 +- docs/guide/exporting-and-publish.md | 3 ++- docs/guide/troubleshooting-and-faq.md | 2 +- docs/roadmap.md | 2 +- docs/web.md | 5 +++-- src/app.rs | 22 ++++++++++++++----- src/web.rs | 6 +++-- 7 files changed, 29 insertions(+), 13 deletions(-) diff --git a/docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md b/docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md index 72caf19f..3c41d365 100644 --- a/docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md +++ b/docs/adr/0137-the-web-editor-is-checked-in-a-real-browser.md @@ -104,7 +104,7 @@ things did not, and none of them could have been seen without a browser: * The check takes 21 s once the bundle is built (five runs in a row here, all green). Against the bundle built from the code before this change it fails at the second step, with the first document saved again in place of the picked one. -* A sequence in the browser is now always an archive, even a short one. One more step to +* A sequence of two or more frames in the browser is now an archive. One more step to unpack it, and no frame is lost. * An artist who pressed F5 to reload the page uses the browser's button; the editor says nothing about it because nothing happens that needs saying: a frame is inserted, as on the diff --git a/docs/guide/exporting-and-publish.md b/docs/guide/exporting-and-publish.md index 66435653..9a13917c 100644 --- a/docs/guide/exporting-and-publish.md +++ b/docs/guide/exporting-and-publish.md @@ -207,7 +207,8 @@ One failing format doesn't stop the others. Exports and Publish download their files. Publish sends several files as one ZIP named after the document. Video export isn't available in a browser, because it needs ffmpeg; export a GIF, animated PNG or WebP, a PNG sequence or an HTML page instead. A PNG or SVG sequence, like any -export of several files, downloads as one ZIP named after its folder (`frames.zip`). +export of several files, downloads as one ZIP named after its folder (`frames.zip`); a single +frame downloads as the picture itself. ## From the command line diff --git a/docs/guide/troubleshooting-and-faq.md b/docs/guide/troubleshooting-and-faq.md index 1f4e18c9..dc3404d0 100644 --- a/docs/guide/troubleshooting-and-faq.md +++ b/docs/guide/troubleshooting-and-faq.md @@ -196,7 +196,7 @@ The web version is the same program running in a browser, with some limits: | The stage on the graphics card, and parallel rendering | Large scenes and exports are slower. | Saving and exporting download the file, usually to your Downloads folder. A PNG or SVG -sequence downloads as one ZIP. The shortcuts are the desktop ones (F5 inserts a frame; to +sequence of several frames downloads as one ZIP. The shortcuts are the desktop ones (F5 inserts a frame; to reload the page use the browser's button), except Ctrl+N and Ctrl+W, which every browser keeps for itself: use File › New and File › Close. diff --git a/docs/roadmap.md b/docs/roadmap.md index 515b7279..81d233cc 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -291,7 +291,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | 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. **Documents too large to draw** ([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)): a frame, a bounds query and a Test Movie step each have an allowance of work that no nesting of symbols gets past; a frame cut short says so in the status bar, in the results of the commands that write frames, in `info` and in the MCP picture's caption. Not yet: the same note from the Lottie and HTML exporters and exporter plug-ins, a notice inside the Test Movie window when its picture is cut short, how much was left out. | -| 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. **Checked in a real browser** (ADR 0137): `scripts/web-check.sh` builds the bundle and `tests/web_browser.rs` drives headless Chrome, Chromium or Edge over the DevTools protocol by keyboard (start, save, open, import, F5, a sequence, preferences and autosave across a reload; about 20 s; Rust and the standard library only). A picked file always opens, also under an open document's name; several exported files leave as one ZIP (a browser kept 10 to 18 of 48 separate frame downloads); the editor's shortcuts are kept from the browser (F5 reloaded the page), and only those. Not yet: the check in CI, Firefox and Safari, a web asset on releases, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Follow system, Dark (Graphite), Light or High contrast; ADR 0077), 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 for the next five starts, then 25 and 100 if it dies again (#335, ADR 0105); stage work on the window's device is submitted only inside a frame, which removes the `Surface::configure` "Failed to wait for GPU to come idle" error behind 0.2.1 closing at start-up and on resizing (#264, #309; ADR 0105); 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, restarting by itself when a driver hangs at start-up. | +| 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/` (21,496 KB, 6,781 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. **Checked in a real browser** (ADR 0137): `scripts/web-check.sh` builds the bundle and `tests/web_browser.rs` drives headless Chrome, Chromium or Edge over the DevTools protocol by keyboard (start, save, open, import, F5, a sequence, preferences and autosave across a reload; about 20 s; Rust and the standard library only). A picked file always opens, also under an open document's name; several exported files leave as one ZIP (a browser kept 10 to 18 of 48 separate frame downloads); the editor's shortcuts are kept from the browser (F5 reloaded the page), and only those. Not yet: the check in CI, Firefox and Safari, a web asset on releases, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Follow system, Dark (Graphite), Light or High contrast; ADR 0077), 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 for the next five starts, then 25 and 100 if it dies again (#335, ADR 0105); stage work on the window's device is submitted only inside a frame, which removes the `Surface::configure` "Failed to wait for GPU to come idle" error behind 0.2.1 closing at start-up and on resizing (#264, #309; ADR 0105); 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, restarting by itself when a driver hangs at start-up. | | 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. **Portable mode and AppImage desktop integration** (ADR 0094): an `anicraft-portable` marker (shipped in the Windows zip and the Linux tar.gz; also honoured beside `AniCraft.app` and an `.AppImage`) keeps preferences, autosave, logs, plug-ins, templates, recent files, brushes, filter presets and workspaces in `data/` beside the app, through one switch in `platform.rs`, falling back visibly when that folder can't be written; Preferences › About shows the mode and every folder; on first start from an AppImage a non-modal card offers once to add AniCraft to the applications menu (`desktop.integrate/remove/status`: desktop entry with a quoted `Exec`, MIME types and icons under `$XDG_DATA_HOME` only, idempotent, removable from About, following a moved or updated AppImage); a store-readiness job checks the Flatpak manifests, AppStream (`appstreamcli validate`), the desktop entry and any winget/MSIX manifests. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, store submissions and winget/MSIX manifests, self-update inside a portable copy, 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. | diff --git a/docs/web.md b/docs/web.md index 9aeb8a92..77e4de37 100644 --- a/docs/web.md +++ b/docs/web.md @@ -120,8 +120,9 @@ ANICRAFT_BROWSER=/usr/bin/chromium scripts/web-check.sh Not checked by it: Firefox and Safari, sound, drag and drop from the desktop, and how the canvas looks. To check those by hand: build, serve, then in the page open a `.anicraft` file, -draw, save (a download arrives), close the tab with unsaved work, reopen it (Restore is -offered), and export a GIF. +draw, drop a picture and a sound from the desktop onto the stage, play (the sound is heard), +save (a download arrives), close the tab with unsaved work, reopen it (Restore is offered), and +export a GIF. **Without a browser**, as before: diff --git a/src/app.rs b/src/app.rs index 36041329..43b75899 100644 --- a/src/app.rs +++ b/src/app.rs @@ -653,6 +653,10 @@ pub struct App { /// A copy or cut ran: the system clipboard gets a note at the end of the frame, so the next /// Ctrl/⌘+V reaches the app (egui-winit sends a paste only when the clipboard holds text). copied: bool, + /// In a browser: the archive the last command's several files left in (ADR 0137), and why + /// one could not be made (the files then went one by one). + web_archive: Option, + web_archive_failed: Option, /// Paste looks at the system clipboard for a picture from another app (#263). Off in /// screenshot runs and tests, which must not depend on what this computer last copied. system_clipboard: bool, @@ -973,6 +977,8 @@ impl App { fonts_rx: None, glyph_check: true, copied: false, + web_archive: None, + web_archive_failed: None, system_clipboard: !shot_mode && !platform::WEB, swallowed_paste: platform::SwallowedPaste::default(), last_revision: 0, @@ -1097,11 +1103,13 @@ impl App { // browser as downloads (ADR 0036). // Several files (a sequence) leave as one ZIP: a browser drops most of a run of // downloads. - let (files, failed) = platform::as_one_download(anicraft_engine::vfs::take_written(), None); + let written = anicraft_engine::vfs::take_written(); + let several = written.len() > 1; + let (files, failed) = platform::as_one_download(written, None); + // For the status line, which is written after this (`perform_here`). + self.web_archive = files.first().filter(|_| several && failed.is_none()).map(|(p, _)| p.display().to_string()); + self.web_archive_failed = failed; platform::deliver(files); - if let Some(e) = failed { - self.status_err(tr!("Could not make the archive: {e}", e = e)); - } } match result { Ok(v) => { @@ -3606,6 +3614,10 @@ impl App { return Some(v); } self.announce(id, &v, selected); + // In a browser: the files went one by one after all, and the status line says why. + if let Some(e) = self.web_archive_failed.take() { + self.status_err(tr!("Could not make the archive: {e}", e = e)); + } Some(v) } @@ -3778,7 +3790,7 @@ impl App { self.status_ok(format!("{done}{report}")); } // In a browser a sequence's frames arrive as one archive named after the folder. - "file.export_png_sequence" | "file.export_svg_sequence" if platform::WEB => self.status_ok(tr!("Exported {path}.zip to your downloads", path = v.get("dir").and_then(Value::as_str).unwrap_or(""))), + "file.export_png_sequence" | "file.export_svg_sequence" if self.web_archive.is_some() => self.status_ok(tr!("Exported {path} to your downloads", path = self.web_archive.as_deref().unwrap_or(""))), "file.export_png" | "file.export_png_sequence" | "file.export_svg_sequence" | "file.export_gif" | "file.export_svg" | "file.export_video" => self.status_ok(tr!("Exported {path}", path = v.get("written").or_else(|| v.get("dir")).and_then(Value::as_str).unwrap_or(""))), // Undo labels are the engine's English, translated when a catalog has them. "edit.undo" => self.status_ok(tr!("Undid {action}", action = crate::i18n::t_dyn(v["undone"].as_str().unwrap_or("")))), diff --git a/src/web.rs b/src/web.rs index cd525ae1..dba6f5e9 100644 --- a/src/web.rs +++ b/src/web.rs @@ -322,9 +322,11 @@ fn guard_keys() { // (Alt's own release no longer counts it as held.) let pressed = egui::Modifiers { alt: e.alt_key() || e.key() == "Alt", ctrl: e.ctrl_key(), shift: e.shift_key(), mac_cmd: e.meta_key(), command: e.ctrl_key() || e.meta_key() }; let name = e.key(); - let key = egui::Key::from_name(&name).or_else(|| egui::Key::from_name(&e.code())); + // Alt itself is no key of a chord here (to egui its physical name, AltLeft, is one). + let alt = name == "Alt"; // i18n-exempt: a DOM key name + let key = if alt { None } else { egui::Key::from_name(&name).or_else(|| egui::Key::from_name(&e.code())) }; // AltGr types a character (€, @ on many layouts): never a shortcut to take. - if (key.is_none() && name != "Alt") || e.get_modifier_state("AltGraph") { // i18n-exempt: DOM key names + if (key.is_none() && !alt) || e.get_modifier_state("AltGraph") { // i18n-exempt: a DOM key name return; } if KEYS.with(|k| { From 20da0d126835e52f054a4246310aa95f44706710 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 28 Nov 2026 00:55:42 -0700 Subject: [PATCH 5/6] test(web): the keys kept from the browser follow the shortcut table (M8) --- src/app.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/app.rs b/src/app.rs index 43b75899..bb92cc88 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5220,6 +5220,23 @@ mod clipboard_key_tests { RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1600.0, 940.0))), events, ..Default::default() } } + /// In a browser the editor keeps from the browser the keys of its shortcut table as the user + /// set it (ADR 0137): a key bound in Edit › Keyboard Shortcuts is taken from then on, and + /// the browser's own keys stay the browser's. + #[test] + fn the_keys_kept_from_the_browser_follow_the_shortcut_table() { + use egui::Key; + let (_ctx, mut app) = app(); + let takes = |app: &App, m: Modifiers, k: Key| crate::platform::claims_key(&app.browser_keys(), crate::platform::menu_bar_keys(), m, Some(k)); + assert!(takes(&app, Modifiers::NONE, Key::F5), "F5 is Insert Frame, not the browser's reload"); + assert_eq!(takes(&app, Modifiers::ALT, Key::F), crate::platform::menu_bar_keys(), "Alt+F is the File menu where Alt reaches the menu bar"); + assert!(!takes(&app, Modifiers::NONE, Key::F12), "a key the editor doesn't use"); + let id = app.shortcuts.iter().find(|(_, k, _)| *k == Key::F5).map(|(_, _, id)| *id).expect("F5 is bound"); + app.prefs.shortcuts = crate::keymap::assign(&app.prefs.shortcuts, id, None, "F12", false).expect("F12 is free"); + app.refresh_keymap(); + assert!(takes(&app, Modifiers::NONE, Key::F12), "bound by the user: the editor's from now on"); + } + /// One frame; what it asked the system clipboard to hold. fn frame(ctx: &egui::Context, app: &mut App, input: RawInput) -> Vec { let mut out = ctx.run_ui(input, |ui| app.frame(ui)); From 8f36bcbf141eff02c32c67f9aba158a96099faf2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 28 Nov 2026 01:17:26 -0700 Subject: [PATCH 6/6] fix(web): Alt with a plain tool letter stays the browser's (M8) On a Mac Option+letter types a character; the macOS gate's new test caught the editor taking it. --- src/platform.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/platform.rs b/src/platform.rs index b3cfc496..1419b665 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -235,8 +235,9 @@ pub fn claims_key(bound: &[(egui::Modifiers, egui::Key)], alt_menus: bool, press if !chorded && !function { return false; } - // As egui matches a shortcut: extra Shift or Alt held still presses it. - bound.iter().any(|(m, k)| *k == key && pressed.matches_logically(*m)) + // As egui matches a shortcut: extra Shift or Alt held still presses it. But a plain letter's + // binding (a tool key) is not a chord to take with Alt held: on a Mac that types a character. + bound.iter().any(|(m, k)| *k == key && (function || m.ctrl || m.command || m.alt) && pressed.matches_logically(*m)) } pub fn set_mac_glyphs(available: bool) { @@ -1480,6 +1481,7 @@ mod tests { assert!(claims(Modifiers::SHIFT, Key::F5), "as egui matches it: Shift held still presses F5"); assert!(!claims(Modifiers::NONE, Key::F12) && !claims(ctrl, Key::T) && !claims(Modifiers::ALT, Key::D), "unused keys are the browser's"); assert!(!claims(Modifiers::NONE, Key::V), "a tool letter is typing in a text field"); + assert!(!claims(Modifiers::ALT, Key::V), "and with Alt it types a character on a Mac"); assert!(!claims(ctrl, Key::V) && !claims(ctrl | Modifiers::SHIFT, Key::V), "paste arrives as the browser's event"); assert!(claims_key(&bound, true, Modifiers::ALT, None), "Alt alone is the editor's menu bar"); assert!(!claims_key(&bound, false, Modifiers::ALT, None), "but not on a Mac, where Alt opens no menu");