mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-10 20:41:25 +00:00
* Disk cache: record the source files each frame reads Part of #3184 (step 1): renders now report which footage files they read, each with its identity (size and modification time) as read. Nothing uses the list yet: images, cache keys and cache behaviour are unchanged. - render: `reads` module with `FileStamp`, `ReadFile`, `ReadFiles` (sorted, deduplicated, bounded; marked incomplete when it can't vouch for every file) and the thread-safe `ReadLog`. `Renderer::reads` collects a frame's files; `FootageSource::recording` lets a source note what it reads. `file_stamp` uses the same identity. - Layer cache entries keep the files their buffer was made of and report them on every hit; derived entries (styles, blend space, flattened) keep their base's. Buffers from the disk cache or the browser store don't know their files yet and mark the list incomplete. - Media pool: every file read notes its identity, taken from the file it opens. Decoded frames, opened movies, GIFs, models and EXR channels keep it with the cache entry, so a frame served from memory reports its file without touching the disk. - Viewer frame worker collects each frame's list and carries it to where the disk entry is written (step 2 stores it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Automation: confined footage passes on the files it reads Part of #3184: ConfinedFootage forwards FootageSource::recording to the source it wraps, so renders of an automation session list their files instead of coming back incomplete. The read tests also render through the viewer's CancellableFootage wrapper. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: frame entries keep their source files, comp key from memory Part of #3184 (step 2). Fixes #3175: opening a comp no longer stamps every footage file of the project before its first frame can show. - The comp's content key (`disk_cache::comp_content_key`) is taken from the project in memory alone: no footage or proxy file is stamped, no `VirtualFileId` is asked. `comp_content_key_with` is gone; `frame_key` hashes a new entry version, so entries of the earlier format are never looked up again (LRU evicts them). - Frame entries (formats 2 and 3) store the files the frame read (`EntryFiles`: size and modification time as read; size and content hash through `VirtualFileId` for files from memory; missing files), then the pixels. Formats 0 and 1 read as misses and are deleted. - Check on hit: `get_frame`/`get_frame_f16` look only at the listed files (one metadata call each) on the frame worker. A changed, back or unreadable file, or a damaged entry, is a miss: the entry is deleted and the frame rendered and stored again. - A frame whose file list is incomplete is shown but not stored. The RAM preview keeps each frame's files, so `persist_missing` writes only frames with a complete list. - Remote frame worker: `FrameServer` records each frame's reads (`take_files`); the web worker stores them with the entry and the page checks them through the file table before using it. The browser's media epoch existed only for the old key and is removed. Export does not use frame entries. - The cache indicator still only asks whether an entry exists. Tests: entry format round trip and damage, the check per file, and in the viewer: a changed file re-renders exactly its frames (and a reopen reads the rest from disk); a frame checks only its own files in a project with a large unused sequence and the key looks at no file; missing, unreadable files and damaged entries never serve a stale frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: layer entries keep their source files, no footage salt Part of #3184 (step 3 of 4). Layer buffers on disk (and in the browser's layer store) now carry the files they were made of, like frame entries since step 2, and are checked against exactly those files when used. The project-wide footage salt is gone: nothing stamps every footage file any more. - Layer entry format 4: the buffer's EntryFiles, then the pixels. A hit checks only the listed files (metadata, or the VirtualFileId hook for files from memory; Missing must still be missing); a change, a damaged entry or the old format 0 is a miss and the entry is deleted, so the re-rendered buffer replaces it. A hit reports its file list, so frames made of buffers from disk are complete and get stored again. - Buffers whose files can't all be named are not written. - Layer disk keys: layer_disk_key = hash of the layer entry version, the renderer version and the layer cache key (which names the footage items with their paths and settings, from memory). - PrefetchStore checks on use; an entry made of changed files is dropped and forgotten, so the new buffer is queued over it. FrameServer passes its virtual-file hook to its layer cache. - Removed: footage_salt(_with), file_stamp, footage_stamp, set_disk_salt, set_store_salt, Session::refresh_disk_salt, poll_disk_salt, footage_fingerprint, disk_salt, disk_salt_background, disk_salt_job, DiskSaltJob, the UI's per-frame poll, the salt in FrameServer and in the availability worker (with its cache_enabled plumbing). The disk cache is attached as soon as it is configured. - Docs: architecture.md, web.md. Tests: layer entries check their files (size, time, missing/back, folder, damaged, old format, incomplete); virtual files; prefetch store; media tests with a real pool across restarts (only the changed file is read, projects with the same item ids never share an entry, missing, unreadable and damaged never serve stale buffers); engine tests that the cache is attached at once and edits do no file work (#1926, #3106). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: no-salt worker test, sequence paths in the frame-blend key Part of #3184 (step 3 of 4). - A frame-blended footage frame's layer-cache key now hashes the sequence's file list: with no project-wide salt, two projects whose items share an id and a first frame must not share its disk entry. - Test: a frame worker syncing, patching and rendering a project with an unused 5000-frame sequence asks its file hook only about the file its buffer reads (the salt asked about every file at every sync). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: the comp key covers what its expressions can read With an expression anywhere in the project, every comp's disk key hashed every item of the project, so any edit (another comp, an unused footage item) threw away every comp's frames on disk. The key now covers what the comp can draw plus what the expressions among it can reach (Project::pixel_reach): - without expressions: the items the comp draws, without silent layers, plus the footage its precomp layers swap in (Media Replacement); - with expressions: every layer of the comps they reach, their markers, the comps and footage they name with string literals (comp("Name"), footage("Name")) together with which items have those names now, and the footage named like a reached source (its data is read by name); - the whole project when an expression computes a name, uses the object model's constructors or internals, dynamic code, computed keys or writes, or text the scanner can't read for sure (regex literals, template strings, escapes): expression_reach errs towards reaching more. Markers count only where an expression can read them (#1083). Memory only, no file is looked at. Tests: scanner and reach unit tests in the project crate; engine tests for the key (own-comp expressions keep the key through edits elsewhere, comp("Other") follows Other and not a third comp, a second comp taking the name counts, a computed name counts every item, markers read from another comp); a ui-egui test that the disk frames outside an expression layer are carried when the comp it names changes. Part of #3184. Part of #1492. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: Reload Footage drops the entries of its files, docs File > Reload Footage now deletes the frame and layer entries whose file lists name the reloaded item's files (DiskCache::drop_files), so a file replaced by one with the same size and modification time, which the check on hit can't tell apart, is read again. The index knows keys, not files: the writer thread reads the files section at the start of each frame and layer entry (not the pixels) after the writes queued before it, and deletes the entries that list one of the files. Until it is done, an entry made of one of them is a miss and frames aren't linked to new keys. The entries are gone for good, so they don't come back after a restart. Automatic reloads don't drop anything: they follow a changed stamp, which the check on hit catches. The browser needs nothing (its file identities are content hashes). Removed: disk_cache::seal, which steps 2 and 3 left without callers (the tests use seal_format). Updated the module, seal_format and forget_media docs, and docs/architecture.md / docs/web.md describe the final design: what is cached, keys from memory, file lists checked on hit, nothing scans the project, incomplete lists stay in memory, Reload Footage drops entries, edits keep the frames they can't change. Tests: render unit tests (same size and time passes the check but not the drop; other files' entries stay; an entry queued before the drop is dropped; a layer entry too; written again afterwards it is used; the drop survives a restart; a pending drop is a miss), and an engine test through file.reloadFootage. Closes #3184. Part of #1492. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: file stamps keep the whole modification time A file's modification time was nanoseconds since 1970 as u64: a time before 1970 read as "no time" (two such files of one size looked alike) and times after 2554 were truncated. It is now i128 nanoseconds, negative before the epoch; None only means the file system has no time. The content-key hash writes a presence tag and the full value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Automation: a refused footage read leaves the render's file list incomplete Footage outside the read roots shows nothing and was noted as no file at all, so a picture made without it had a complete, empty list and could be kept on disk for a later session with other roots. A refused read during `recording` now marks the list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: a buffer kept by another worker comes with its own files LayerCache::insert returns the files of the buffer it keeps, and Renderer::keep notes them in the render's log and returns them, so a render that uses another worker's buffer lists that buffer's files (a file changed between the two reads then has two identities and the list is incomplete). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: sampleImage and text fonts note the files they read EvalCtx carries the render's read log. A sampleImage render records its footage reads, keeps them with its per-thread cached buffer and notes them in the evaluating render's log on every use. Text notes the font files it is drawn with, with the identity their bytes were read with; a family that isn't installed, a fallback or missing glyph, or a font from memory leaves the list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: frame entries store the whole modification time A frame entry's file list stores a file's modification time as i128 nanoseconds since 1970 (negative before), as the file stamps now keep it; the frame entry format version goes to frame-entry-files-2 so entries in the old layout are not read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: layer entries store the whole modification time Layer entries share the frame entries' file list layout, which now stores the full i128 modification time: the layer entry format version goes to layer-entry-files-2. The module doc names the font files text is drawn with among an entry's source files, and what keeps a list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Layer cache: buffers that read other layers are keyed by the switches passed down A layer whose effect reads another layer (Gradient Wipe, Set Matte, Blend…) gets that layer drawn by its own renderer. Through a precomp layer, Switches Affect Nested Comps, the switches inherited from the precomp layers above and motion blur on change those pixels, but the key held only the layers' own switches: a buffer made with the setting on was reused (from memory or the disk cache) with it off. Such layers now derive their key with what the renderer passes down. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Layer cache: masked buffers are keyed by the mask motion blur gate A mask with Mask Motion Blur On blurs even when the layer's own switch is off, as long as the render's gate is open (Render Settings motion blur, and with Switches Affect Nested Comps the precomp layers above). The key held the layer's own motion blur state only, so a buffer blurred with the gate open was reused with it closed (and the other way round), also from the disk cache. Masked layer, input and footprint keys now tell a closed gate apart. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: cached buffers list what their expressions and substituted characters read - Buffers made under `Renderer::recorded` (layer content, a Time effect's input, an adjustment layer's footprint) evaluate their masks, shapes and effects with the context that notes into the buffer's own read log, so a file an expression reads (`sampleImage`, also at shutter times mask motion blur adds and the cache key doesn't see) is in the buffer's files. - A styled layer served from the cache lists the files of the cached body and passes too, so the buffers made of it (flattened, blending space) don't get a complete list when one of them came with an incomplete one. - A character put in by Character Offset or Character Value without a relayout notes the font it is drawn with; a fallback face (or none) leaves the list incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render: text lists the font file of a run that draws no glyph; tests clean their temp dirs An empty first paragraph draws no glyph, but in a box its face sets the first baseline that places every later line. The read list took faces only from glyphs, so it could be complete without that file. Note each style run's resolved face as well. The font-reads and confine tests use tempfile::tempdir(): a fresh directory per run, removed on panic too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: Reload Footage closes the gaps around its drop (#3184) - A reload while the disk cache is off is kept on the session (pending_disk_drops) and applied when the cache is switched on, before anything is read from it. - Each render takes the cache's drop generation before it reads (frame worker; layer cache at the miss). An entry listing a file dropped after that is refused under the queue's lock, so a render that was under way during the reload can't store pixels from before it. Such a frame is shown with an incomplete file list, so persist_missing skips it too. The per-file record is bounded (past it, everything older is refused). - An entry read while its drop was pending is a miss even when the writer ends the sweep between the read and the check (a stale hit found under load): the pending drops and the generation are taken before the entry is read. - Test: a reopened project serves its frame from disk with no source file opened or decoded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Disk cache: RAM frames keep the drop generation their render started at Reload Footage empties the RAM preview, but an idle pass of persist_missing may already hold a frame from before the reload. It took the cache's drop generation when it ran, after the drop, so the old pixels could be written back and, with the file's size and time unchanged, served again after a restart. Each RAM frame now keeps the disk cache its render started with and that cache's drop generation then. persist_missing writes a frame only to that cache, with that generation, and skips it once one of its files was dropped since; a frame rendered without that cache is not written from there. Tests use tempfile directories (the layer drop test, the frame_files folders under target/). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Doc comments for the functions this PR touches * Disk cache: cap the free-space reserve at 10 GB, skip encodes the limit refuses The reserve the cache leaves free on its disk was max(2 GB, 5% of the disk) (#2551). On a 4 TB disk with 190 GB free that is 200 GB, so a cache set to 20 GB had a limit of 0: every write was refused, the cache never held anything, and only a log warning said so. The reserve is now clamp(5% of the disk, 2 GB, 10 GB). It is there to keep the cache from filling the disk, not to keep a share of a large disk free: 10 GB leaves the system room to work on any disk, a small disk still keeps 2 GB, and a 100 GB disk keeps 5 GB as before. After Effects has only a maximum cache size and no reserve; a clamp keeps the floor for small disks, where a fixed 10 GB would take most of the space. Writes the limit refuses cost no work: DiskCache::accepts_writes (one atomic read) is checked before a frame is converted (put_disk_frame) and before frames and layers are compressed (put_frame, put_frame_f16, put_layer). The frame workers spent about 8 ms per frame and 14 ms per layer on encodes that were then refused. persist_missing returns at once at limit 0 instead of converting the RAM frames on every idle pass. Settings > Disk shows the limit in effect in MB under Maximum Disk Cache Size, with a note when free disk space lowers it (settings.disk.cacheLimit). * Disk cache: refuse writes below 64 MB of room, show this disk's reserve Review follow-ups to the reserve fix: - accepts_writes also refuses while free disk space leaves less than 64 MB of room (a limit the setting asks for is always used): a few frames would fill it, and the rest would be compressed only to be refused. - While writes are refused the idle passes ask for no repaint, so the UI keeps a frame coming every 5 s: the free space is read again and the RAM frames are written once there is room. - Settings > Disk names the space kept free on this disk (the reserve the last reading applied; the rule from MIN/MAX_DISK_RESERVE when it is unknown), and the "no room" note follows accepts_writes. - The settings.disk.cacheLimit automation label is machine-readable and the same in every language: limitMb, maxMb, reserveMb, spaceLimited, writes. - cargo fmt. * Disk cache: follow 3D model sources in the comp's reach The reach walk followed comp, footage and solid sources but not LayerSource::Model. An expression reading a model layer's source (thisComp.layer("Model").source.name) left the model item out of the comp's content key, so renaming the model kept the key and the old frames on disk were served. Every source item is followed now (LayerSource::item), which also counts the model when no expression reads it (Advanced 3D draws it). The same omission is fixed in the RAM preview's content walk (frames.rs) and in the layer key's walk of referenced layers (cache/dependencies.rs). * Disk cache: a render's drop generation travels with its reads; no disk entries for Expression Selectors Drop generation per render: the layer cache recovered a buffer's drop generation from the latest miss of its key, so a second render of the key that started after File > Reload Footage lent its generation to a render still running from before, and that render's buffer (the file as it was) was written after the sweep. Now Renderer::recorded starts each buffer's read log at the store's drop generation before anything is read (ReadLog::starting_at); ReadFiles carries the earliest generation through merges, so derived buffers (styles, the blend-space copy, the flattened layer) and frames that use a buffer from memory carry it too. LayerCache::insert keeps a buffer made of a file dropped since its reads began neither on disk nor in memory; a list that doesn't say counts as made before every drop. DiskCache::dropped_since takes the list's own generation too. missed_at keeps only the miss time. Expression Selectors: the layer key evaluates a text Expression Selector's amount for the first character only, so a per-character dependency such as textIndex == 1 ? 0 : footage("ref.png").width was not in the key, and after the footage item's width changed a reopened session reused the old layer entry. A text layer with an Expression Selector now marks its reads unkeyed (ReadFiles::is_unkeyed), which merges like the generation; such buffers stay in memory and are never written to disk. Frame entries are unaffected: the comp's frame key hashes what the expressions name. The equality and hash of ReadFiles ignore both new fields. * Disk cache: never serve a RAM layer buffer made before a drop of its files A render that passed the drop check could sit in put_layer's encode while Reload Footage cleared the layer cache and dropped the file, then publish its old pixels to memory after the purge; get, and a fresh render's insert, then served them. The disk-hit promotion went through the same insert_mem. Every way the cache hands out a RAM buffer (get, the kept-first path of insert, an existing entry in insert_mem) now checks the entry's files against the store's drops from their own generation (ReadFiles::since): an entry made before a drop of one of its files is forgotten and the lookup misses, so a fresh render's buffer replaces it. insert_mem also re-checks a buffer just before publishing it. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
348 lines
17 KiB
Rust
348 lines
17 KiB
Rust
//! The app: startup (storage, session restore, hooks), the eframe app and the page glue.
|
|
|
|
use std::cell::RefCell;
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use effectcraft_engine::Session;
|
|
|
|
use crate::startup::Startup;
|
|
use crate::{api, audio, browse, config_file, diskcache, files, frames, persist, storage, worker};
|
|
use effectcraft_ui_egui::EffectcraftApp;
|
|
use serde_json::json;
|
|
use wasm_bindgen::prelude::*;
|
|
|
|
#[wasm_bindgen(module = "/js/host.js")]
|
|
extern "C" {
|
|
#[wasm_bindgen(js_name = showDeviceLost)]
|
|
fn show_device_lost(message: &str, kept: bool);
|
|
#[wasm_bindgen(js_name = installCanvasShortcuts)]
|
|
fn install_canvas_shortcuts(canvas: &web_sys::HtmlCanvasElement);
|
|
}
|
|
|
|
/// Work for the UI thread with access to the app (posted by async tasks: picked files…).
|
|
type Action = Box<dyn FnOnce(&mut EffectcraftApp)>;
|
|
|
|
static WORKER: AtomicBool = AtomicBool::new(false);
|
|
|
|
/// Running inside a Web Worker (no page, no downloads).
|
|
pub fn is_worker() -> bool {
|
|
WORKER.load(Ordering::Relaxed)
|
|
}
|
|
|
|
pub(crate) fn set_worker() {
|
|
WORKER.store(true, Ordering::Relaxed);
|
|
}
|
|
|
|
/// `rel` resolved against the page's URL (`worker.js`, `audio-worklet.js`); `""` = the page's
|
|
/// folder.
|
|
pub fn page_url(rel: &str) -> String {
|
|
let href = web_sys::window().and_then(|w| w.location().href().ok()).unwrap_or_default();
|
|
web_sys::Url::new_with_base(if rel.is_empty() { "./" } else { rel }, &href).map(|u| u.href()).unwrap_or_else(|_| rel.to_string())
|
|
}
|
|
|
|
thread_local! {
|
|
static ACTIONS: RefCell<Vec<Action>> = const { RefCell::new(Vec::new()) };
|
|
static CTX: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
|
|
}
|
|
|
|
/// Run `f` on the UI thread at the next frame.
|
|
pub fn post(f: impl FnOnce(&mut EffectcraftApp) + 'static) {
|
|
ACTIONS.with(|a| a.borrow_mut().push(Box::new(f)));
|
|
repaint();
|
|
}
|
|
|
|
/// Ask for a UI frame.
|
|
pub fn repaint() {
|
|
CTX.with(|c| {
|
|
if let Some(c) = c.borrow().as_ref() {
|
|
c.request_repaint();
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Open a project or import media from table paths (picked or dropped files).
|
|
pub(crate) fn open_or_import(app: &mut EffectcraftApp, paths: Vec<String>) {
|
|
let (projects, media): (Vec<String>, Vec<String>) = paths.into_iter().partition(|p| p.to_ascii_lowercase().ends_with(".ecproj"));
|
|
if let Some(p) = projects.last()
|
|
&& let Err(e) = app.session.execute("file.open", json!({"path": p}))
|
|
{
|
|
app.ui.status = e.to_string();
|
|
}
|
|
if !media.is_empty() {
|
|
match app.session.execute("file.import", json!({"paths": media})) {
|
|
Ok(r) => {
|
|
if let Some(errs) = r["errors"].as_array().filter(|e| !e.is_empty()) {
|
|
app.ui.status = errs.iter().filter_map(|e| e.as_str()).collect::<Vec<_>>().join("; ");
|
|
}
|
|
}
|
|
Err(e) => app.ui.status = e.to_string(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The eframe app: the shared EffectCraft UI plus the browser host's per-frame duties.
|
|
pub struct WebApp {
|
|
pub app: EffectcraftApp,
|
|
/// Keep the session snapshot (off with `?empty`; off with an explicit `"demo"` startup until
|
|
/// the user's own work begins, see `demo_start`).
|
|
pub persist: bool,
|
|
/// Started on the demo by the config: the snapshot stays off, so the demo never replaces the
|
|
/// last visit's project, until the user opens a project from a file or edits the demo.
|
|
pub demo_start: bool,
|
|
/// The last title written to `document.title`.
|
|
pub document_title: String,
|
|
}
|
|
|
|
impl eframe::App for WebApp {
|
|
/// Take dropped files out of `raw_input` before eframe can replay them on a hidden tab, read them asynchronously
|
|
/// through `open_or_import`, then run the shared app's input hook.
|
|
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
|
// Files dropped on the page are input: read them here, where the browser's drop event is
|
|
// still the current pass's, not from a later (possibly logic-only) tick.
|
|
//
|
|
// The list is *taken* out of the raw input: a hidden tab runs `logic` and eframe appends
|
|
// the same prepared raw input back for the next pass, so leaving the files there would
|
|
// import them again on every hidden logic tick.
|
|
let dropped_files = std::mem::take(&mut raw_input.dropped_files);
|
|
let dropped: Vec<web_sys::File> = dropped_files.iter().filter_map(|f| f.web_file().cloned()).collect();
|
|
if !dropped.is_empty() {
|
|
files::read_files(dropped, |paths| post(move |app| open_or_import(app, paths)));
|
|
}
|
|
self.app.raw_input_hook(ctx, raw_input);
|
|
}
|
|
|
|
/// The browser host's logic tick: run queued UI actions, tick the shared app, poll API replies, flush Render
|
|
/// Queue downloads, persist the session snapshot when enabled, publish GPU/frame-worker/disk-cache info and close
|
|
/// the IME pass.
|
|
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
|
let actions = ACTIONS.with(|a| std::mem::take(&mut *a.borrow_mut()));
|
|
for f in actions {
|
|
f(&mut self.app);
|
|
}
|
|
self.app.tick(ctx, frame);
|
|
// eframe on the web ignores `ViewportCommand::Title`: the tab title follows the open document here.
|
|
if self.app.window_title() != self.document_title {
|
|
self.document_title = self.app.window_title().to_owned();
|
|
set_document_title(&self.document_title);
|
|
}
|
|
api::poll_replies();
|
|
// Render Queue outputs written this frame (here or by a worker) → downloads.
|
|
files::flush_downloads();
|
|
// The user's own work after a demo start is worth keeping too: turn the snapshot on.
|
|
if self.demo_start && (self.app.session.path.is_some() || self.app.session.is_dirty()) {
|
|
self.demo_start = false;
|
|
self.persist = true;
|
|
}
|
|
// What a reload comes back to.
|
|
if self.persist {
|
|
// The app's monotonic clock: `ctx.input(|i| i.time)` is stale in a logic-only tick.
|
|
persist::snapshot(&self.app.session, self.app.now(), 1.0);
|
|
}
|
|
api::set_info("gpu", json!({"compositor": self.app.gpu_adapter(), "viewerOnGpu": self.app.viewer_on_gpu()}));
|
|
api::set_info("frameWorkers", frames::stats());
|
|
// Settings ▸ Disk ▸ Disk Cache (frames in the Origin Private File System).
|
|
let d = &self.app.session.prefs.disk;
|
|
diskcache::configure(d.disk_cache_enabled, d.disk_cache_max_gb, storage::quota());
|
|
api::set_info("diskCache", diskcache::stats());
|
|
self.app.finish_ime_logic(ctx);
|
|
}
|
|
|
|
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
|
self.app.ui(ui, frame);
|
|
}
|
|
}
|
|
|
|
/// The browser tab's title.
|
|
fn set_document_title(title: &str) {
|
|
if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
|
|
doc.set_title(title);
|
|
}
|
|
}
|
|
|
|
fn query() -> Option<web_sys::UrlSearchParams> {
|
|
web_sys::window().and_then(|w| w.location().search().ok()).and_then(|s| web_sys::UrlSearchParams::new_with_str(&s).ok())
|
|
}
|
|
|
|
fn query_flag(name: &str) -> bool {
|
|
query().is_some_and(|p| p.has(name))
|
|
}
|
|
|
|
fn query_value(name: &str) -> Option<String> {
|
|
query().and_then(|p| p.get(name))
|
|
}
|
|
|
|
/// A session wired for the browser: media decoding from memory, expressions, scripting, Render
|
|
/// Queue export to downloads, settings in browser storage, renders and analyses in workers.
|
|
pub fn session() -> Session {
|
|
let pool = Arc::new(effectcraft_media::MediaPool::new());
|
|
persist::register_media(&pool);
|
|
Session {
|
|
services: Arc::new(files::WebServices),
|
|
footage: pool.clone(),
|
|
importer: Some(Arc::new(files::WebImporter { pool })),
|
|
expr: Some(Arc::new(effectcraft_expr::Expressions)),
|
|
expr_check: Some(effectcraft_expr::check_syntax),
|
|
script: Some(effectcraft_host::script::runner),
|
|
exporter: Some(Arc::new(effectcraft_host::FileExporter { sink: Some(files::export_sink()) })),
|
|
config: Some(Arc::new(persist::config())),
|
|
offload: (!query_flag("noworkers")).then(|| {
|
|
// Job workers render on a WebGPU device of their own (`?nogpuworkers`: their CPU).
|
|
worker::set_job_worker_gpu(!query_flag("nogpuworkers"));
|
|
Arc::new(worker::WorkerOffload) as Arc<dyn effectcraft_engine::offload::Offload>
|
|
}),
|
|
browser: Some(Arc::new(browse::WebBrowser)),
|
|
storage: Some(Arc::new(storage::WebStorage)),
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
/// Browser file pickers in place of the desktop's file dialogs.
|
|
fn install_hooks(app: &mut EffectcraftApp) {
|
|
app.hooks.pick_files = Some(Box::new(|exts: &[&str]| {
|
|
let accept = exts.iter().map(|e| format!(".{e}")).collect::<Vec<_>>().join(",");
|
|
if let Err(e) = files::pick(&accept, true, |paths| post(move |app| open_or_import(app, paths))) {
|
|
log::warn!("file picker: {e:?}");
|
|
}
|
|
// the import happens when the browser hands over the files
|
|
Vec::new()
|
|
}));
|
|
app.hooks.pick_open_project = Some(Box::new(|| {
|
|
if let Err(e) = files::pick(".ecproj", false, |paths| post(move |app| open_or_import(app, paths))) {
|
|
log::warn!("file picker: {e:?}");
|
|
}
|
|
None
|
|
}));
|
|
// Saving downloads the file: the chosen name is all a "save dialog" needs. A project (Save As,
|
|
// Save a Copy) asks for the name, starting from the open project's (#2788): without asking,
|
|
// Save As would replace the open project's file; Cancel cancels. A name that is already in
|
|
// browser storage asks before replacing it, as the desktop's save dialogs do.
|
|
app.hooks.pick_save = Some(Box::new(|name: &str| {
|
|
let name = if name.is_empty() { "Untitled Project.ecproj" } else { name };
|
|
if !std::path::Path::new(name).extension().is_some_and(|e| e.eq_ignore_ascii_case("ecproj") || e.eq_ignore_ascii_case("ecprojx")) {
|
|
return Some(files::path_for(name));
|
|
}
|
|
let window = web_sys::window()?;
|
|
let typed = window.prompt_with_message_and_default("Save project as:", name).ok().flatten();
|
|
let typed = crate::store::typed_save_name(name, typed)?;
|
|
let path = files::path_for(&typed);
|
|
if files::get(&path).is_some() && !window.confirm_with_message(&format!("{typed} already exists. Replace it?")).unwrap_or(false) {
|
|
return None;
|
|
}
|
|
Some(path)
|
|
}));
|
|
app.hooks.audio_device = Some(Box::new(audio::open));
|
|
app.hooks.audio_devices = Some(Box::new(|| vec!["Browser default output".into()]));
|
|
}
|
|
|
|
/// Entry point (called by the page's bootstrap script once the wasm module is instantiated).
|
|
#[wasm_bindgen]
|
|
pub async fn start(canvas_id: String) -> Result<(), JsValue> {
|
|
eframe::WebLogger::init(log::LevelFilter::Info).ok();
|
|
// Match System follows `?lang=` in the address, then the browser's languages; a language
|
|
// chosen in Settings still wins.
|
|
let navigator = web_sys::window().map(|w| w.navigator());
|
|
let browser = navigator.iter().flat_map(|n| n.languages().iter().filter_map(|v| v.as_string()).collect::<Vec<_>>());
|
|
effectcraft_ui_egui::i18n::set_system_locales(query_value("lang"), browser.collect());
|
|
let doc = web_sys::window().and_then(|w| w.document()).ok_or("no document")?;
|
|
let canvas: web_sys::HtmlCanvasElement = doc.get_element_by_id(&canvas_id).ok_or("no canvas")?.dyn_into()?;
|
|
install_canvas_shortcuts(&canvas);
|
|
let empty = query_flag("empty");
|
|
let home = query_flag("home");
|
|
// Browser storage: settings, recent projects, imported media, saved projects, auto-saves and
|
|
// the last session come back.
|
|
// Monotonic (performance.now) rather than the wall clock: a system-time jump must not turn
|
|
// the storage-load report negative or huge.
|
|
let t0 = web_time::Instant::now();
|
|
let stored = match persist::load(&query_value("storage").unwrap_or_default()).await {
|
|
Ok(n) => n,
|
|
Err(e) => {
|
|
log::warn!("browser storage unavailable: {e}");
|
|
0
|
|
}
|
|
};
|
|
api::set_info("storage", json!({"backend": persist::backend(), "entries": stored, "loadMs": t0.elapsed().as_secs_f64() * 1000.0}));
|
|
audio::install_unlock();
|
|
// `./effectcraft-config.json`: what to open on load.
|
|
// `?empty` and `?demo` decide by themselves, so they skip the request.
|
|
let startup = if empty || query_flag("demo") { Startup::default() } else { config_file::startup().await };
|
|
// An explicit `"demo"` start leaves the saved session alone until the user opens or edits something.
|
|
let keep_session = !empty && startup.keeps_session();
|
|
browse::restore();
|
|
diskcache::init();
|
|
storage::refresh();
|
|
let runner = eframe::WebRunner::new();
|
|
runner
|
|
.start(
|
|
canvas,
|
|
eframe::WebOptions::default(),
|
|
Box::new(move |cc| {
|
|
EffectcraftApp::install_ime_reset_hooks(&cc.egui_ctx);
|
|
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
|
|
// The page owns this shared presentation device; worker devices retain their
|
|
// separate owned-device handlers. No browser error-scope future is blocked on.
|
|
let gpu_failures = effectcraft_ui_egui::gpu_failure::GpuFailureBridge::new(&cc.egui_ctx);
|
|
if let Some(rs) = &cc.wgpu_render_state {
|
|
let errors = gpu_failures.clone();
|
|
rs.device.on_uncaptured_error(Arc::new(move |error| {
|
|
let message = format!("uncaptured GPU error: {error}");
|
|
if errors.report(&message, false) {
|
|
log::error!("{message}");
|
|
}
|
|
}));
|
|
// The canvas can't present any more (#225): the page says so over it and
|
|
// offers a reload, which brings the session back when browser storage keeps it.
|
|
let lost = gpu_failures.clone();
|
|
let kept = keep_session && persist::backend() != "memory";
|
|
rs.device.set_device_lost_callback(move |reason, message| {
|
|
let message = format!("GPU device lost ({reason:?}): {message}");
|
|
lost.report(&message, true);
|
|
show_device_lost(&message, kept);
|
|
});
|
|
}
|
|
let mut session = session();
|
|
session.load_settings();
|
|
// Scripts in Scripts/Startup run before a project opens.
|
|
let _ = session.execute("file.runStartupScripts", json!({}));
|
|
let recovery = session.begin_recovery();
|
|
// `?empty`: a blank project; `?demo`: the demo project; otherwise what the config's
|
|
// `startup` says (default: the last visit's project, the demo on a first visit).
|
|
let demo = query_flag("demo");
|
|
let restored = !empty && !demo && startup.restores() && persist::restore(&mut session);
|
|
if !restored && !empty && (demo || startup.demo_when_nothing_restored()) {
|
|
let _ = session.execute("file.openDemoProject", json!({}));
|
|
}
|
|
api::set_info("restored", json!(restored));
|
|
// The ScriptUI panels open on the last visit open again.
|
|
let _ = session.execute("window.restoreScriptPanels", json!({}));
|
|
let mut app = EffectcraftApp::new(session);
|
|
app.set_gpu_failure_bridge(gpu_failures);
|
|
app.ui.start_screen = home;
|
|
if let Some(r) = recovery.filter(|r| !restored && r.autosave.is_some()) {
|
|
app.offer_recovery(r);
|
|
}
|
|
install_hooks(&mut app);
|
|
// Viewer frames render in frame workers (`?frameworkers=N`, 0 or `?noworkers`:
|
|
// on the page's thread), each on its own WebGPU device where the browser has
|
|
// WebGPU in workers (`?nogpuworkers`: their CPU).
|
|
let n = if query_flag("noworkers") { 0 } else { query_value("frameworkers").and_then(|v| v.parse().ok()).unwrap_or(2usize).min(8) };
|
|
if n > 0 {
|
|
app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n, !query_flag("nogpuworkers")))));
|
|
}
|
|
app.frames.set_virtual_id(Arc::new(|path| files::STORE.file_identity(path)));
|
|
let (tx, rx) = std::sync::mpsc::channel();
|
|
api::set_sender(tx);
|
|
app = app.with_control(rx);
|
|
let backend = cc.wgpu_render_state.as_ref().map(|rs| format!("{:?}", rs.adapter.get_info().backend));
|
|
api::set_info("backend", json!(backend));
|
|
Ok(Box::new(WebApp { app, persist: keep_session, demo_start: !empty && !keep_session, document_title: String::new() }))
|
|
}),
|
|
)
|
|
.await?;
|
|
// Hide the loading message once the app runs.
|
|
if let Some(el) = doc.get_element_by_id("loading") {
|
|
el.remove();
|
|
}
|
|
Ok(())
|
|
}
|