diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.toml index c12cda0f6..ed043d564 100644 --- a/apps/solidcraft-web/Cargo.toml +++ b/apps/solidcraft-web/Cargo.toml @@ -25,6 +25,7 @@ solidcraft-engine = { workspace = true } solidcraft-ui-egui = { workspace = true } egui = { workspace = true } log = { workspace = true } +serde_json = { workspace = true } url = "2" percent-encoding = "2" @@ -33,7 +34,6 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -serde_json = { workspace = true } web-sys = { version = "0.3", features = [ "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "StorageManager", "FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemGetDirectoryOptions", "FileSystemWritableFileStream", diff --git a/apps/solidcraft-web/src/disk.rs b/apps/solidcraft-web/src/disk.rs index 7b1cee097..6d84c81a6 100644 --- a/apps/solidcraft-web/src/disk.rs +++ b/apps/solidcraft-web/src/disk.rs @@ -553,7 +553,7 @@ mod web { /// Open a design remembered from an earlier session (a recent one, after a reload): ask once /// for access to the file (call in the click), read it into the engine's files and queue it /// to open. A file that is gone is forgotten and dropped from the recent designs. - pub fn restore(files: &Rc, path: &str) { + pub fn restore(files: &Rc, path: &str, on_opened: Option>) { let Some((id, name)) = parse(path) else { return }; let (files, path, id, name) = (files.clone(), path.to_string(), id.to_string(), name.to_string()); spawn_local(async move { @@ -568,6 +568,9 @@ mod web { files.opened.borrow_mut().push(path); files.wake(); touch(&id).await; + if let Some(done) = on_opened { + done(); + } } Err(e) => { let gone = e.contains("NotFoundError") || e.contains("could not be found") || e.contains("no longer remembers"); diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rs index 1f076ec1f..bf74e7a6c 100644 --- a/apps/solidcraft-web/src/files.rs +++ b/apps/solidcraft-web/src/files.rs @@ -5,7 +5,8 @@ //! and go out as downloads (exports, and "Download design"). Where the File System Access API //! exists a design also lives on the computer's disk, saved and opened through the browser's file //! dialogs (`disk.rs`). An autosave of unsaved work is kept in OPFS and offered again after a -//! reload or a crash. +//! reload or a crash. With "keep unsaved work in this browser" on, each open design's unsaved +//! changes are kept there instead, one copy per design (`keep.rs`, #10220). use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -13,7 +14,7 @@ use std::rc::Rc; use js_sys::{Array, Function, Object, Reflect, Uint8Array}; use solidcraft_engine::io::vfs; -use crate::disk; +use crate::{disk, keep}; use wasm_bindgen::{JsCast as _, JsValue, closure::Closure}; use wasm_bindgen_futures::{JsFuture, spawn_local}; use web_sys::{ @@ -79,6 +80,16 @@ pub struct Files { pub recovery: RefCell)>>, /// The app's context, to wake it when a browser call finishes. pub ctx: RefCell>, + /// This page's id: the copies it keeps are named after it (`keep::entry_id`). + pub keep_page: RefCell, + /// Kept copies stored by this page, and the design revision each holds once its write ended. + pub kept: RefCell>>, + /// Kept copies being written or removed now (one browser call at a time per copy). + pub keeping: RefCell>, + /// When (ms) the last write of a copy failed, to wait before trying again (`keep::may_write`). + pub kept_failed: RefCell>, + /// Copies earlier pages left, newer than their design's last save: offered at start. + pub keep_offered: RefCell>, } impl Files { @@ -288,6 +299,9 @@ pub fn start(files: &Rc) { let _ = JsFuture::from(p).await; }); } + let page = keep::page_id(js_sys::Date::now(), js_sys::Math::random()); + hold_page_lock(&page); + *files.keep_page.borrow_mut() = page; let files = files.clone(); spawn_local(async move { match disk::known_ids().await { @@ -300,6 +314,7 @@ pub fn start(files: &Rc) { files.say("This page can't use the browser's file storage (it needs https or localhost): designs are kept in local storage, a few MB at most.", false); } let mut entries = Vec::new(); + let kept = kept_copies(&all); let has_recovery = all.iter().any(|(n, _, _)| n == RECOVERY); let legacy = (!has_recovery).then(|| LEGACY_RECOVERY.into_iter().find(|l| all.iter().any(|(n, _, _)| n == l))).flatten(); for (name, bytes, modified) in all { @@ -315,7 +330,7 @@ pub fn start(files: &Rc) { *files.recovery.borrow_mut() = Some((n, meta["path"].as_str().map(str::to_string))); continue; } - if name != RECOVERY { + if name != RECOVERY && keep::parse_name(&name).is_none() { entries.push(Entry { name: name.clone(), size: bytes.len() as u64, modified }); } vfs::insert(&format!("{OPFS}{name}"), bytes); @@ -326,6 +341,7 @@ pub fn start(files: &Rc) { if !vfs::exists(&format!("{OPFS}{RECOVERY}")) { *files.recovery.borrow_mut() = None; } + sort_kept(&files, kept, &live_pages().await); } Err(e) => files.say(format!("browser storage: {e}"), true), } @@ -343,7 +359,7 @@ pub fn flush(files: &Rc) { { let mut e = files.entries.borrow_mut(); e.retain(|x| x.name != name); - if name != RECOVERY && name != RECOVERY_META { + if name != RECOVERY && name != RECOVERY_META && keep::parse_name(&name).is_none() { e.push(Entry { name: name.clone(), size: bytes.len() as u64, modified: js_sys::Date::now() }); e.sort_by_key(|a| a.name.to_lowercase()); } @@ -473,7 +489,15 @@ pub fn recovery_path() -> String { /// A recovery file lives in OPFS, but its relative links belong to the original design's /// folder (which can be on disk). Resolve them before Open sees the temporary file location. pub fn prepare_recovery(original_path: Option<&str>) -> Result { - let path = recovery_path(); + prepare_copy(recovery_path(), original_path) +} + +/// The same for a kept copy (#10220). +pub fn prepare_kept(id: &str, original_path: Option<&str>) -> Result { + prepare_copy(format!("{OPFS}{}", keep::design_file(id)), original_path) +} + +fn prepare_copy(path: String, original_path: Option<&str>) -> Result { let bytes = vfs::read(&path, solidcraft_engine::io::MAX_DESIGN_BYTES).map_err(|e| e.to_string())?; let mut doc = solidcraft_engine::io::read_design(&bytes).map_err(|e| e.to_string())?; solidcraft_engine::resolve_design_links(&mut doc, original_path); @@ -646,3 +670,149 @@ pub fn take_drops(files: &Rc, raw: &mut egui::RawInput, theme: bool) { }); } } + +/// Hold this page's browser lock while it runs, so other tabs know its kept copies are in use +/// (`keep.rs`). Browsers without the Web Locks API hold none; their copies are then offered by +/// any later page. +fn hold_page_lock(page: &str) { + let Some(locks) = web_locks() else { return }; + let Ok(request) = Reflect::get(&locks, &"request".into()).and_then(|f| f.dyn_into::().map_err(JsValue::from)) else { return }; + // A promise that never settles: the lock is let go only when the page goes. + let hold = Closure:: js_sys::Promise>::new(|_lock: JsValue| js_sys::Promise::new(&mut |_, _| {})); + let name = format!("{}{page}", keep::LOCK_PREFIX); + if let Err(e) = request.call2(&locks, &name.into(), hold.as_ref().unchecked_ref()) { + log::info!("keep: no page lock: {}", err(e)); + } + // The callback lives as long as the page. + hold.forget(); +} + +fn web_locks() -> Option { + let nav = web_sys::window()?.navigator(); + Reflect::get(&nav, &"locks".into()).ok().filter(|l| l.is_object()) +} + +/// The pages still open (in this browser profile) that hold their lock. +async fn live_pages() -> Vec { + let query = async { + let locks = web_locks().ok_or("no Web Locks")?; + let f: Function = Reflect::get(&locks, &"query".into()).map_err(err)?.dyn_into().map_err(|_| "no query".to_string())?; + let p: js_sys::Promise = f.call0(&locks).map_err(err)?.dyn_into().map_err(|_| "no promise".to_string())?; + let state = JsFuture::from(p).await.map_err(err)?; + let held: Array = Reflect::get(&state, &"held".into()).map_err(err)?.dyn_into().map_err(|_| "no list".to_string())?; + Ok::<_, String>( + held.iter() + .take(10_000) + .filter_map(|l| Reflect::get(&l, &"name".into()).ok()?.as_string()) + .filter_map(|n| n.strip_prefix(keep::LOCK_PREFIX).map(str::to_string)) + .collect(), + ) + }; + query.await.unwrap_or_else(|e| { + log::info!("keep: open pages unknown ({e})"); + Vec::new() + }) +} + +/// The kept copies among the stored files: (copy, when its design's file was last written), and +/// the ids of designs stored without their metadata. +struct Found { + copies: Vec<(keep::Entry, Option)>, + orphans: Vec, +} + +fn kept_copies(all: &[(String, Vec, f64)]) -> Found { + let modified = |path: &str| path.strip_prefix(OPFS).and_then(|n| all.iter().find(|(name, _, _)| name == n)).map(|(_, _, m)| *m); + let mut copies = Vec::new(); + let mut designs = Vec::new(); + for (name, bytes, _) in all { + match keep::parse_name(name) { + Some((id, keep::Part::Meta)) => { + if let Some(e) = keep::Entry::parse(id, bytes) { + let saved = e.path.as_deref().and_then(modified); + copies.push((e, saved)); + } + } + Some((id, keep::Part::Design)) => designs.push(id.to_string()), + None => {} + } + } + // A copy is whole only with its design. + copies.retain(|(e, _)| designs.contains(&e.id)); + let orphans = designs.into_iter().filter(|id| !copies.iter().any(|(e, _)| &e.id == id)).collect(); + Found { copies, orphans } +} + +/// Offer the copies earlier pages left that hold unsaved work, and remove those their design's +/// later save made stale (and parts without the rest), leaving open pages' copies alone. +fn sort_kept(files: &Rc, found: Found, live: &[String]) { + let mut offered = Vec::new(); + let mut gone = Vec::new(); + for (e, saved) in found.copies { + match keep::fate(&e, live, saved) { + keep::Fate::Offer => offered.push(e), + keep::Fate::Drop => gone.push(e.id), + keep::Fate::Leave => {} + } + } + gone.extend(found.orphans.into_iter().filter(|id| !keep::page_of(id).is_some_and(|p| live.iter().any(|l| l == p)))); + keep::order_offered(&mut offered); + *files.keep_offered.borrow_mut() = offered; + for id in gone { + remove_kept(files, &id); + } +} + +/// The path (in the engine's files) a kept copy opens from. +pub fn kept_path(id: &str) -> String { + format!("{OPFS}{}", keep::design_file(id)) +} + +/// Write the copy of a design with unsaved changes (`bytes`, described by `entry`) that holds +/// its revision `revision`. Its metadata goes last, so a copy is never offered half written. +pub fn write_kept(files: &Rc, entry: &keep::Entry, bytes: Vec, revision: u64) { + let id = entry.id.clone(); + if !files.keeping.borrow_mut().insert(id.clone()) { + return; + } + files.kept.borrow_mut().entry(id.clone()).or_insert(None); + let meta = entry.to_json(); + let files = files.clone(); + spawn_local(async move { + let r = async { + write_file(&keep::design_file(&id), &bytes).await?; + write_file(&keep::meta_file(&id), meta.as_bytes()).await + }; + match r.await { + Ok(()) => { + files.kept.borrow_mut().insert(id.clone(), Some(revision)); + files.kept_failed.borrow_mut().remove(&id); + } + Err(e) => { + files.kept_failed.borrow_mut().insert(id.clone(), js_sys::Date::now()); + files.say(format!("keeping unsaved work in this browser: {e}"), true) + } + } + files.keeping.borrow_mut().remove(&id); + files.wake(); + }); +} + +/// Remove kept copy `id` (its design was saved, closed, discarded or restored). +pub fn remove_kept(files: &Rc, id: &str) { + let id = id.to_string(); + if !files.keeping.borrow_mut().insert(id.clone()) { + return; + } + let _ = vfs::remove(&kept_path(&id)); + files.kept_failed.borrow_mut().remove(&id); + let files = files.clone(); + spawn_local(async move { + // The metadata first: what's left without it is never offered. + let _ = remove_file(&keep::meta_file(&id)).await; + let _ = remove_file(&keep::design_file(&id)).await; + files.kept.borrow_mut().remove(&id); + files.keeping.borrow_mut().remove(&id); + files.wake(); + }); +} diff --git a/apps/solidcraft-web/src/keep.rs b/apps/solidcraft-web/src/keep.rs new file mode 100644 index 000000000..80e182c6a --- /dev/null +++ b/apps/solidcraft-web/src/keep.rs @@ -0,0 +1,360 @@ +//! Keep unsaved work in this browser (#10220): the decisions, in plain Rust (tested natively). +//! +//! With Preferences › General › "Keep unsaved work in this browser instead of asking when the tab +//! closes" on, each open design with unsaved changes has a copy in the browser's private storage: +//! `keep-.sc` (the design) and `keep-.json` (its name, its file and when it last +//! changed). The copy is written shortly after each change ([`due`]) and again when the page is +//! hidden, so it is already current when the tab closes; the page then doesn't ask through the +//! browser's "leave site?" box ([`asks_before_unload`]). A design that is saved, closed or +//! discarded has its copy removed. The next visit offers the copies newer than their design's +//! last save ([`fate`]) in SolidCraft's own window, answered with [`plan`]. +//! +//! An id is `-`: the page that wrote it (each page load has its own) and the design's +//! number in that page. A page holds a browser lock named after it while it runs, so another tab +//! never offers, or removes, the copies of a page that is still open. +#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + +use serde_json::{Value, json}; + +/// The start of every kept file's name. +pub const PREFIX: &str = "keep-"; +/// The browser lock a page holds while it runs: this, then its page id. +pub const LOCK_PREFIX: &str = "solidcraft.keep."; +/// A copy is written once the design has been still this long (ms)… +pub const QUIET_MS: f64 = 800.0; +/// …or at the latest this long after the first change it doesn't hold yet (ms). +pub const MAX_WAIT_MS: f64 = 4000.0; +/// The most copies offered at once (the rest wait for the next visit). +pub const MAX_OFFERED: usize = 32; +const MAX_ID: usize = 64; +const MAX_NAME: usize = 256; +const MAX_PATH: usize = 4096; +/// Copies' metadata is small: a damaged or hostile one is not read. +pub const MAX_META_BYTES: usize = 64 * 1024; + +/// Ids are short and safe in a file name: ASCII letters, digits and dashes, with a page part. +pub fn valid_id(id: &str) -> bool { + !id.is_empty() && id.len() <= MAX_ID && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') && page_of(id).is_some() +} + +/// The page that wrote copy `id`. +pub fn page_of(id: &str) -> Option<&str> { + id.rsplit_once('-').map(|(page, _)| page).filter(|p| !p.is_empty()) +} + +/// This page's id, from the time it started (ms since 1970) and a random number in 0..1: +/// letters and digits only. +pub fn page_id(now_ms: f64, random: f64) -> String { + let now = if now_ms.is_finite() && now_ms > 0.0 { now_ms.min(1e15) as u64 } else { 0 }; + let random = if random.is_finite() { (random.clamp(0.0, 1.0) * f64::from(0xff_ffff)) as u64 } else { 0 }; + format!("{now:x}{random:06x}") +} + +/// The copy of design `uid` (`Session::uid`) open in page `page`. +pub fn entry_id(page: &str, uid: u64) -> String { + format!("{page}-{uid}") +} + +/// The stored file names of copy `id`: its design and its metadata. +pub fn design_file(id: &str) -> String { + format!("{PREFIX}{id}.{}", solidcraft_engine::io::DESIGN_EXT) +} +pub fn meta_file(id: &str) -> String { + format!("{PREFIX}{id}.json") +} + +/// Which part of a copy a stored file is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Part { + Design, + Meta, +} + +/// A stored file's copy id and part; `None` for every other file. +pub fn parse_name(name: &str) -> Option<(&str, Part)> { + let rest = name.strip_prefix(PREFIX)?; + let (id, part) = if let Some(id) = rest.strip_suffix(".json") { + (id, Part::Meta) + } else { + (rest.strip_suffix(solidcraft_engine::io::DESIGN_EXT)?.strip_suffix('.')?, Part::Design) + }; + valid_id(id).then_some((id, part)) +} + +/// A kept copy, as its metadata describes it. +#[derive(Clone, Debug, PartialEq)] +pub struct Entry { + pub id: String, + /// The design's name. + pub name: String, + /// Its file (`None`: never saved). + pub path: Option, + /// When the design last changed (ms since 1970). + pub changed_at: f64, +} + +impl Entry { + pub fn to_json(&self) -> String { + json!({"name": self.name, "path": self.path, "changed_at": self.changed_at}).to_string() + } + + /// Read copy `id`'s metadata. Anything malformed, oversized or not finite is no copy. + pub fn parse(id: &str, bytes: &[u8]) -> Option { + if !valid_id(id) || bytes.len() > MAX_META_BYTES { + return None; + } + let v: Value = serde_json::from_slice(bytes).ok()?; + let name = v.get("name")?.as_str()?.chars().take(MAX_NAME).collect::(); + let path = match v.get("path") { + None | Some(Value::Null) => None, + Some(p) => Some(p.as_str().filter(|p| !p.is_empty() && p.len() <= MAX_PATH)?.to_string()), + }; + let changed_at = v.get("changed_at")?.as_f64().filter(|t| t.is_finite() && *t >= 0.0)?; + Some(Entry { id: id.to_string(), name, path, changed_at }) + } +} + +/// Whether a copy that last changed at `changed_at` holds work its design's file doesn't: +/// the file was last written at `saved_at` (ms since 1970; `None` or unknown: never saved, or +/// the time can't be read, so the copy is kept rather than lost). +pub fn newer_than_save(changed_at: f64, saved_at: Option) -> bool { + match saved_at { + Some(saved) if saved.is_finite() && saved > 0.0 => changed_at > saved, + _ => true, + } +} + +/// What the next visit does with a copy it finds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fate { + /// Offer it: "Restore unsaved design…?". + Offer, + /// Its design was saved after it: remove it without asking. + Drop, + /// Its page is still open (another tab): leave it alone. + Leave, +} + +/// The copy `entry`, whose design's file was last written at `saved_at`, while the pages +/// `live` are open. +pub fn fate(entry: &Entry, live: &[String], saved_at: Option) -> Fate { + if page_of(&entry.id).is_some_and(|p| live.iter().any(|l| l == p)) { + Fate::Leave + } else if newer_than_save(entry.changed_at, saved_at) { + Fate::Offer + } else { + Fate::Drop + } +} + +/// Copies to offer first: the most recently changed, at most [`MAX_OFFERED`]. +pub fn order_offered(entries: &mut Vec) { + entries.sort_by(|a, b| b.changed_at.total_cmp(&a.changed_at).then_with(|| a.id.cmp(&b.id))); + entries.truncate(MAX_OFFERED); +} + +/// Whether a design's copy is due to be written at `now`: the design last changed at +/// `last_change`, and the copy has lacked a change since `first_unwritten` (all ms). +pub fn due(now: f64, first_unwritten: f64, last_change: f64) -> bool { + now - last_change >= QUIET_MS || now - first_unwritten >= MAX_WAIT_MS +} + +/// How long after a failed write of a design's copy it isn't tried again (ms). +pub const RETRY_MS: f64 = 30_000.0; + +/// Whether a copy whose write last failed at `failed_at` (ms; `None`: it hasn't) may be written +/// at `now`: not before [`RETRY_MS`] has passed, so a full or denied store isn't hit every tick. +pub fn may_write(now: f64, failed_at: Option) -> bool { + failed_at.is_none_or(|t| !(now >= t) || now - t >= RETRY_MS) +} + +/// Whether `wanted` is the design now open, given the open design's path. +pub fn is_open(open: Option<&str>, wanted: &str) -> bool { + open == Some(wanted) +} + +/// Whether leaving the page asks through the browser's "leave site?" box: there is unsaved work, +/// and either the user still wants to be asked or it isn't all kept in the browser yet (with the +/// keep preference off it never is, so there the box always stays). +pub fn asks_before_unload(persists: bool, keep: bool, also_ask: bool, any_unsaved: bool, all_kept: bool) -> bool { + persists && any_unsaved && (also_ask || !(keep && all_kept)) +} + +/// An answer in the "Restore unsaved design?" window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Answer { + /// Open the copy, with its unsaved changes, as the design it was (saving goes to its file). + Restore, + /// Open the design's file as last saved; the copy goes. + OpenSaved, + /// The copy goes. + Discard, +} + +/// What an answer does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Plan { + /// Open the copy (and, once it is open, give it back its name and file). + pub open_copy: bool, + /// Open this saved file. + pub open_saved: Option, + /// Remove the copy. + pub drop_copy: bool, +} + +/// What `answer` does to copy `entry`; `saved_exists`: its file can still be opened. `None`: the +/// answer isn't offered for it (Open saved version of a design never saved, or gone). +pub fn plan(answer: Answer, entry: &Entry, saved_exists: bool) -> Option { + match answer { + Answer::Restore => Some(Plan { open_copy: true, open_saved: None, drop_copy: true }), + Answer::OpenSaved => { + let path = entry.path.clone().filter(|_| saved_exists)?; + Some(Plan { open_copy: false, open_saved: Some(path), drop_copy: true }) + } + Answer::Discard => Some(Plan { open_copy: false, open_saved: None, drop_copy: true }), + } +} + +/// The answers the window offers for `entry`, in order. +pub fn answers(entry: &Entry, saved_exists: bool) -> Vec { + [Answer::Restore, Answer::OpenSaved, Answer::Discard].into_iter().filter(|a| plan(*a, entry, saved_exists).is_some()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(id: &str, changed_at: f64, path: Option<&str>) -> Entry { + Entry { id: id.into(), name: "Bracket".into(), path: path.map(str::to_string), changed_at } + } + + #[test] + fn a_failed_write_waits_before_the_next_try() { + assert!(may_write(1000.0, None)); + assert!(!may_write(1000.0 + RETRY_MS - 1.0, Some(1000.0))); + assert!(may_write(1000.0 + RETRY_MS, Some(1000.0))); + // A clock that went back doesn't block for good. + assert!(may_write(10.0, Some(1000.0))); + } + + #[test] + fn a_design_counts_as_opened_only_at_its_own_path() { + assert!(is_open(Some("a.sc"), "a.sc")); + assert!(!is_open(Some("b.sc"), "a.sc")); + assert!(!is_open(None, "a.sc")); + } + + #[test] + fn copies_are_named_by_page_and_design_and_nothing_else_reads_as_one() { + let page = page_id(1_700_000_000_000.0, 0.5); + assert!(page.chars().all(|c| c.is_ascii_hexdigit())); + let id = entry_id(&page, 7); + assert!(valid_id(&id)); + assert_eq!(page_of(&id), Some(page.as_str())); + assert_eq!(parse_name(&design_file(&id)), Some((id.as_str(), Part::Design))); + assert_eq!(parse_name(&meta_file(&id)), Some((id.as_str(), Part::Meta))); + for other in ["part.sc", "recovery.sc", "recovery.json", "keep-.sc", "keep-x.sc", "keep-a/b-1.sc", "keep-a-1.step", "keep-a-1sc"] { + assert_eq!(parse_name(other), None, "{other}"); + } + // Hostile clocks still give a usable id. + for (now, random) in [(f64::NAN, f64::NAN), (f64::INFINITY, -1.0), (-5.0, 9.0)] { + assert!(valid_id(&entry_id(&page_id(now, random), 1))); + } + } + + #[test] + fn metadata_round_trips_and_hostile_metadata_is_no_copy() { + let e = entry("a1-3", 1234.0, Some("/opfs/Bracket.sc")); + assert_eq!(Entry::parse("a1-3", e.to_json().as_bytes()), Some(e.clone())); + let never_saved = entry("a1-4", 99.0, None); + assert_eq!(Entry::parse("a1-4", never_saved.to_json().as_bytes()), Some(never_saved)); + for bad in [ + "", + "[]", + r#"{"name":"x","changed_at":"soon"}"#, + r#"{"name":"x","changed_at":-1}"#, + r#"{"name":"x","changed_at":1e999}"#, + r#"{"name":"x","path":7,"changed_at":1}"#, + r#"{"name":"x","path":"","changed_at":1}"#, + r#"{"changed_at":1}"#, + ] { + assert_eq!(Entry::parse("a1-3", bad.as_bytes()), None, "{bad}"); + } + assert_eq!(Entry::parse("../x", e.to_json().as_bytes()), None); + assert_eq!(Entry::parse("a1-3", &vec![b' '; MAX_META_BYTES + 1]), None); + let long = json!({"name": "n".repeat(10_000), "changed_at": 1}).to_string(); + assert_eq!(Entry::parse("a1-3", long.as_bytes()).map(|e| e.name.len()), Some(MAX_NAME)); + } + + #[test] + fn a_copy_newer_than_the_last_save_is_offered_an_older_one_dropped_an_open_pages_left() { + let e = entry("p1-1", 2000.0, Some("/opfs/Bracket.sc")); + // Changed after the file was last written: offered. + assert_eq!(fate(&e, &[], Some(1000.0)), Fate::Offer); + // Saved since (in this tab or another): nothing to offer. + assert_eq!(fate(&e, &[], Some(2000.0)), Fate::Drop); + assert_eq!(fate(&e, &[], Some(3000.0)), Fate::Drop); + // Never saved, or the save time can't be read: kept rather than lost. + for saved in [None, Some(0.0), Some(f64::NAN), Some(f64::INFINITY), Some(-4.0)] { + assert_eq!(fate(&e, &[], saved), Fate::Offer, "{saved:?}"); + } + // Its page is still open in another tab: neither offered nor removed. + assert_eq!(fate(&e, &["p1".into()], Some(1000.0)), Fate::Leave); + assert_eq!(fate(&e, &["p1".into()], Some(3000.0)), Fate::Leave); + assert_eq!(fate(&e, &["p2".into()], Some(1000.0)), Fate::Offer); + } + + #[test] + fn the_newest_copies_are_offered_first_and_at_most_a_windowful() { + let mut list: Vec = (0..40).map(|i| entry(&format!("p-{i}"), f64::from(i), None)).collect(); + order_offered(&mut list); + assert_eq!(list.len(), MAX_OFFERED); + assert_eq!(list.first().map(|e| e.id.as_str()), Some("p-39")); + } + + #[test] + fn a_copy_is_written_once_the_design_is_still_or_after_the_longest_wait() { + // Still changing, not waited long: not yet. + assert!(!due(1000.0, 900.0, 900.0)); + // Still for QUIET_MS: due. + assert!(due(900.0 + QUIET_MS, 900.0, 900.0)); + // Changing all the time: due after MAX_WAIT_MS anyway. + assert!(!due(5000.0, 2000.0, 4900.0)); + assert!(due(2000.0 + MAX_WAIT_MS, 2000.0, 2000.0 + MAX_WAIT_MS - 1.0)); + } + + #[test] + fn the_browser_asks_before_unload_unless_told_not_to_and_every_copy_is_current() { + // Keeping off: exactly as before, unsaved work asks, whatever the second option says. + assert!(asks_before_unload(true, false, true, true, true)); + assert!(asks_before_unload(true, false, true, true, false)); + assert!(asks_before_unload(true, false, false, true, true)); + // Keeping on, asking on (the default): both, the box and the copy. + assert!(asks_before_unload(true, true, true, true, true)); + // Keeping on, asking off, every unsaved design kept: no browser box. + assert!(!asks_before_unload(true, true, false, true, true)); + // Keeping on, asking off, a copy still being written (or failed): the browser still asks. + assert!(asks_before_unload(true, true, false, true, false)); + // Nothing unsaved, or an embedded page that keeps nothing: never. + assert!(!asks_before_unload(true, true, true, false, false)); + assert!(!asks_before_unload(true, false, true, false, false)); + assert!(!asks_before_unload(false, false, true, true, false)); + } + + #[test] + fn restore_open_saved_and_discard_each_do_one_thing_and_always_remove_the_copy() { + let saved = entry("p-1", 5.0, Some("/opfs/Bracket.sc")); + assert_eq!(plan(Answer::Restore, &saved, true), Some(Plan { open_copy: true, open_saved: None, drop_copy: true })); + assert_eq!( + plan(Answer::OpenSaved, &saved, true), + Some(Plan { open_copy: false, open_saved: Some("/opfs/Bracket.sc".into()), drop_copy: true }) + ); + assert_eq!(plan(Answer::Discard, &saved, true), Some(Plan { open_copy: false, open_saved: None, drop_copy: true })); + assert_eq!(answers(&saved, true), [Answer::Restore, Answer::OpenSaved, Answer::Discard]); + // A design never saved, or whose file is gone, has no saved version to open. + let never = entry("p-2", 5.0, None); + assert_eq!(plan(Answer::OpenSaved, &never, true), None); + assert_eq!(plan(Answer::OpenSaved, &saved, false), None); + assert_eq!(answers(&never, false), [Answer::Restore, Answer::Discard]); + } +} diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index d9db4981a..966e0ac1b 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -19,6 +19,8 @@ mod easyprint; mod files; #[cfg(target_arch = "wasm32")] mod install; +#[cfg(any(target_arch = "wasm32", test))] +mod keep; #[cfg(target_arch = "wasm32")] mod linked; #[cfg(any(target_arch = "wasm32", test))] @@ -184,6 +186,7 @@ mod web { use crate::api::Api; use crate::disk::{self, SaveTarget}; use crate::files::{self, Files, Intent}; + use crate::keep; use crate::space_mouse::SpaceMouse; const CANVAS_ID: &str = "solidcraft_canvas"; @@ -243,7 +246,9 @@ mod web { } /// The browser's "leave site? changes you made may not be saved" prompt while a design has - /// unsaved changes (the page can't show its own dialog when it is being closed). + /// unsaved changes (the page can't show its own dialog when it is being closed). With "keep + /// unsaved work in this browser" on and "still ask" off, there is nothing to ask once every + /// unsaved design's copy is current (`keep::asks_before_unload`, #10220). fn ask_before_unload(window: &web_sys::Window) { let on_unload = wasm_bindgen::closure::Closure::::new(|e: web_sys::BeforeUnloadEvent| { if UNSAVED.with(std::cell::Cell::get) { @@ -256,6 +261,50 @@ mod web { on_unload.forget(); } + /// With "keep unsaved work in this browser" on, the page brings every unsaved design's copy up + /// to date when it is hidden or goes (`pagehide`, `visibilitychange`): the browser may not + /// wait for that write, so the copies are written shortly after each change as well + /// (`Shell::keep_tick`, #10220). + fn keep_when_hidden(window: &web_sys::Window, runner: &eframe::WebRunner) { + let keep_now = { + let runner = runner.clone(); + move || { + if let Some(mut shell) = runner.app_mut::() { + shell.keep_tick(None, true); + } + } + }; + let on_hide = { + let keep_now = keep_now.clone(); + wasm_bindgen::closure::Closure::::new(move |_: web_sys::Event| keep_now()) + }; + let on_visibility = wasm_bindgen::closure::Closure::::new(move |_: web_sys::Event| { + let hidden = web_sys::window() + .and_then(|w| w.document()) + .and_then(|d| js_sys::Reflect::get(&d, &"visibilityState".into()).ok()) + .and_then(|v| v.as_string()) + .is_some_and(|v| v == "hidden"); + if hidden { + keep_now(); + } + }); + let _ = window.add_event_listener_with_callback("pagehide", on_hide.as_ref().unchecked_ref()); + if let Some(document) = window.document() { + let _ = document.add_event_listener_with_callback("visibilitychange", on_visibility.as_ref().unchecked_ref()); + } + // The listeners live as long as the page. + on_hide.forget(); + on_visibility.forget(); + } + + /// One open design followed for its kept copy: its revision, when that last changed, and since + /// when its copy has lacked a change (`None`: current, or being written). + struct Track { + revision: u64, + last_change: f64, + first_unwritten: Option, + } + /// eframe cancels the browser's action for every Tab it gets, so the browser couldn't switch /// tabs while the app has the keyboard. Its tab-switching keys stop here, on the way down to /// the canvas, before eframe sees them; the browser then acts on them as usual. @@ -328,6 +377,10 @@ mod web { /// The settings this tab wrote or loaded last, and those another tab wrote since (#8644). prefs_writer: crate::PrefsWriter, other_tab_prefs: PrefsInbox, + /// The open designs followed for their kept copy, by `Session::uid` (#10220). + keep_track: std::collections::HashMap, + /// Every unsaved design's kept copy is current (and the preference is on). + all_kept: bool, } impl Shell { @@ -442,8 +495,14 @@ mod web { self.sync_recents(); } let now = ctx.input(|i| i.time); + // With "keep unsaved work in this browser" on, each design's own copy takes over from + // the single autosave (#10220). + if self.app.preferences.keep_unsaved_in_browser && self.autosaved.is_some() { + files::autosave(&self.files, None); + self.autosaved = None; + } // Unsaved work is kept (at most every AUTOSAVE_S); saved work needs no autosave. - if self.files.ready.get() && self.files.recovery.borrow().is_none() { + if self.files.ready.get() && self.files.recovery.borrow().is_none() && !self.app.preferences.keep_unsaved_in_browser { let s = &self.app.session; let changed = s.is_dirty() && self.autosaved != Some(s.revision); let wait = AUTOSAVE_S - (now - self.autosaved_at); @@ -462,6 +521,175 @@ mod web { if !self.files.ready.get() || !self.files.incoming.borrow().is_empty() { ctx.request_repaint_after(std::time::Duration::from_millis(100)); } + self.all_kept = self.keep_tick(Some(ctx), false); + } + + /// Keep each open design's unsaved changes in the browser, when the preference asks for + /// it: a design's copy is written once it has been still a moment (`keep::due`), or at + /// once with `now` (the page is being hidden); a copy whose design is saved or closed, or + /// with the preference off, goes. Answers whether every unsaved design's copy is current. + fn keep_tick(&mut self, ctx: Option<&egui::Context>, now: bool) -> bool { + if !self.launch.persists() || !self.files.ready.get() { + return false; + } + let Shell { app, files, keep_track, .. } = self; + let on = app.preferences.keep_unsaved_in_browser; + let time = js_sys::Date::now(); + let page = files.keep_page.borrow().clone(); + let mut wanted = std::collections::HashSet::new(); + let mut all_kept = true; + let mut wake: Option = None; + let mut error = None; + let mut soon = |ms: f64| wake = Some(wake.map_or(ms, |w: f64| w.min(ms))); + if on { + for s in solidcraft_ui_egui::documents::open_sessions(app).into_iter().filter(|s| s.is_dirty()) { + let id = keep::entry_id(&page, s.uid); + wanted.insert(s.uid); + let t = keep_track.entry(s.uid).or_insert(Track { revision: s.revision, last_change: time, first_unwritten: None }); + if t.revision != s.revision { + t.revision = s.revision; + t.last_change = time; + } + if files.kept.borrow().get(&id).copied().flatten() == Some(s.revision) { + t.first_unwritten = None; + continue; + } + all_kept = false; + if files.keeping.borrow().contains(&id) { + soon(100.0); + continue; + } + let first = *t.first_unwritten.get_or_insert(time); + let failed = files.kept_failed.borrow().get(&id).copied(); + if !keep::may_write(time, failed) { + // The last write failed: try again after a while. + soon(keep::RETRY_MS); + continue; + } + if now || keep::due(time, first, t.last_change) { + match solidcraft_engine::io::write_design_container(&s.design()) { + Ok(bytes) => { + let entry = keep::Entry { id, name: s.doc.name.clone(), path: s.path.clone(), changed_at: t.last_change }; + files::write_kept(files, &entry, bytes, s.revision); + t.first_unwritten = None; + } + Err(e) => { + files.kept_failed.borrow_mut().insert(id, time); + error = Some(format!("keeping unsaved work in this browser: {e}")); + } + } + soon(100.0); + } else { + soon((keep::QUIET_MS - (time - t.last_change)).min(keep::MAX_WAIT_MS - (time - first)).max(16.0)); + } + } + } + // This page's copies no design needs any more: saved, closed, or the preference off. + let stale: Vec = files + .kept + .borrow() + .keys() + .filter(|id| keep::page_of(id) == Some(page.as_str())) + .filter(|id| !wanted.iter().any(|uid| keep::entry_id(&page, *uid) == **id)) + .cloned() + .collect(); + for id in stale { + files::remove_kept(files, &id); + soon(100.0); + } + keep_track.retain(|uid, _| wanted.contains(uid)); + if let Some(e) = error { + app.set_status(e, true); + } + if let (Some(ctx), Some(ms)) = (ctx, wake) { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(ms / 1000.0)); + } + on && all_kept + } + + /// Offer the copies an earlier visit kept (#10220): "Restore unsaved design: , + /// changed