feat(shell): web build of the editor: browser entry, file picker and downloads, autosave to browser storage (M8)

src/web.rs starts the editor on a page canvas with eframe's WebRunner (WebGL2 via glow) and
provides the browser's services; platform.rs decides when: picked files go to the engine's
in-memory store and the command runs, saves and exports leave as downloads, preferences and
recovery copies live in localStorage, Web Locks tell open tabs from crashed ones, and leaving
with unsaved work asks first. The GPU stage and sound output become build cfgs that are off
on wasm. Video export and plug-in installs are dimmed in the browser with the reason.

scripts/build-web.sh and .ps1 build web/ with the wasm-bindgen CLI pinned to Cargo.lock's
version, from packaging/web/index.html. The web profile (opt-level s, stripped, renderer and
geometry at opt-level 3) gives an 8973 KB module, 3278 KB gzipped, in 41 s.
crates/engine/tests/wasm.rs runs the engine inside WebAssembly in Node (3 tests, 0.6 s).
This commit is contained in:
Tanish Manku committed 2026-11-09 22:36:09 -07:00
1 parent 06c004b294
commit 7dcd01041e
23 files changed
+1166 -94

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
/target/
# release packages (packaging/*/package.*)
/dist/
# the web editor built by scripts/build-web.sh (ADR 0036)
/web/
# sample plug-ins built by examples/plugins/build.sh (sources are committed, binaries never)
/examples/plugins/dist/
/examples/plugins/target/
Generated
+76
View File
@@ -219,9 +219,14 @@ dependencies = [
"eframe",
"egui",
"fontdb",
"js-sys",
"rfd",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"web-time",
"winresource",
]
@@ -282,6 +287,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"wasm-bindgen-test",
"wat",
"web-time",
]
@@ -886,6 +892,12 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
version = "1.10.0"
@@ -2304,6 +2316,16 @@ dependencies = [
"autocfg",
]
[[package]]
name = "minicov"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
dependencies = [
"cc",
"walkdir",
]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -2423,6 +2445,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
@@ -2879,6 +2910,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -4194,6 +4231,45 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-bindgen-test"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
dependencies = [
"async-trait",
"cast",
"js-sys",
"libm",
"minicov",
"nu-ansi-term",
"num-traits",
"oorandom",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test-macro",
"wasm-bindgen-test-shared",
]
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "wasm-bindgen-test-shared"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
[[package]]
name = "wasm-encoder"
version = "0.263.0"
+32 -3
View File
@@ -92,15 +92,29 @@ anicraft-doc.workspace = true
anicraft-render.workspace = true
anicraft-engine.workspace = true
anicraft-gpu = { workspace = true, optional = true }
eframe.workspace = true
egui.workspace = true
rfd.workspace = true
serde.workspace = true
fontdb.workspace = true
anicraft-audio.workspace = true
serde_json.workspace = true
web-time.workspace = true
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
eframe.workspace = true
rfd.workspace = true
# Sound output (Apache-2.0): WASAPI on Windows, CoreAudio on macOS, ALSA on Linux and the BSDs.
cpal = { version = "0.18", optional = true }
serde_json.workspace = true
# The web build (ADR 0036, docs/web.md). The window draws with WebGL2 (glow): every current
# browser has it, the stage is drawn on the CPU there, and leaving wgpu out keeps the download
# smaller. The browser glue is wasm-bindgen's (MIT OR Apache-2.0), already under eframe's web
# backend.
[target.'cfg(target_arch = "wasm32")'.dependencies]
eframe = { version = "0.36", default-features = false, features = ["accesskit", "default_fonts", "glow"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] }
[build-dependencies]
# Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets.
@@ -133,3 +147,18 @@ debug = false
lto = "thin"
codegen-units = 1
strip = "debuginfo"
[profile.web]
# The web editor (scripts/build-web.sh, ADR 0036): the release build optimized for size, since
# the browser downloads and compiles the whole module before anything shows (9.1 MB, 3.3 MB
# gzipped, against 11.3 / 4.0 MB at opt-level 3), and without the symbol names.
inherits = "release"
opt-level = "s"
strip = true
# ...except the CPU renderer and the geometry under it, which draw the stage there on one thread.
[profile.web.package.anicraft-render]
opt-level = 3
[profile.web.package.anicraft-geom]
opt-level = 3
+14
View File
@@ -81,7 +81,21 @@ fn windows_icon() {
}
}
/// The desktop-only features (ADR 0036) as cfgs: `gpu_stage` and `sound_output` are on when
/// their feature is and the target isn't the web, so `cargo build --target wasm32-unknown-unknown`
/// works with the default features and the web build draws on the CPU, silently.
fn native_features() {
println!("cargo::rustc-check-cfg=cfg(gpu_stage, sound_output)");
let web = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
for (feature, cfg) in [("CARGO_FEATURE_GPU_STAGE", "gpu_stage"), ("CARGO_FEATURE_SOUND_OUTPUT", "sound_output")] {
if std::env::var_os(feature).is_some() && !web {
println!("cargo::rustc-cfg={cfg}");
}
}
}
fn main() {
native_features();
windows_icon();
println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR");
println!("cargo:rerun-if-changed=build.rs");
+4
View File
@@ -28,5 +28,9 @@ png.workspace = true
# Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception).
wat = "1.228"
# Runs tests/wasm.rs inside WebAssembly, in Node (ADR 0036; MIT OR Apache-2.0).
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = "0.3"
[lints]
workspace = true
+3 -4
View File
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec { id: "file.new", label: "New", menu: "File", shortcut: Some("Ctrl+N"), params: "{width?, height?, fps?}", mutates: false, run: new_doc },
CommandSpec { id: "file.new_sample", label: "New from Sample", menu: "File", shortcut: None, params: "{which?: demo (default) | interactive (a menu with a Play button, for Test Movie)}", mutates: false, run: new_sample },
CommandSpec { id: "file.open", label: "Open…", menu: "File", shortcut: Some("Ctrl+O"), params: "{path, unsaved? (opens it as unsaved work with no file name: a restored copy)}", mutates: false, run: open },
CommandSpec { id: "file.open", label: "Open…", menu: "File", shortcut: Some("Ctrl+O"), params: "{path, unsaved? (opens it as unsaved work: a restored copy), untitled? (with no file name, so Save asks for one)}", mutates: false, run: open },
CommandSpec { id: "file.save", label: "Save", menu: "File", shortcut: Some("Ctrl+S"), params: "{path?, confirm?}", mutates: false, run: save },
CommandSpec {
id: "file.save_as",
@@ -152,6 +152,7 @@ pub fn is_animate(path: &std::path::Path) -> bool {
fn open(s: &mut Session, p: &Value) -> Result<Value> {
let path = PathBuf::from(str_req(p, "path")?);
let unsaved = opt_bool(p, "unsaved")?.unwrap_or(false);
let untitled = opt_bool(p, "untitled")?.unwrap_or(false);
if is_animate(&path) {
// Imported, not adopted: the document is untitled, so Save asks for a new .anicraft
// name and never writes over the Animate file.
@@ -177,11 +178,9 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(info);
}
let doc = format::load(&path)?;
s.replace_document(doc, (!untitled).then_some(path));
if unsaved {
s.replace_document(doc, None);
s.mark_unsaved();
} else {
s.replace_document(doc, Some(path));
}
Ok(s.info())
}
+6 -3
View File
@@ -38,9 +38,12 @@ fn save_downloads_and_a_picked_file_opens() {
assert_eq!((t.frame_count(), t.path.as_deref(), t.is_dirty()), (frames, Some(Path::new("walk.anicraft")), false));
assert!(vfs::take_written().is_empty(), "opening writes nothing, and the picked file is let go");
// A restored autosave copy opens as unsaved work with no file name.
vfs::put(Path::new("recovered/walk.anicraft"), bytes).unwrap();
t.execute("file.open", &json!({"path": "recovered/walk.anicraft", "unsaved": true})).unwrap();
// A restored autosave copy opens as unsaved work, with its name or without one.
vfs::put(Path::new("recovered/s1/walk.anicraft"), bytes.clone()).unwrap();
t.execute("file.open", &json!({"path": "recovered/s1/walk.anicraft", "unsaved": true, "confirm": true})).unwrap();
assert_eq!((t.path.as_deref(), t.is_dirty()), (Some(Path::new("recovered/s1/walk.anicraft")), true));
vfs::put(Path::new("recovered/s2/Untitled"), bytes).unwrap();
t.execute("file.open", &json!({"path": "recovered/s2/Untitled", "unsaved": true, "untitled": true, "confirm": true})).unwrap();
assert_eq!((t.path.as_deref(), t.is_dirty()), (None, true));
assert!(t.execute("file.open", &json!({"path": "gone.anicraft"})).is_err(), "a missing file is an error, not a crash");
});
+80
View File
@@ -0,0 +1,80 @@
//! The engine inside WebAssembly (ADR 0036), as the web editor runs it: one thread, no file
//! system, no `std::time` clock. Run in Node by wasm-bindgen's test runner (docs/web.md):
//!
//! ```sh
//! CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER=wasm-bindgen-test-runner \
//! cargo test -p anicraft-engine --target wasm32-unknown-unknown --test wasm
//! ```
//!
//! A build can't catch what traps at run time (a clock or thread call that compiles but isn't
//! there); these do. Natively this file is empty.
#![cfg(target_arch = "wasm32")]
use anicraft_engine::plugins::{Host, Limits, Plugin};
use anicraft_engine::render_service::RenderService;
use anicraft_engine::{Session, vfs};
use serde_json::{Map, Value, json};
use std::path::Path;
use wasm_bindgen_test::wasm_bindgen_test;
fn names() -> Vec<String> {
vfs::take_written().into_iter().map(|(p, _)| p.display().to_string()).collect()
}
#[wasm_bindgen_test]
fn saves_opens_and_exports_through_memory() {
assert!(vfs::in_memory(), "the browser has no disk: files live in memory");
let mut s = Session::new(anicraft_engine::doc::sample::demo());
s.execute("file.save", &json!({"path": "walk.anicraft"})).unwrap();
let saved = vfs::take_written();
assert_eq!(saved.len(), 1);
vfs::put(Path::new("walk.anicraft"), saved[0].1.clone()).unwrap();
let mut t = Session::default();
t.execute("file.open", &json!({"path": "walk.anicraft"})).unwrap();
assert_eq!(t.frame_count(), s.frame_count());
// Parallel renders (rayon on the one thread), timing (web clock), encoders.
s.execute("file.export_png", &json!({"path": "f.png"})).unwrap();
s.execute("file.export_gif", &json!({"path": "m.gif", "to": 4})).unwrap();
s.execute("file.export_html", &json!({"path": "m.html"})).unwrap();
s.execute("file.export_png_sequence", &json!({"dir": "seq", "to": 2})).unwrap();
assert_eq!(names().len(), 6);
assert!(s.execute("file.export_video", &json!({"path": "m.webm"})).is_err());
}
#[wasm_bindgen_test]
fn the_stage_renders_without_a_thread() {
let s = Session::new(anicraft_engine::doc::sample::demo());
let svc = RenderService::new(64 << 20, None);
let view = anicraft_engine::render::View::stage(&s.doc, 0.5);
// No worker thread can start, so a request renders right away.
let img = svc.request(svc.job(s.state, &s.doc, 3, view, false)).expect("rendered on this thread");
assert!(img.error.is_none() && img.width > 0 && img.rgba_premul.iter().any(|&b| b != 0));
}
struct Quiet;
impl Host for Quiet {
fn request(&mut self, _: &str, _: &Value) -> Result<Value, String> {
Ok(Value::Null)
}
}
#[wasm_bindgen_test]
fn plugins_run_in_the_browser_too() {
let manifest = r#"{"id":"org.test.web","name":"Web","version":"1.0.0","kind":"command","author":"Tests"}"#;
let text = format!(
r#"(module
(import "anicraft" "call" (func (param i32 i32) (result i32)))
(import "anicraft" "response" (func (param i32 i32) (result i32)))
(memory (export "memory") 1)
(data (i32.const 1024) "{manifest}")
(func (export "ac_abi_version") (result i32) i32.const 1)
(func (export "ac_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 1024)))
(func (export "ac_alloc") (param i32) (result i32) i32.const 4096)
(func (export "ac_run") (param i32 i32) (result i32) i32.const 0))"#,
manifest = manifest.replace('"', "\\22"),
len = manifest.len()
);
let plugin = Plugin::load(&wat::parse_str(&text).unwrap(), Limits::default()).unwrap();
assert_eq!(plugin.id(), "org.test.web");
plugin.run(&mut Quiet, &Map::new()).unwrap();
}
+34
View File
@@ -0,0 +1,34 @@
<!doctype html>
<!-- The page the web editor runs in (ADR 0036, docs/web.md). scripts/build-web.sh copies it into
web/ beside the generated anicraft.js and anicraft_bg.wasm; src/web.rs looks for the two ids
below. Colours are the Graphite theme's chrome and dim text (src/theme.rs). -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>AniCraft</title>
<link rel="icon" href="anicraft.png">
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #131316; }
canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
#anicraft_loading {
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
padding: 2em; text-align: center; color: #b0b0b8; font: 15px/1.5 system-ui, sans-serif;
}
</style>
</head>
<body>
<canvas id="anicraft_canvas"></canvas>
<div id="anicraft_loading">Loading AniCraft…</div>
<noscript>AniCraft needs JavaScript and WebAssembly.</noscript>
<script type="module">
import init from "./anicraft.js";
// init() loads anicraft_bg.wasm and runs the program's main, which starts the editor.
init().catch((e) => {
console.error(e);
document.getElementById("anicraft_loading").textContent = "AniCraft could not start in this browser: " + e;
});
</script>
</body>
</html>
+55
View File
@@ -0,0 +1,55 @@
# Builds the web editor into web\ (ADR 0036, docs\web.md): index.html, anicraft.js,
# anicraft_bg.wasm and the page icon. Everything in web\ is generated (git-ignored); serve the
# folder with any static web server. The Windows twin of scripts/build-web.sh.
#
# Needs the wasm32-unknown-unknown target and the wasm-bindgen CLI at the version Cargo.lock
# pins for the wasm-bindgen crate (both MIT OR Apache-2.0):
#
# rustup target add wasm32-unknown-unknown
# cargo install wasm-bindgen-cli --version <the version this script asks for> --locked
#
# scripts\build-web.ps1 # optimized (the `web` profile)
# scripts\build-web.ps1 -Dev # quicker to build, larger and slower
[CmdletBinding()]
param([switch]$Dev)
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $PSScriptRoot
Set-Location $Root
$CargoProfile = if ($Dev) { 'dev' } else { 'web' }
# The CLI and the crate must be the same version, or the generated glue doesn't match.
$lock = Get-Content -Raw (Join-Path $Root 'Cargo.lock')
$m = [regex]::Match($lock, '(?m)^name = "wasm-bindgen"\r?\nversion = "([^"]+)"')
if (-not $m.Success) { throw 'Cargo.lock names no wasm-bindgen version' }
$Want = $m.Groups[1].Value
if (-not (Get-Command wasm-bindgen -ErrorAction SilentlyContinue)) {
throw "wasm-bindgen not found: cargo install wasm-bindgen-cli --version $Want --locked"
}
$Have = ((& wasm-bindgen --version) -split ' ')[1]
if ($Have -ne $Want) {
throw "wasm-bindgen $Have found, Cargo.lock needs ${Want}: cargo install wasm-bindgen-cli --version $Want --locked"
}
if (Get-Command rustup -ErrorAction SilentlyContinue) {
if (-not ((& rustup target list --installed) -contains 'wasm32-unknown-unknown')) {
throw 'the wasm32-unknown-unknown target is missing: rustup target add wasm32-unknown-unknown'
}
}
& cargo build -p anicraft --bin anicraft --target wasm32-unknown-unknown --profile $CargoProfile
if ($LASTEXITCODE -ne 0) { throw 'cargo build failed' }
$TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' }
$Dir = if ($Dev) { 'debug' } else { $CargoProfile }
$Wasm = Join-Path $TargetDir "wasm32-unknown-unknown\$Dir\anicraft.wasm"
$Out = Join-Path $Root 'web'
if (Test-Path $Out) { Remove-Item -Recurse -Force $Out }
New-Item -ItemType Directory -Force $Out | Out-Null
& wasm-bindgen --target web --no-typescript --out-dir $Out --out-name anicraft $Wasm
if ($LASTEXITCODE -ne 0) { throw 'wasm-bindgen failed' }
Copy-Item (Join-Path $Root 'packaging\web\index.html') (Join-Path $Out 'index.html')
Copy-Item (Join-Path $Root 'assets\app-icon\hicolor\128x128\apps\ai.storyteller.anicraft.png') (Join-Path $Out 'anicraft.png')
$Bytes = (Get-Item (Join-Path $Out 'anicraft_bg.wasm')).Length
Write-Host ("web\ is ready: anicraft_bg.wasm is {0} KB." -f [math]::Floor($Bytes / 1024))
Write-Host 'Serve it locally, for example: python -m http.server --directory web 8080 (then open http://localhost:8080)'
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Builds the web editor into web/ (ADR 0036, docs/web.md): index.html, anicraft.js,
# anicraft_bg.wasm and the page icon. Everything in web/ is generated (git-ignored); serve the
# folder with any static web server.
#
# Needs the wasm32-unknown-unknown target and the wasm-bindgen CLI at the version Cargo.lock
# pins for the wasm-bindgen crate (both MIT OR Apache-2.0):
#
# rustup target add wasm32-unknown-unknown
# cargo install wasm-bindgen-cli --version <the version this script asks for> --locked
#
# scripts/build-web.sh # optimized (the `web` profile)
# scripts/build-web.sh --dev # quicker to build, larger and slower
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
PROFILE=web
case "${1:-}" in
"") ;;
--dev) PROFILE=dev ;;
*) echo "usage: scripts/build-web.sh [--dev]" >&2; exit 2 ;;
esac
# The CLI and the crate must be the same version, or the generated glue doesn't match.
WANT="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)"
[ -n "$WANT" ] || { echo "error: Cargo.lock names no wasm-bindgen version" >&2; exit 1; }
command -v wasm-bindgen >/dev/null || { echo "error: wasm-bindgen not found: cargo install wasm-bindgen-cli --version $WANT --locked" >&2; exit 1; }
HAVE="$(wasm-bindgen --version | awk '{ print $2 }')"
[ "$HAVE" = "$WANT" ] || { echo "error: wasm-bindgen $HAVE found, Cargo.lock needs $WANT: cargo install wasm-bindgen-cli --version $WANT --locked" >&2; exit 1; }
if command -v rustup >/dev/null && ! rustup target list --installed | grep -qx wasm32-unknown-unknown; then
echo "error: the wasm32-unknown-unknown target is missing: rustup target add wasm32-unknown-unknown" >&2
exit 1
fi
cargo build -p anicraft --bin anicraft --target wasm32-unknown-unknown --profile "$PROFILE"
TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}"
DIR="$PROFILE"
[ "$PROFILE" = dev ] && DIR=debug
WASM="$TARGET_DIR/wasm32-unknown-unknown/$DIR/anicraft.wasm"
OUT="$ROOT/web"
rm -rf "$OUT"
mkdir -p "$OUT"
wasm-bindgen --target web --no-typescript --out-dir "$OUT" --out-name anicraft "$WASM"
cp packaging/web/index.html "$OUT/index.html"
cp assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png "$OUT/anicraft.png"
BYTES="$(wc -c <"$OUT/anicraft_bg.wasm" | tr -d ' ')"
GZIP="$(gzip -9 -c "$OUT/anicraft_bg.wasm" | wc -c | tr -d ' ')"
echo "web/ is ready: anicraft_bg.wasm is $((BYTES / 1024)) KB ($((GZIP / 1024)) KB gzipped)."
echo "Serve it locally, for example: python3 -m http.server --directory web 8080 (then open http://localhost:8080)"
+61 -7
View File
@@ -382,8 +382,10 @@ pub const VIEW_SHORTCUTS: &[(&str, &str)] = &[
impl App {
pub fn new(cc: &eframe::CreationContext<'_>, session: Session, shot: Option<PathBuf>) -> App {
#[cfg_attr(not(gpu_stage), allow(unused_mut))]
let mut app = App::with_context(&cc.egui_ctx, session, shot);
// The GPU stage shares the window's device when it runs on wgpu (ADR 0029).
#[cfg(gpu_stage)]
app.stage_cache.gpu.set_window_device(cc.wgpu_render_state.as_ref());
app
}
@@ -401,7 +403,9 @@ impl App {
// Text lays out with the fonts on this computer plus the embedded interface font (so new
// text has the same default everywhere). Scan them now, off the UI thread.
anicraft_engine::text::Fonts::register(crate::theme::embedded_fonts());
std::thread::spawn(|| {
// (No thread in a browser, ADR 0036: there the library is only the embedded faces and
// is built on first use.)
let _ = std::thread::Builder::new().name("anicraft-font-scan".into()).spawn(|| {
let _ = anicraft_engine::text::Fonts::get();
});
let mut session = session;
@@ -522,7 +526,13 @@ impl App {
}
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
match self.s.execute(id, &params) {
let result = self.s.execute(id, &params);
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());
}
match result {
Ok(v) => Some(v),
Err(e) => {
self.status_err(e.to_string());
@@ -531,6 +541,18 @@ impl App {
}
}
/// A file the browser handed over: it goes where the command reads it, and the command runs
/// (through `request`, so opening over unsaved work asks first).
fn open_picked(&mut self, p: platform::Picked) {
// Only the name: the browser never says which folder it came from.
let name: String = std::path::Path::new(&p.name).file_name().map_or_else(|| "file".into(), |n| n.to_string_lossy().chars().take(128).collect());
let path = std::path::PathBuf::from(&name);
match p.data.and_then(|data| anicraft_engine::vfs::put(&path, data).map_err(|e| e.to_string())) {
Ok(()) => self.request(p.cmd, json!({"path": name})),
Err(e) => self.status_err(format!("Could not open {name}: {e}")),
}
}
// ----- preferences ----------------------------------------------------------------------
/// Applies scale and fonts from `self.prefs`. System fonts need the font scan; until it
@@ -971,7 +993,19 @@ impl App {
/// Runs a command and reports the outcome; routine destructive edits say how to undo.
pub fn perform(&mut self, id: &str, params: Value) -> Option<Value> {
let selected = self.s.selection.len();
// A browser's autosaved copy opens as a file (ADR 0036): it is a restore all the same.
let restored = autosave::restored_session(id, &params);
let v = self.run(id, params)?;
if let Some(session) = restored {
self.view.fit = true;
self.frame_sel = None;
self.library_sel = LibraryItem::first(&self.s.doc);
self.decode_sounds();
self.recovery.restored(&session);
let name = self.s.path.as_deref().and_then(std::path::Path::file_name).map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned());
self.status_ok(format!("Restored “{name}”. It isn't saved yet: Save to keep it."));
return Some(v);
}
match id {
"file.new" | "file.new_sample" | "file.open" => {
self.view.fit = true;
@@ -1001,7 +1035,8 @@ impl App {
self.status_ok("Discarded the autosaved copy");
}
"file.save" | "file.save_as" => {
self.status_ok(format!("Saved {}", v["saved"].as_str().unwrap_or("")));
// In a browser the file goes to the downloads (ADR 0036).
self.status_ok(format!("Saved {}{}", v["saved"].as_str().unwrap_or(""), if platform::WEB { " to your downloads" } else { "" }));
if self.close_after_save {
self.allow_close = true;
}
@@ -1101,6 +1136,10 @@ impl App {
"edit.paste" if self.timeline_focus && !self.s.frame_clipboard.is_empty() => "timeline.paste_frames",
other => other,
};
if let Some(why) = platform::unavailable(id) {
self.status_err(why);
return;
}
if id == "timeline.paste_frames"
&& let Some(p) = timeline::paste_params(self)
{
@@ -1108,7 +1147,9 @@ impl App {
return;
}
if id == "file.recovery_list" {
self.recovery.rescan();
if !self.recovery.rescan() {
return; // a browser answers on a later frame (autosave::tick)
}
self.recovery.show = !self.recovery.found.is_empty();
if !self.recovery.show {
self.status_ok(if self.recovery.active() { "No autosaved work to recover" } else { "Autosave is off on this system, so there is nothing to recover" });
@@ -1159,9 +1200,17 @@ impl App {
};
if let Some((title, key, text)) = prompt {
let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || id == "plugin.install");
if is_file && self.prefs.native_dialogs && self.shot.is_none() {
if is_file && platform::WEB && platform::reads_file(id) {
// The browser's file picker (ADR 0036). The file arrives on a later frame
// (`open_picked`); a save or export asks for the download's name below.
self.playing = false;
platform::pick_file(id);
return;
}
if is_file && self.prefs.native_dialogs && self.shot.is_none() && !platform::WEB {
// The platform's own dialog (it blocks, as native dialogs do). Cancel = no-op.
self.playing = false;
#[cfg(not(target_arch = "wasm32"))]
match platform::file_dialog(id, title, &text) {
Some(path) => self.request(id, json!({ key: path.display().to_string() })),
None => self.close_after_save = false,
@@ -1594,8 +1643,8 @@ fn app_mark(ctx: &egui::Context) -> egui::TextureHandle {
if let Some(tex) = ctx.data(|d| d.get_temp::<egui::TextureHandle>(id)) {
return tex;
}
let icon = eframe::icon_data::from_png_bytes(PNG).unwrap_or_default();
let image = egui::ColorImage::from_rgba_unmultiplied([icon.width as usize, icon.height as usize], &icon.rgba);
let (w, h, rgba) = anicraft_engine::doc::decode_png(PNG).map_or_else(|| (1, 1, vec![0; 4]), |p| (p.width as usize, p.height as usize, p.rgba));
let image = egui::ColorImage::from_rgba_unmultiplied([w, h], &rgba);
let options = egui::TextureOptions { mipmap_mode: Some(egui::TextureFilter::Linear), ..egui::TextureOptions::LINEAR };
let tex = ctx.load_texture("anicraft-app-mark", image, options);
ctx.data_mut(|d| d.insert_temp(id, tex.clone()));
@@ -1639,6 +1688,9 @@ impl App {
let ctx = ui.ctx().clone();
self.handle_screenshot(&ctx);
self.poll_font_scan(&ctx);
if let Some(p) = platform::picked_file() {
self.open_picked(p);
}
if self.glyph_check {
// Fonts installed last frame are live now: can they draw the macOS key symbols?
let ok = ctx.fonts_mut(|f| f.has_glyphs(&theme::font(theme::Type::Key), "⌘⇧⌥"));
@@ -1711,6 +1763,8 @@ impl App {
// After this frame's edits: start a recovery copy when one is due (off this thread).
autosave::tick(self, &ctx);
// A browser asks before leaving a page with unsaved work (its close guard).
platform::set_unsaved(self.s.is_dirty());
// An edit late in this frame (after the stage drew) must be shown without waiting for
// the next input event: egui only repaints on demand. This was the "drag commits after a
+157 -30
View File
@@ -5,12 +5,20 @@
//! its own thread, and the `file.recover` / `file.discard_recovery` commands act on what was
//! left behind. This module only decides *when* (Preferences: every N seconds, or after N
//! changes, whichever comes first) and shows the choices.
//!
//! In a browser (ADR 0036) the copies go to the site's storage instead of the recovery folder
//! (`web::BrowserSaver`, the same calls), and which tabs are still open is known a moment after
//! start, so the Recover window comes up then.
use crate::a11y::Named;
use crate::app::App;
use crate::prefs::Prefs;
use crate::theme::{T, Type, text};
use anicraft_engine::recovery::{self, Autosaver, Entry, Outcome, SessionLock};
#[cfg(target_arch = "wasm32")]
use crate::web::BrowserSaver as Autosaver;
use anicraft_engine::recovery::{self, Entry, Outcome};
#[cfg(not(target_arch = "wasm32"))]
use anicraft_engine::recovery::{Autosaver, SessionLock};
use anicraft_engine::StateId;
use serde_json::json;
use std::path::PathBuf;
@@ -38,6 +46,10 @@ pub struct Recovery {
pub show: bool,
/// The session whose Discard is waiting for its second click.
confirm_discard: Option<String>,
/// In a browser: the list of copies is on its way; `true` when the user asked for it (so
/// an empty one is said).
#[cfg(target_arch = "wasm32")]
scanning: Option<bool>,
}
/// Whether a new copy is due: unsaved for the whole interval, or enough changes made (not in
@@ -51,33 +63,59 @@ impl Recovery {
/// runs leave the real folder alone unless `ANICRAFT_RECOVERY_DIR` names one.
pub fn start(shot_mode: bool) -> (Recovery, Option<String>) {
let mut r = Recovery::default();
if shot_mode && !crate::platform::recovery_dir_overridden() {
return (r, None);
}
let Some(dir) = crate::platform::recovery_dir() else { return (r, Some("Autosave is off: this system has no settings folder".into())) };
recovery::prune(&dir);
r.found = recovery::scan(&dir, None);
r.show = !r.found.is_empty();
let err = match SessionLock::acquire(&dir).and_then(Autosaver::start) {
Ok(s) => {
r.saver = Some(s);
None
#[cfg(target_arch = "wasm32")]
{
let _ = shot_mode;
match Autosaver::start() {
Ok(s) => {
r.saver = Some(s);
r.scanning = Some(false);
(r, None)
}
Err(e) => (r, Some(format!("Autosave is off: {e}"))),
}
Err(e) => Some(format!("Autosave is off: {e}")),
};
r.dir = Some(dir);
(r, err)
}
#[cfg(not(target_arch = "wasm32"))]
{
if shot_mode && !crate::platform::recovery_dir_overridden() {
return (r, None);
}
let Some(dir) = crate::platform::recovery_dir() else { return (r, Some("Autosave is off: this system has no settings folder".into())) };
recovery::prune(&dir);
r.found = recovery::scan(&dir, None);
r.show = !r.found.is_empty();
let err = match SessionLock::acquire(&dir).and_then(Autosaver::start) {
Ok(s) => {
r.saver = Some(s);
None
}
Err(e) => Some(format!("Autosave is off: {e}")),
};
r.dir = Some(dir);
(r, err)
}
}
pub fn active(&self) -> bool {
self.saver.is_some()
}
/// Rescans for left-behind copies (File › Recover Autosaved Documents…).
pub fn rescan(&mut self) {
if let Some(dir) = &self.dir {
let own = self.saver.as_ref().map(|s| s.id().to_string());
self.found = recovery::scan(dir, own.as_deref());
/// Rescans for left-behind copies (File › Recover Autosaved Documents…). `false` when the
/// list comes later (a browser asks which tabs are open), and [`tick`] shows it then.
pub fn rescan(&mut self) -> bool {
#[cfg(target_arch = "wasm32")]
{
crate::web::refresh_live();
self.scanning = Some(true);
false
}
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(dir) = &self.dir {
let own = self.saver.as_ref().map(|s| s.id().to_string());
self.found = recovery::scan(dir, own.as_deref());
}
true
}
}
@@ -107,8 +145,92 @@ impl Recovery {
}
}
/// Removes another session's copy once this one holds its work (the user chose Restore).
fn drop_adopted(app: &mut App, old: &str) {
#[cfg(target_arch = "wasm32")]
{
let _ = &app;
crate::web::discard(old);
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(dir) = app.recovery.dir.clone() {
// Through the command, as any front end would.
let _ = app.s.execute("file.discard_recovery", &json!({"dir": dir.display().to_string(), "session": old, "confirm": true}));
}
}
/// In a browser: shows the copies once the browser has said which tabs are still open.
#[cfg(target_arch = "wasm32")]
fn poll_scan(app: &mut App) {
let Some(asked) = app.recovery.scanning else { return };
let own = app.recovery.saver.as_ref().map(|s| s.id().to_string());
let Some(found) = crate::web::scan(own.as_deref()) else { return };
let r = &mut app.recovery;
r.scanning = None;
r.found = found;
r.show = !r.found.is_empty();
if asked && !r.show {
app.status_ok("No autosaved work to recover");
}
}
/// Where a restored browser copy is opened from: `recovered/<session>/<name>`, so its download
/// keeps the document's name.
pub const RESTORED_DIR: &str = "recovered";
/// The session a `file.open` restores, when it opens a browser copy (see [`RESTORED_DIR`]).
pub fn restored_session(cmd: &str, params: &serde_json::Value) -> Option<String> {
if cmd != "file.open" || params.get("unsaved") != Some(&json!(true)) {
return None;
}
let path = std::path::Path::new(params.get("path")?.as_str()?);
let mut parts = path.components().map(|c| c.as_os_str().to_string_lossy().into_owned());
(parts.next()? == RESTORED_DIR).then(|| parts.next()).flatten().filter(|id| recovery::valid_id(id))
}
/// Restore: opens the copy as unsaved work. Through `request`, so restoring over unsaved
/// changes asks first (ADR 0004).
fn restore(app: &mut App, id: String) {
#[cfg(target_arch = "wasm32")]
{
let Some((json, meta)) = crate::web::load(&id) else {
app.status_err("That autosaved copy is gone");
app.recovery.discarded(&id);
return;
};
let name = meta.original.as_deref().and_then(std::path::Path::file_name).map_or_else(|| "Untitled.anicraft".to_string(), |n| n.to_string_lossy().into_owned());
let path = std::path::Path::new(RESTORED_DIR).join(&id).join(&name);
match anicraft_engine::vfs::put(&path, json.into_bytes()) {
Ok(()) => app.request("file.open", json!({"path": path.display().to_string(), "unsaved": true, "untitled": meta.original.is_none()})),
Err(e) => app.status_err(format!("Could not restore {name}: {e}")),
}
}
#[cfg(not(target_arch = "wasm32"))]
{
let dir = app.recovery.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default();
app.request("file.recover", json!({"dir": dir, "session": id}));
}
}
/// Discard (after its second click): the copy is deleted for good.
fn discard(app: &mut App, id: String) {
#[cfg(target_arch = "wasm32")]
{
crate::web::discard(&id);
app.recovery.discarded(&id);
app.status_ok("Discarded the autosaved copy");
}
#[cfg(not(target_arch = "wasm32"))]
{
let dir = app.recovery.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default();
app.perform("file.discard_recovery", json!({"dir": dir, "session": id, "confirm": true}));
}
}
/// Per frame: collects finished copies and starts a new one when it is due.
pub fn tick(app: &mut App, ctx: &egui::Context) {
#[cfg(target_arch = "wasm32")]
poll_scan(app);
let now = ctx.input(|i| i.time);
let outcomes = app.recovery.saver.as_ref().map(Autosaver::poll).unwrap_or_default();
for o in outcomes {
@@ -116,9 +238,8 @@ pub fn tick(app: &mut App, ctx: &egui::Context) {
Outcome::Written { .. } => {
app.recovery.last_copy_at = Some(now);
app.recovery.failed = false;
if let (Some(old), Some(dir)) = (app.recovery.adopt.take(), app.recovery.dir.clone()) {
// Through the command, as any front end would. The user chose Restore.
let _ = app.s.execute("file.discard_recovery", &json!({"dir": dir.display().to_string(), "session": old, "confirm": true}));
if let Some(old) = app.recovery.adopt.take() {
drop_adopted(app, &old);
}
}
Outcome::Failed { error, .. } => {
@@ -295,18 +416,14 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
if !open {
act = Some(Act::Later);
}
let dir = app.recovery.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default();
match act {
// Through `request`: restoring over unsaved changes asks first (ADR 0004).
Some(Act::Restore(id)) => {
app.recovery.confirm_discard = None;
app.request("file.recover", json!({"dir": dir, "session": id}));
restore(app, id);
}
Some(Act::AskDiscard(id)) => app.recovery.confirm_discard = Some(id),
// The second click on the red button is the confirmation.
Some(Act::Discard(id)) => {
app.perform("file.discard_recovery", json!({"dir": dir, "session": id, "confirm": true}));
}
Some(Act::Discard(id)) => discard(app, id),
Some(Act::KeepIt) => app.recovery.confirm_discard = None,
Some(Act::Later) => {
app.recovery.show = false;
@@ -333,6 +450,16 @@ mod tests {
assert!(!due(5.0, 10_000, false, &time_only));
}
#[test]
fn restored_browser_copies_are_recognized() {
let open = |path: &str| json!({"path": path, "unsaved": true});
assert_eq!(restored_session("file.open", &open("recovered/web-1a-2b/walk.anicraft")).as_deref(), Some("web-1a-2b"));
assert_eq!(restored_session("file.open", &json!({"path": "recovered/web-1/walk.anicraft"})), None, "an ordinary open");
assert_eq!(restored_session("file.open", &open("walk.anicraft")), None);
assert_eq!(restored_session("file.open", &open("recovered/../x/y")), None);
assert_eq!(restored_session("file.save", &open("recovered/web-1/walk.anicraft")), None);
}
#[test]
fn ages_read_naturally() {
assert_eq!(ago(5), "just now");
+1 -1
View File
@@ -519,7 +519,7 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
});
ui.separator();
ui.label(text(Type::Caption, format!("{} · settings stored in {}", crate::platform::OS.name(), crate::platform::config_dir().map_or_else(|| "memory only".to_string(), |d| d.display().to_string()))));
ui.label(text(Type::Caption, format!("{} · settings stored in {}", crate::platform::OS.name(), crate::platform::settings_place())));
});
a11y::name_title_bar(&shown, title);
if reset_confirms {
+15 -15
View File
@@ -6,6 +6,9 @@
//! missing or fails. Without the feature this is a stub and the CPU always draws. Exports never
//! use it.
//!
//! The web build has no GPU stage yet (ADR 0036): in the browser wgpu's objects belong to one
//! thread and start asynchronously, so the renderer can't run behind the render service there.
//!
//! When the window runs on wgpu, the renderer shares the window's device and draws each stage
//! tile into a texture the window shows as it is (no copy back to the CPU, ADR 0029). When it
//! can't (the window on OpenGL, or the window's device lacks what the stage needs) it opens a
@@ -19,7 +22,7 @@ use anicraft_engine::render_service::{NativeImage, RenderService};
/// Where the GPU stage is.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(not(feature = "gpu-stage"), allow(dead_code))]
#[cfg_attr(not(gpu_stage), allow(dead_code))]
pub enum State {
/// The CPU draws (by choice, or because this build has no GPU stage).
Off,
@@ -31,7 +34,7 @@ pub enum State {
}
/// Whether this build has the GPU stage at all.
pub const AVAILABLE: bool = cfg!(feature = "gpu-stage");
pub const AVAILABLE: bool = cfg!(gpu_stage);
/// The renderer the user asked for, after the environment override.
pub fn wanted(pref: StageRenderer) -> StageRenderer {
@@ -44,7 +47,7 @@ pub fn wanted(pref: StageRenderer) -> StageRenderer {
#[derive(Default)]
pub struct GpuStage {
#[cfg(feature = "gpu-stage")]
#[cfg(gpu_stage)]
imp: imp::Imp,
}
@@ -52,7 +55,7 @@ pub struct GpuStage {
/// window's renderer for as long as this lives.
pub struct NativeTile {
id: egui::TextureId,
#[cfg(feature = "gpu-stage")]
#[cfg(gpu_stage)]
_keep: imp::Registered,
}
@@ -64,19 +67,16 @@ impl NativeTile {
impl GpuStage {
pub fn state(&self) -> State {
#[cfg(feature = "gpu-stage")]
#[cfg(gpu_stage)]
return self.imp.state.clone();
#[cfg(not(feature = "gpu-stage"))]
#[cfg(not(gpu_stage))]
State::Off
}
/// The window's wgpu device, when it runs on wgpu (from eframe's creation context).
#[allow(unused_variables)]
#[cfg(gpu_stage)]
pub fn set_window_device(&mut self, rs: Option<&eframe::egui_wgpu::RenderState>) {
#[cfg(feature = "gpu-stage")]
{
self.imp.window = rs.cloned();
}
self.imp.window = rs.cloned();
}
/// Applies the choice to the render service (called every frame; cheap when nothing
@@ -85,7 +85,7 @@ impl GpuStage {
pub fn sync(&mut self, pref: StageRenderer, svc: &RenderService, ctx: &egui::Context) {
// Unit tests never open a graphics device (as they never open an audio one): a start-up
// thread still inside the driver when the test process exits can crash it.
#[cfg(feature = "gpu-stage")]
#[cfg(gpu_stage)]
self.imp.sync(wanted(pref) == StageRenderer::Gpu && !cfg!(test), svc, ctx);
}
@@ -93,14 +93,14 @@ impl GpuStage {
/// `None` when it isn't one of ours (then nothing is shown and the tile is drawn again).
#[allow(unused_variables)]
pub fn register(&self, native: &NativeImage) -> Option<NativeTile> {
#[cfg(feature = "gpu-stage")]
#[cfg(gpu_stage)]
return self.imp.register(native);
#[cfg(not(feature = "gpu-stage"))]
#[cfg(not(gpu_stage))]
None
}
}
#[cfg(feature = "gpu-stage")]
#[cfg(gpu_stage)]
mod imp {
use super::{NativeTile, State};
use anicraft_engine::render_service::{NativeImage, Raster, Rasterizer, RenderService};
+21
View File
@@ -6,11 +6,17 @@
//! anicraft --version
//! ```
//! `--screenshot` starts normally, draws ~120 frames, saves the window as PNG and exits.
//!
//! Built for `wasm32-unknown-unknown` the same program is the web editor (`src/web.rs`,
//! ADR 0036, docs/web.md).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
// Release builds are Windows GUI programs, so no console window opens beside the app (the
// packaging checks the PE subsystem, ADR 0026). Debug builds keep the console for logs; the
// headless front end is anicraft-cli.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
// The browser build leaves out what only the desktop has (screenshot runs, the recovery folder,
// window chrome, `--open` panels); that code stays compiled for it but unused (ADR 0036).
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]
mod a11y;
mod actions_panel;
@@ -36,14 +42,19 @@ mod stage;
mod test_movie;
mod theme;
mod timeline;
#[cfg(target_arch = "wasm32")]
mod web;
mod widthtool;
#[cfg(not(target_arch = "wasm32"))]
use anicraft_engine::Session;
#[cfg(not(target_arch = "wasm32"))]
use std::path::{Path, PathBuf};
/// The session to start with: the file given on the command line (through `file.open`, so
/// `.fla` / `.xfl` import works the same as from the menu), else the sample. Also the import
/// report of an Animate document, for the status bar.
#[cfg(not(target_arch = "wasm32"))]
fn open_session(file: Option<&Path>) -> (Session, Option<String>) {
let Some(p) = file else { return (Session::new(anicraft_engine::doc::sample::demo()), None) };
let mut s = Session::default();
@@ -64,12 +75,14 @@ fn open_session(file: Option<&Path>) -> (Session, Option<String>) {
/// `--theme` / `--scale`: the look for this run only (screenshots of high contrast or 200 %),
/// over the saved preferences, without saving them.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, Default)]
struct Look {
theme: Option<theme::Palette>,
scale: Option<f32>,
}
#[cfg(not(target_arch = "wasm32"))]
fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option<PathBuf>, open: Option<String>, look: Look) -> eframe::Result {
let options = eframe::NativeOptions {
viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])),
@@ -96,6 +109,14 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option<PathBuf>, o
)
}
/// In the browser the page's script calls this once the module is loaded: the editor starts on
/// the page's canvas.
#[cfg(target_arch = "wasm32")]
fn main() {
web::start();
}
#[cfg(not(target_arch = "wasm32"))]
fn main() -> eframe::Result {
let mut shot: Option<PathBuf> = None;
let mut file: Option<PathBuf> = None;
+12 -3
View File
@@ -67,7 +67,14 @@ fn item(app: &mut App, ui: &mut egui::Ui, spec: &CommandSpec) {
_ => spec.label.to_string(),
};
let button = egui::Button::new(label).shortcut_text(text(Type::Key, platform::shortcut_label(app.keymap.primary(spec.id).unwrap_or(""))));
if ui.add_enabled(enabled(app, spec.id), button).clicked() {
// What this build can't do stays in its usual place, dimmed, saying why (the web build).
let missing = platform::unavailable(spec.id);
let r = ui.add_enabled(enabled(app, spec.id) && missing.is_none(), button);
let r = match missing {
Some(why) => r.on_disabled_hover_text(why),
None => r,
};
if r.clicked() {
app.invoke(spec.id);
ui.close();
}
@@ -134,7 +141,8 @@ fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpe
match top {
// Windows / Linux conventions; on macOS these live in the AniCraft (application) menu.
"File" if platform::OS != Os::Mac => {
// A web page is closed with its tab.
"File" if platform::OS != Os::Mac && !platform::WEB => {
ui.separator();
if ui_item(ui, "Exit", "Ctrl+Q", None) {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
@@ -228,7 +236,8 @@ fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpe
app.show_shortcuts = true;
}
ui.separator();
if ui_item(ui, "Project Files & Docs…", "", None) {
// (The web build has no folders to show.)
if !platform::WEB && ui_item(ui, "Project Files & Docs…", "", None) {
app.show_files = true;
}
if ui_item(ui, "Licenses & Notices", "", None) {
+126 -2
View File
@@ -1,6 +1,9 @@
//! Platform layer (ADR 0006). Every OS-specific decision in the shell lives here, so the rest
//! of the UI is written once: shortcut labels (⌘ on macOS), window chrome, the settings folder,
//! native file dialogs and the renderer choice.
//!
//! The web build (ADR 0036) is one more platform: the browser's file picker and downloads take
//! the dialogs' place, its storage the settings folder's, and the glue lives in `web.rs`.
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -10,6 +13,8 @@ pub enum Os {
Mac,
Windows,
Linux,
/// A web browser (the wasm32 build).
Web,
Other,
}
@@ -17,6 +22,8 @@ pub const OS: Os = if cfg!(target_os = "macos") {
Os::Mac
} else if cfg!(target_os = "windows") {
Os::Windows
} else if cfg!(target_arch = "wasm32") {
Os::Web
} else if cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly")) {
Os::Linux
} else {
@@ -29,14 +36,31 @@ impl Os {
Os::Mac => "macOS",
Os::Windows => "Windows",
Os::Linux => "Linux / BSD",
Os::Web => "web browser",
Os::Other => "other",
}
}
}
/// The web build runs in a browser (ADR 0036).
pub const WEB: bool = cfg!(target_arch = "wasm32");
/// Whether the active fonts can draw ⌘ ⇧ ⌥ ⌃ (set once fonts are installed).
static MAC_GLYPHS: AtomicBool = AtomicBool::new(false);
/// In a browser: whether it runs on a Mac (its command key is ⌘, as egui reads it there).
static WEB_ON_MAC: AtomicBool = AtomicBool::new(false);
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
pub fn set_web_on_mac(mac: bool) {
WEB_ON_MAC.store(mac, Ordering::Relaxed);
}
/// Whose conventions shortcut labels follow: the OS's, or in a browser the computer's under it.
fn keys_os() -> Os {
if OS == Os::Web && WEB_ON_MAC.load(Ordering::Relaxed) { Os::Mac } else { OS }
}
pub fn set_mac_glyphs(available: bool) {
MAC_GLYPHS.store(available, Ordering::Relaxed);
}
@@ -44,7 +68,7 @@ pub fn set_mac_glyphs(available: bool) {
/// A registry shortcut ("Ctrl+Shift+S") as this platform writes it: unchanged on Windows and
/// Linux; "⇧⌘S" on macOS (or "Shift+Cmd+S" when the font lacks the symbols).
pub fn shortcut_label(s: &str) -> String {
shortcut_label_for(OS, s, MAC_GLYPHS.load(Ordering::Relaxed))
shortcut_label_for(keys_os(), s, MAC_GLYPHS.load(Ordering::Relaxed))
}
pub fn shortcut_label_for(os: Os, s: &str, glyphs: bool) -> String {
@@ -85,6 +109,8 @@ pub fn config_dir() -> Option<PathBuf> {
match OS {
Os::Windows => env("APPDATA").map(|p| p.join("AniCraft")),
Os::Mac => env("HOME").map(|p| p.join("Library").join("Application Support").join("AniCraft")),
// A web page has no folders: settings go to browser storage (`load_settings`).
Os::Web => None,
Os::Linux | Os::Other => env("XDG_CONFIG_HOME").or_else(|| env("HOME").map(|h| h.join(".config"))).map(|p| p.join("anicraft")),
}
}
@@ -103,6 +129,49 @@ pub fn recovery_dir_overridden() -> bool {
std::env::var_os("ANICRAFT_RECOVERY_DIR").is_some_and(|v| !v.is_empty())
}
/// Where settings are kept, for Preferences.
pub fn settings_place() -> String {
if WEB {
return "this browser's storage for this site".into();
}
config_dir().map_or_else(|| "memory only".to_string(), |d| d.display().to_string())
}
/// The saved preferences (JSON): `prefs.json` in the settings folder, or browser storage.
pub fn load_settings() -> Option<String> {
#[cfg(target_arch = "wasm32")]
return crate::web::storage_get(crate::web::PREFS_KEY);
#[cfg(not(target_arch = "wasm32"))]
config_dir().and_then(|d| std::fs::read_to_string(d.join("prefs.json")).ok())
}
/// Saves the preferences; on disk atomically (temp file + rename).
pub fn save_settings(json: &str) -> Result<(), String> {
#[cfg(target_arch = "wasm32")]
return crate::web::storage_set(crate::web::PREFS_KEY, json);
#[cfg(not(target_arch = "wasm32"))]
{
let dir = config_dir().ok_or("no settings folder on this system")?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let (path, tmp) = (dir.join("prefs.json"), dir.join("prefs.json.tmp"));
std::fs::write(&tmp, json).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, &path).map_err(|e| e.to_string())
}
}
/// Why this build can't run `cmd`, if it can't: a web page can't start ffmpeg or keep files in
/// a folder of the computer (ADR 0036). The desktop app runs everything.
pub fn unavailable(cmd: &str) -> Option<&'static str> {
if !WEB {
return None;
}
match cmd {
"file.export_video" => Some("Video export runs ffmpeg, which a web browser can't start: use the desktop app, or export an animated GIF or a PNG sequence"),
"plugin.install" | "plugin.remove" | "plugin.reload" => Some("Plug-ins are installed into a folder on your computer: use the desktop app"),
_ => None,
}
}
/// Where installed plug-ins live: a `plugins` folder in the settings folder (ADR 0017).
pub fn plugins_dir() -> Option<PathBuf> {
config_dir().map(|d| d.join("plugins"))
@@ -114,6 +183,7 @@ pub const APP_ID: &str = "ai.storyteller.anicraft";
/// Main-window chrome. macOS gets the unified look (content under a transparent title bar,
/// traffic lights over our menu row); Windows and Linux keep their native frames.
#[cfg(not(target_arch = "wasm32"))]
pub fn viewport(b: egui::ViewportBuilder) -> egui::ViewportBuilder {
// The Wayland app_id / X11 class: docks match it to the installed desktop entry
// (packaging/linux/ai.storyteller.anicraft.desktop) for the icon and the launcher.
@@ -126,6 +196,7 @@ pub fn viewport(b: egui::ViewportBuilder) -> egui::ViewportBuilder {
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
/// the tile on Apple's grid (with its transparent margin); elsewhere the full-bleed tile.
#[cfg(not(target_arch = "wasm32"))]
fn app_icon() -> egui::IconData {
#[cfg(target_os = "macos")]
let png: &[u8] = include_bytes!("../assets/app-icon/anicraft-macos-512.png");
@@ -140,6 +211,7 @@ pub fn menu_inset() -> f32 {
}
/// Renderer requested by `--renderer` / `ANICRAFT_RENDERER` (`wgpu` or `gl`), if any.
#[cfg(not(target_arch = "wasm32"))]
pub fn forced_renderer(arg: Option<&str>) -> Option<eframe::Renderer> {
let v = arg.map(str::to_owned).or_else(|| std::env::var("ANICRAFT_RENDERER").ok())?;
match v.to_ascii_lowercase().as_str() {
@@ -171,22 +243,74 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) {
}
}
/// Commands that read a file the user picks (the others write one, or a folder of them).
pub fn reads_file(cmd: &str) -> bool {
matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library")
}
/// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal).
/// `None` when cancelled.
#[cfg(not(target_arch = "wasm32"))]
pub fn file_dialog(cmd: &str, title: &str, default_name: &str) -> Option<PathBuf> {
let (label, exts) = filters(cmd);
let d = rfd::FileDialog::new().set_title(title);
match cmd {
"file.open" | "plugin.install" | "file.import" | "file.import_to_library" => d.add_filter(label, exts).pick_file(),
c if reads_file(c) => d.add_filter(label, exts).pick_file(),
"file.export_png_sequence" => d.pick_folder(),
_ => d.add_filter(label, exts).set_file_name(default_name).save_file(),
}
}
/// In a browser: asks for a file with the browser's file picker. It arrives later through
/// [`picked_file`]; nothing arrives if the user cancels. The desktop has [`file_dialog`].
#[cfg_attr(not(target_arch = "wasm32"), allow(unused_variables, dead_code))]
pub fn pick_file(cmd: &'static str) {
#[cfg(target_arch = "wasm32")]
crate::web::pick_file(cmd, filters(cmd).1);
}
/// A file the user picked in the browser: the command that asked for it, its name, and its
/// bytes (or why the browser couldn't read them).
pub struct Picked {
pub cmd: &'static str,
pub name: String,
pub data: Result<Vec<u8>, String>,
}
/// The next file the browser handed over, if one arrived.
pub fn picked_file() -> Option<Picked> {
#[cfg(target_arch = "wasm32")]
return crate::web::take_picked();
#[cfg(not(target_arch = "wasm32"))]
None
}
/// 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<u8>)>) {
#[cfg(target_arch = "wasm32")]
for (path, data) in files {
crate::web::download(&path, &data);
}
}
/// 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) {
#[cfg(target_arch = "wasm32")]
crate::web::set_unsaved(unsaved);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_desktop_runs_every_command() {
assert!(anicraft_engine::commands().iter().all(|c| unavailable(c.id).is_none()));
assert!(reads_file("file.open") && reads_file("file.import") && !reads_file("file.save"));
}
#[test]
fn mac_labels_use_apple_order_and_glyphs() {
assert_eq!(shortcut_label_for(Os::Mac, "Ctrl+Shift+S", true), "⇧⌘S");
+4 -14
View File
@@ -1,5 +1,5 @@
//! User preferences: appearance (fonts, UI scale), stage rendering, file dialogs. Stored as
//! JSON in the platform's settings folder (`platform::config_dir`). A missing or broken file
//! JSON in the platform's settings folder (`platform::load_settings`; browser storage on the web). A missing or broken file
//! falls back to defaults; it never stops the app from starting.
use serde::{Deserialize, Serialize};
@@ -114,10 +114,6 @@ pub const SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.75..=2.0;
pub const GAP_RANGE: std::ops::RangeInclusive<f32> = 0.0..=48.0;
impl Prefs {
fn path() -> Option<std::path::PathBuf> {
crate::platform::config_dir().map(|d| d.join("prefs.json"))
}
pub fn sanitized(mut self) -> Prefs {
self.ui_scale = if self.ui_scale.is_finite() { self.ui_scale.clamp(*SCALE_RANGE.start(), *SCALE_RANGE.end()) } else { 1.0 };
self.timeline_start_gap = if self.timeline_start_gap.is_finite() { self.timeline_start_gap.clamp(*GAP_RANGE.start(), *GAP_RANGE.end()) } else { 0.0 };
@@ -139,19 +135,13 @@ impl Prefs {
}
pub fn load() -> Prefs {
Self::path().and_then(|p| std::fs::read_to_string(p).ok()).map_or_else(Prefs::default, |t| Prefs::from_json(&t))
crate::platform::load_settings().map_or_else(Prefs::default, |t| Prefs::from_json(&t))
}
/// Writes atomically (temp file + rename).
/// Writes where the platform keeps settings (a file, atomically; or browser storage).
pub fn save(&self) -> Result<(), String> {
let path = Self::path().ok_or("no settings folder on this system")?;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
}
let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
let tmp = path.with_extension("json.tmp");
std::fs::write(&tmp, json).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, &path).map_err(|e| e.to_string())
crate::platform::save_settings(&json)
}
}
+10 -10
View File
@@ -16,7 +16,7 @@ use std::sync::{Arc, Mutex};
pub struct SoundOut {
player: Arc<Mutex<Player>>,
failed: Arc<AtomicBool>,
#[cfg(feature = "sound-output")]
#[cfg(sound_output)]
stream: Option<cpal::Stream>,
tried: bool,
rate: u32,
@@ -33,7 +33,7 @@ impl SoundOut {
SoundOut {
player: Arc::new(Mutex::new(Player::new(48_000))),
failed: Arc::new(AtomicBool::new(false)),
#[cfg(feature = "sound-output")]
#[cfg(sound_output)]
stream: None,
tried: false,
rate: 48_000,
@@ -48,7 +48,7 @@ impl SoundOut {
if !self.tried {
self.tried = true;
match open(&self.player, &self.failed) {
#[cfg(feature = "sound-output")]
#[cfg(sound_output)]
Ok((stream, rate)) => {
self.stream = Some(stream);
self.rate = rate;
@@ -56,7 +56,7 @@ impl SoundOut {
*p = Player::new(rate);
}
}
#[cfg(not(feature = "sound-output"))]
#[cfg(not(sound_output))]
Ok(rate) => self.rate = rate,
Err(e) => self.error = Some(e),
}
@@ -66,9 +66,9 @@ impl SoundOut {
/// The device is open and working.
fn live(&self) -> bool {
#[cfg(feature = "sound-output")]
#[cfg(sound_output)]
let open = self.stream.is_some();
#[cfg(not(feature = "sound-output"))]
#[cfg(not(sound_output))]
let open = false;
open && !self.failed.load(Ordering::Relaxed)
}
@@ -149,7 +149,7 @@ impl SoundOut {
}
}
#[cfg(feature = "sound-output")]
#[cfg(sound_output)]
fn open(player: &Arc<Mutex<Player>>, failed: &Arc<AtomicBool>) -> Result<(cpal::Stream, u32), String> {
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
let device = cpal::default_host().default_output_device().ok_or("no sound output device")?;
@@ -168,14 +168,14 @@ fn open(player: &Arc<Mutex<Player>>, failed: &Arc<AtomicBool>) -> Result<(cpal::
Ok((stream, rate))
}
#[cfg(not(feature = "sound-output"))]
#[cfg(not(sound_output))]
fn open(_: &Arc<Mutex<Player>>, _: &Arc<AtomicBool>) -> Result<u32, String> {
Err("this build of AniCraft has no sound output".into())
Err(if cfg!(target_arch = "wasm32") { "the web version of AniCraft has no sound output yet".into() } else { "this build of AniCraft has no sound output".into() })
}
/// An output stream whose callback mixes from the player. The lock is held only while one
/// buffer is mixed; the UI holds it only to change a few fields.
#[cfg(feature = "sound-output")]
#[cfg(sound_output)]
fn build<T: cpal::SizedSample + cpal::FromSample<f32>>(device: &cpal::Device, config: cpal::StreamConfig, player: &Arc<Mutex<Player>>, failed: &Arc<AtomicBool>) -> Result<cpal::Stream, cpal::Error> {
use cpal::traits::DeviceTrait;
let channels = usize::from(config.channels);
+1 -1
View File
@@ -664,7 +664,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
RenderMode::Auto => app.stage_cache.ms <= IMMEDIATE_BUDGET_MS,
};
let batch: Vec<FrameJob> = missing.iter().map(|&i| jobs[i].1.clone()).collect();
let started = std::time::Instant::now();
let started = web_time::Instant::now();
let results: Vec<Option<std::sync::Arc<FrameImage>>> = if immediate { svc.render_now_batch(batch).into_iter().map(Some).collect() } else { svc.request_batch(batch) };
let wall = started.elapsed().as_secs_f32() * 1000.0;
let mut ms = 0.0f32;
+1 -1
View File
@@ -149,7 +149,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
let px = [((sw * scale).round() as u32).max(1), ((sh * scale).round() as u32).max(1)];
let stale = tm.shown.as_ref().is_none_or(|(st, at)| *st != tm.movie.state || *at != px);
if stale {
let t0 = std::time::Instant::now();
let t0 = web_time::Instant::now();
let dl = evaluate_player(&tm.doc, &tm.movie.state);
let view = View { transform: Affine::scale(scale, scale), width: px[0], height: px[1], background: Some(tm.doc.stage.background) };
if let Ok((pm, _)) = render(&dl, &view) {
+399
View File
@@ -0,0 +1,399 @@
//! The editor in a web browser (ADR 0036, docs/web.md): the start on the page's canvas, and
//! what the browser offers in place of the operating system's services. `platform.rs` decides
//! when they are used; this module only talks to the browser.
//!
//! * **Files.** The browser's file picker brings a file in; its bytes go to the engine's
//! in-memory store (`engine::vfs`) and the command runs on it. What a save or an export
//! writes there leaves as a download.
//! * **Settings and crash-recovery copies** (ADR 0015) live in the browser's local storage for
//! this site. Each tab holds a Web Lock named after its session for as long as it is open,
//! so the copies offered at start are those of tabs that closed or crashed, never those of a
//! tab still open (the same rule as the desktop's lock files).
//! * **Leaving the page** with unsaved work asks first, as closing the window does.
//!
//! Nothing here can panic on what the browser returns: every call that can fail is checked
//! and a failure degrades (no storage: autosave is off and says so; no picker: nothing opens).
use crate::platform::Picked;
use anicraft_engine::doc::Document;
use anicraft_engine::recovery::{Entry, Outcome, RecoveryMeta, WriteStats};
use std::cell::{Cell, RefCell};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
/// Where the preferences are kept.
pub const PREFS_KEY: &str = "anicraft.prefs";
/// Recovery copies: `<prefix><session>.doc` (the document) and `.meta` (its description).
const RECOVERY_PREFIX: &str = "anicraft.recovery.";
/// Each open tab's Web Lock: this prefix and its session id.
const LOCK_PREFIX: &str = "anicraft-session-";
/// The page's canvas and loading message (packaging/web/index.html).
const CANVAS_ID: &str = "anicraft_canvas";
const LOADING_ID: &str = "anicraft_loading";
const PICKER_ID: &str = "anicraft_file_input";
/// Largest file taken from the picker (the engine's own limits are lower for most kinds).
const MAX_PICK_BYTES: f64 = 512.0 * 1024.0 * 1024.0;
thread_local! {
/// Files the picker delivered, waiting for the next frame.
static PICKED: RefCell<Vec<Picked>> = const { RefCell::new(Vec::new()) };
/// The editor's context, to wake it when something arrives.
static CTX: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
static UNSAVED: Cell<bool> = const { Cell::new(false) };
/// Sessions whose tab is still open (they hold their lock); `None` until the browser said.
static LIVE: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}
/// Starts the editor on the page's canvas.
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();
wasm_bindgen_futures::spawn_local(async {
match run().await {
Ok(()) => {
if let Some(el) = element(LOADING_ID) {
el.remove();
}
}
Err(e) => {
web_sys::console::error_1(&JsValue::from_str(&e));
if let Some(el) = element(LOADING_ID) {
el.set_text_content(Some(&format!("AniCraft could not start in this browser: {e}")));
}
}
}
});
}
async fn run() -> Result<(), String> {
let canvas = element(CANVAS_ID).ok_or("the page has no canvas for AniCraft")?.dyn_into::<web_sys::HtmlCanvasElement>().map_err(|_| "the AniCraft element is not a canvas")?;
// Text needs a face to lay out with, and a page can't see the computer's fonts.
anicraft_engine::text::Fonts::register(fonts());
let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo());
eframe::WebRunner::new()
.start(
canvas,
eframe::WebOptions::default(),
Box::new(move |cc| {
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
Ok(Box::new(crate::app::App::new(cc, session, None)))
}),
)
.await
.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))
}
/// The embedded interface faces, or egui's own (in every build) when there are none.
fn fonts() -> Vec<Arc<[u8]>> {
let mut faces = crate::theme::embedded_fonts();
if faces.is_empty()
&& let Some(f) = egui::FontDefinitions::default().font_data.get("Ubuntu-Light")
{
faces.push(Arc::from(f.font.as_ref()));
}
faces
}
fn document() -> Option<web_sys::Document> {
web_sys::window()?.document()
}
fn element(id: &str) -> Option<web_sys::Element> {
document()?.get_element_by_id(id)
}
fn repaint() {
CTX.with(|c| {
if let Some(ctx) = c.borrow().as_ref() {
ctx.request_repaint();
}
});
}
// ----- files ------------------------------------------------------------------------------------
/// Opens the browser's file picker for `cmd`, showing files with these extensions. The file
/// arrives through [`take_picked`]; a cancelled picker delivers nothing.
pub fn pick_file(cmd: &'static str, exts: &[&str]) {
let Some(doc) = document() else { return };
let Some(body) = doc.body() else { return };
// One picker at a time: a cancelled one is still on the page.
if let Some(old) = doc.get_element_by_id(PICKER_ID) {
old.remove();
}
let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else { return };
input.set_type("file");
input.set_id(PICKER_ID);
input.set_accept(&exts.iter().map(|e| format!(".{e}")).collect::<Vec<_>>().join(","));
let _ = input.style().set_property("display", "none");
let picker = input.clone();
let on_change = Closure::once_into_js(move || {
let file = picker.files().and_then(|l| l.get(0));
picker.remove();
if let Some(file) = file {
wasm_bindgen_futures::spawn_local(read_picked(cmd, file));
}
});
input.set_onchange(Some(on_change.unchecked_ref()));
// Some browsers only open pickers that are on the page.
if body.append_child(&input).is_ok() {
input.click();
}
}
async fn read_picked(cmd: &'static str, file: web_sys::File) {
let name = file.name();
let data = if file.size() > MAX_PICK_BYTES {
Err(format!("it is larger than {} MB", MAX_PICK_BYTES as u64 >> 20))
} else {
match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await {
Ok(buf) => Ok(js_sys::Uint8Array::new(&buf).to_vec()),
Err(_) => Err("the browser could not read it".to_string()),
}
};
PICKED.with(|p| p.borrow_mut().push(Picked { cmd, name, data }));
repaint();
}
/// The next file the picker delivered.
pub fn take_picked() -> Option<Picked> {
PICKED.with(|p| {
let mut p = p.borrow_mut();
(!p.is_empty()).then(|| p.remove(0))
})
}
/// Offers `data` as a download named after `path`'s file name.
pub fn download(path: &Path, data: &[u8]) {
let name = path.file_name().map_or_else(|| "download".to_string(), |n| n.to_string_lossy().into_owned());
if let Err(e) = try_download(&name, data) {
web_sys::console::error_2(&JsValue::from_str(&format!("could not download {name}")), &e);
}
}
fn try_download(name: &str, data: &[u8]) -> Result<(), JsValue> {
let window = web_sys::window().ok_or("no window")?;
let doc = window.document().ok_or("no document")?;
let body = doc.body().ok_or("no body")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(data));
let opts = web_sys::BlobPropertyBag::new();
opts.set_type("application/octet-stream");
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts)?;
let url = web_sys::Url::create_object_url_with_blob(&blob)?;
let a = doc.create_element("a")?.dyn_into::<web_sys::HtmlAnchorElement>()?;
a.set_href(&url);
a.set_download(name);
let _ = a.style().set_property("display", "none");
body.append_child(&a)?;
a.click();
a.remove();
// The download has its own copy long before this.
let revoke = Closure::once_into_js(move || {
let _ = web_sys::Url::revoke_object_url(&url);
});
window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 60_000)?;
Ok(())
}
// ----- leaving the page -------------------------------------------------------------------------
pub fn set_unsaved(unsaved: bool) {
UNSAVED.with(|u| u.set(unsaved));
}
/// The browser asks "Leave site?" while there are unsaved changes.
fn guard_leaving() {
let Some(window) = web_sys::window() else { return };
let on_leave = Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(|e: web_sys::BeforeUnloadEvent| {
if UNSAVED.with(Cell::get) {
e.prevent_default();
e.set_return_value("You have unsaved changes.");
}
});
if window.add_event_listener_with_callback("beforeunload", on_leave.as_ref().unchecked_ref()).is_ok() {
// Lives as long as the page.
on_leave.forget();
}
}
// ----- storage ----------------------------------------------------------------------------------
fn storage() -> Option<web_sys::Storage> {
web_sys::window()?.local_storage().ok()?
}
pub fn storage_get(key: &str) -> Option<String> {
storage()?.get_item(key).ok()?
}
pub fn storage_set(key: &str, value: &str) -> Result<(), String> {
let s = storage().ok_or("this browser keeps no storage for the site (private browsing?)")?;
s.set_item(key, value).map_err(|_| "the browser's storage for this site is full (documents with large images or sounds may not fit)".to_string())
}
fn storage_remove(key: &str) {
if let Some(s) = storage() {
let _ = s.remove_item(key);
}
}
fn storage_keys() -> Vec<String> {
let Some(s) = storage() else { return Vec::new() };
let n = s.length().unwrap_or(0).min(100_000);
(0..n).filter_map(|i| s.key(i).ok().flatten()).collect()
}
// ----- crash recovery (ADR 0015 in a browser) ---------------------------------------------------
fn doc_key(id: &str) -> String {
format!("{RECOVERY_PREFIX}{id}.doc")
}
fn meta_key(id: &str) -> String {
format!("{RECOVERY_PREFIX}{id}.meta")
}
/// This tab's autosave: the same calls as the desktop's `Autosaver`, writing to browser storage.
/// Storage is synchronous, so a copy is written when it is asked for (serializing a typical
/// document takes milliseconds; the outcome comes back on the next poll, as on the desktop).
pub struct BrowserSaver {
id: String,
next_tag: u64,
done: RefCell<Vec<Outcome>>,
}
impl BrowserSaver {
pub fn start() -> Result<BrowserSaver, String> {
storage().ok_or("this browser keeps no storage for the site (private browsing?)")?;
let millis = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_millis());
let id = format!("web-{millis:x}-{:08x}", (js_sys::Math::random() * f64::from(u32::MAX)) as u32);
hold_lock(&id);
refresh_live();
Ok(BrowserSaver { id, next_tag: 0, done: RefCell::new(Vec::new()) })
}
pub fn id(&self) -> &str {
&self.id
}
pub fn write(&mut self, doc: Document, original: Option<&Path>) -> u64 {
self.next_tag += 1;
let tag = self.next_tag;
let meta = RecoveryMeta::describe(&self.id, &doc, original);
let t = web_time::Instant::now();
let outcome = match anicraft_engine::format::to_json(&doc) {
Ok(json) => {
let serialize_ms = t.elapsed().as_secs_f64() * 1000.0;
let t = web_time::Instant::now();
// The description last: a description always has its whole document.
let meta_json = serde_json::to_string(&meta).unwrap_or_default();
match storage_set(&doc_key(&self.id), &json).and_then(|()| storage_set(&meta_key(&self.id), &meta_json)) {
Ok(()) => Outcome::Written { tag, stats: WriteStats { bytes: json.len() as u64, serialize_ms, write_ms: t.elapsed().as_secs_f64() * 1000.0 } },
Err(error) => Outcome::Failed { tag, error },
}
}
Err(e) => Outcome::Failed { tag, error: e.to_string() },
};
self.done.borrow_mut().push(outcome);
tag
}
pub fn clear(&mut self) -> u64 {
self.next_tag += 1;
discard(&self.id);
self.done.borrow_mut().push(Outcome::Cleared { tag: self.next_tag });
self.next_tag
}
pub fn poll(&self) -> Vec<Outcome> {
std::mem::take(&mut *self.done.borrow_mut())
}
pub fn finish(mut self, last: Option<(Document, Option<PathBuf>)>) -> Vec<Outcome> {
match last {
Some((doc, original)) => self.write(doc, original.as_deref()),
None => self.clear(),
};
self.poll()
}
}
/// `navigator.locks`, where the browser has Web Locks (secure pages: https and localhost).
fn locks() -> Option<JsValue> {
let nav = web_sys::window()?.navigator();
js_sys::Reflect::get(&nav, &JsValue::from_str("locks")).ok().filter(|l| l.is_object())
}
fn method(obj: &JsValue, name: &str) -> Option<js_sys::Function> {
js_sys::Reflect::get(obj, &JsValue::from_str(name)).ok()?.dyn_into::<js_sys::Function>().ok()
}
/// Holds this tab's lock until the tab goes (the callback's promise never settles).
fn hold_lock(id: &str) {
let Some(locks) = locks() else { return };
let Some(request) = method(&locks, "request") else { return };
let hold = Closure::<dyn FnMut(JsValue) -> js_sys::Promise>::new(|_| js_sys::Promise::new(&mut |_, _| {}));
if request.call2(&locks, &JsValue::from_str(&format!("{LOCK_PREFIX}{id}")), hold.as_ref()).is_ok() {
hold.forget();
}
}
/// Asks the browser which sessions' tabs are open; the answer arrives asynchronously. Without
/// Web Locks every other session counts as closed (its copy is offered; restoring is a copy).
pub fn refresh_live() {
LIVE.with(|l| *l.borrow_mut() = None);
let query = locks().and_then(|locks| method(&locks, "query").and_then(|q| q.call0(&locks).ok())).and_then(|p| p.dyn_into::<js_sys::Promise>().ok());
let Some(query) = query else {
LIVE.with(|l| *l.borrow_mut() = Some(Vec::new()));
return;
};
wasm_bindgen_futures::spawn_local(async move {
let mut live = Vec::new();
if let Ok(snapshot) = wasm_bindgen_futures::JsFuture::from(query).await
&& let Ok(held) = js_sys::Reflect::get(&snapshot, &JsValue::from_str("held"))
{
for info in js_sys::Array::from(&held).iter().take(10_000) {
if let Some(name) = js_sys::Reflect::get(&info, &JsValue::from_str("name")).ok().and_then(|n| n.as_string())
&& let Some(id) = name.strip_prefix(LOCK_PREFIX)
{
live.push(id.to_string());
}
}
}
LIVE.with(|l| *l.borrow_mut() = Some(live));
repaint();
});
}
/// Copies left by tabs that closed or crashed, newest first, not `own`; `None` until the
/// browser has said which tabs are open.
pub fn scan(own: Option<&str>) -> Option<Vec<Entry>> {
let live = LIVE.with(|l| l.borrow().clone())?;
let mut found: Vec<Entry> = storage_keys()
.iter()
.filter_map(|k| k.strip_prefix(RECOVERY_PREFIX)?.strip_suffix(".meta"))
.filter(|id| anicraft_engine::recovery::valid_id(id) && Some(*id) != own && !live.iter().any(|l| l == id))
.filter_map(|id| {
let meta = serde_json::from_str::<RecoveryMeta>(&storage_get(&meta_key(id))?).ok()?;
let bytes = storage_get(&doc_key(id))?.len() as u64;
Some(Entry { session: id.to_string(), document: PathBuf::new(), meta, bytes })
})
.collect();
found.sort_by_key(|e| std::cmp::Reverse(e.meta.saved_at));
Some(found)
}
/// The document and description of session `id`'s copy.
pub fn load(id: &str) -> Option<(String, RecoveryMeta)> {
let meta = serde_json::from_str::<RecoveryMeta>(&storage_get(&meta_key(id))?).ok()?;
Some((storage_get(&doc_key(id))?, meta))
}
/// Removes session `id`'s copy.
pub fn discard(id: &str) {
storage_remove(&meta_key(id));
storage_remove(&doc_key(id));
}