diff --git a/Cargo.lock b/Cargo.lock index 9b228e5..0075acd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -778,6 +778,7 @@ version = "2.1.1" dependencies = [ "encoding_rs", "pgn-reader", + "serde", "shakmaty", "thiserror 2.0.21", ] diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index 962a6d7..ae025c9 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -65,6 +65,8 @@ tar = "0.4" # The web version: the page, its files and storage (apps/web starts it). [target.'cfg(target_family = "wasm")'.dependencies] +# The reader worker gives the page a database's index (platform::web::import). +chess-core = { workspace = true, features = ["serde"] } getrandom = { version = "0.3", features = ["wasm_js"] } # The browser's languages for the first start. sys-locale = { version = "0.3", features = ["js"] } @@ -82,7 +84,7 @@ web-sys = { version = "0.3", features = [ "HtmlMediaElement", "HtmlCanvasElement", "console", "CacheStorage", "Cache", "Request", "Response", "ResponseInit", "Headers", "ReadableStream", "ReadableStreamDefaultReader", "StorageManager", "StorageEstimate", "History", - "BeforeUnloadEvent", + "BeforeUnloadEvent", "WorkerOptions", "WorkerType", ] } [build-dependencies] diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index bfbe486..5417b03 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -32,6 +32,9 @@ enum Async { EngineChecked(Result<(PathBuf, String), String>), /// The folder for new databases (`None`: the dialog was cancelled). FolderPicked(Option), + /// A remembered file the browser let the page read again. + #[cfg(web)] + ReadAllowed(PathBuf), } /// A passing message at the bottom; `undo`: with the button that puts a deleted game back. @@ -2450,6 +2453,7 @@ impl App { if let Some(old) = self.choosing_again.take() { self.settings.databases.retain(|d| *d != old); self.library.forget(&old); + crate::platform::files::forget(&old); } for p in paths.iter().rev() { self.settings.touch_database(p); @@ -2460,6 +2464,8 @@ impl App { self.settings_dirty = true; } Async::SavePicked(path) => self.save_game(ctx, path), + #[cfg(web)] + Async::ReadAllowed(path) => self.library.reload(&path, ctx), Async::SaveCancelled => { self.close_after_save = None; self.restart_to = None; @@ -2811,18 +2817,23 @@ impl App { }; let mut open = false; let mut delete = false; - ui.horizontal(|ui| { - ui.label( - RichText::new(trf( - "There is an unsaved game: {title}, {n} moves.", - &[("title", &d.title), ("n", &d.moves)], - )) - .color(ui.visuals().warn_fg_color), - ); - open = ui.button(tr("Open")).clicked(); - delete = ui.button(tr("Delete")).clicked(); - }); - ui.separator(); + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(8, 6)) + .fill(ui.visuals().faint_bg_color) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(trf( + "There is an unsaved game: {title}, moves: {n}.", + &[("title", &d.title), ("n", &d.moves)], + )) + .color(ui.visuals().warn_fg_color), + ); + open = ui.button(tr("Open")).clicked(); + delete = ui.button(tr("Delete")).clicked(); + }); + }); if open { self.draft_offer = None; self.open_pgn_text(ctx, d.pgn, false); @@ -3573,6 +3584,7 @@ impl eframe::App for App { LibraryAction::RemoveDatabase(p) => { self.settings.databases.retain(|d| *d != p); self.library.forget(&p); + crate::platform::files::forget(&p); self.settings_dirty = true; // The file stays where it is; said so, with the place. self.toast = Some(Toast { @@ -3584,6 +3596,16 @@ impl eframe::App for App { undo: false, }); } + #[cfg(web)] + LibraryAction::AllowReading(p) => { + let (tx, wake) = (self.tx.clone(), ctx.clone()); + crate::platform::files::allow_reading(&p.clone(), move |back| { + if back { + let _ = tx.send(Async::ReadAllowed(p)); + } + wake.request_repaint(); + }); + } LibraryAction::ChooseAgain(p) => { self.choosing_again = Some(p); self.pick_databases(&ctx); diff --git a/apps/desktop/src/db_counts.rs b/apps/desktop/src/db_counts.rs index 426c974..fe9ee57 100644 --- a/apps/desktop/src/db_counts.rs +++ b/apps/desktop/src/db_counts.rs @@ -1,15 +1,14 @@ //! How many games each database on the shelf holds before it is opened: «not loaded» -//! on a card told the user nothing. A thread of its own counts the databases one after -//! another (reading a large one takes seconds; the screen never waits) and remembers the -//! counts with the file's size and time, so the next start shows them at once. A card -//! whose database is not counted yet says nothing. +//! on a card told the user nothing. The databases are counted one after another away +//! from the screen (reading a large one takes seconds; the screen never waits): on a +//! thread of its own, in a browser by the page's reader (`platform::web::import`). The +//! counts are remembered with the file's size and time, so the next start shows them +//! at once. A card whose database is not counted yet says nothing. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::atomic::AtomicBool; -use std::sync::mpsc::{Sender, channel}; +use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; -use std::time::UNIX_EPOCH; use chess_import::Database; use serde::{Deserialize, Serialize}; @@ -52,13 +51,145 @@ enum Job { Known(PathBuf, Count), } -#[derive(Default)] -struct Shared { - known: HashMap, +/// A file to read and count: its path and its size and time now. +struct ToCount(PathBuf, (u64, u64)); + +/// The counts known and where they are kept. +#[derive(Clone)] +struct Counter { + known: Arc>>, + /// `None`: for this run only. + file: Option, + ctx: egui::Context, +} + +impl Counter { + /// What the job leaves to do: a file to read, or nothing (its count is known now). + fn take(&self, job: Job) -> Option { + let (path, known) = match job { + Job::Count(p) => (p, None), + Job::Known(p, c) => (p, Some(c)), + }; + let stamp = stamp(&path)?; + let fresh = self.known.lock().ok().and_then(|k| { + k.get(&path) + .filter(|e| (e.size, e.modified) == stamp) + .map(|e| e.count) + }); + match known { + Some(c) if fresh == Some(c) => None, + Some(c) => { + self.record(path, stamp, c); + None + } + None if fresh.is_some() => None, + None => Some(ToCount(path, stamp)), + } + } + + fn record(&self, path: PathBuf, (size, modified): (u64, u64), count: Count) { + let json = match self.known.lock() { + Ok(mut k) => { + k.insert( + path, + Entry { + size, + modified, + count, + }, + ); + serde_json::to_vec(&*k).ok() + } + Err(_) => return, + }; + if let (Some(f), Some(json)) = (&self.file, json) { + let _ = crate::platform::fs::write_atomic(f, &json); + } + self.ctx.request_repaint(); + } + + /// Counts the files of the jobs, one after another, on a thread of its own. + #[cfg(not(web))] + fn start(self, jobs: Receiver) -> bool { + let spawned = std::thread::Builder::new() + .name("db-counts".into()) + .spawn(move || { + let never = std::sync::atomic::AtomicBool::new(false); + for job in jobs { + let Some(ToCount(path, stamp)) = self.take(job) else { + continue; + }; + // The card says why it cannot be read when the database is opened. + if let Ok(o) = chess_import::open(&path, &mut |_| {}, &never) { + self.record(path, stamp, Count::of(&o.db)); + } + } + }); + spawned.is_ok() + } + + /// Counts the files of the jobs, one after another, in the page's reader: the next + /// once the last is answered ([`Counts`] calls [`Counter::next`] after each job). + #[cfg(web)] + fn start(self, jobs: Receiver) -> bool { + WEB.with_borrow_mut(|w| { + *w = Some(Web { + counter: self, + jobs, + busy: false, + }) + }); + true + } + + #[cfg(web)] + fn next() { + let read = WEB.with_borrow_mut(|w| { + let w = w.as_mut()?; + if w.busy { + return None; + } + while let Ok(job) = w.jobs.try_recv() { + if let Some(to_count) = w.counter.take(job) { + w.busy = true; + return Some((w.counter.clone(), to_count)); + } + } + None + }); + let Some((counter, ToCount(path, stamp))) = read else { + return; + }; + crate::platform::web::import::count(&path.clone(), move |games| { + if let Some(games) = games { + let locked = false; + counter.record(path, stamp, Count { games, locked }); + } + WEB.with_borrow_mut(|w| { + if let Some(w) = w.as_mut() { + w.busy = false; + } + }); + Counter::next(); + }); + } +} + +/// The counting of the page: the jobs not taken yet, and whether a file is being read. +#[cfg(web)] +struct Web { + counter: Counter, + jobs: Receiver, + busy: bool, +} + +#[cfg(web)] +thread_local! { + static WEB: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } pub struct Counts { - shared: Arc>, + known: Arc>>, asked: HashSet, jobs: Option>, } @@ -73,100 +204,51 @@ impl Counts { fn kept_in(file: Option, ctx: &egui::Context) -> Self { let known: HashMap = file .as_ref() - .and_then(|f| std::fs::read(f).ok()) + .and_then(|f| crate::platform::fs::read(f).ok()) .and_then(|b| serde_json::from_slice(&b).ok()) .unwrap_or_default(); - let shared = Arc::new(Mutex::new(Shared { known })); + let known = Arc::new(Mutex::new(known)); let (tx, rx) = channel::(); - let (worker, ctx) = (shared.clone(), ctx.clone()); - let spawned = std::thread::Builder::new() - .name("db-counts".into()) - .spawn(move || { - let never = AtomicBool::new(false); - for job in rx { - let (path, known) = match job { - Job::Count(p) => (p, None), - Job::Known(p, c) => (p, Some(c)), - }; - let Some((size, modified)) = stamp(&path) else { - continue; - }; - let fresh = worker.lock().ok().and_then(|s| { - s.known - .get(&path) - .filter(|e| e.size == size && e.modified == modified) - .map(|e| e.count) - }); - let count = match known { - Some(c) if fresh == Some(c) => continue, - Some(c) => c, - None if fresh.is_some() => continue, - None => match chess_import::open(&path, &mut |_| {}, &never) { - Ok(o) => Count::of(&o.db), - // The card says why when the database is opened. - Err(_) => continue, - }, - }; - let json = match worker.lock() { - Ok(mut s) => { - s.known.insert( - path, - Entry { - size, - modified, - count, - }, - ); - serde_json::to_vec(&s.known).ok() - } - Err(_) => return, - }; - if let (Some(f), Some(json)) = (&file, json) { - if let Some(dir) = f.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = crate::settings::write_atomic(f, &json); - } - ctx.request_repaint(); - } - }); + let counter = Counter { + known: known.clone(), + file, + ctx: ctx.clone(), + }; Self { - shared, + known, asked: HashSet::new(), - jobs: spawned.ok().map(|_| tx), + jobs: counter.start(rx).then_some(tx), + } + } + + fn send(&self, job: Job) { + if let Some(jobs) = &self.jobs { + let _ = jobs.send(job); + #[cfg(web)] + Counter::next(); } } /// The games of a database not opened yet (`None`: not counted yet); it is counted /// from now on. pub fn get(&mut self, path: &Path) -> Option { - if self.asked.insert(path.to_owned()) - && let Some(jobs) = &self.jobs - { - let _ = jobs.send(Job::Count(path.to_owned())); + if self.asked.insert(path.to_owned()) { + self.send(Job::Count(path.to_owned())); } - self.shared.lock().ok()?.known.get(path).map(|e| e.count) + self.known.lock().ok()?.get(path).map(|e| e.count) } /// A database was opened: its count is remembered for the next start. pub fn opened(&mut self, path: &Path, db: &Database) { self.asked.insert(path.to_owned()); - if let Some(jobs) = &self.jobs { - let _ = jobs.send(Job::Known(path.to_owned(), Count::of(db))); - } + self.send(Job::Known(path.to_owned(), Count::of(db))); } } /// The file's size and time (seconds since the epoch); a changed file is counted again. fn stamp(path: &Path) -> Option<(u64, u64)> { - let m = std::fs::metadata(path).ok()?; - let modified = m - .modified() - .ok()? - .duration_since(UNIX_EPOCH) - .ok()? - .as_secs(); - Some((m.len(), modified)) + let m = crate::platform::fs::meta(path).ok()?; + Some((m.len, m.modified_ms / 1000)) } #[cfg(test)] @@ -202,9 +284,8 @@ mod tests { assert!(wait(&mut counts, &pgn, 2)); // An opened database tells its count; a changed file is counted anew. std::fs::write(&pgn, "[White \"A\"]\n\n1. e4 *\n").unwrap(); - let db = chess_import::open(&pgn, &mut |_| {}, &AtomicBool::new(false)) - .unwrap() - .db; + let never = std::sync::atomic::AtomicBool::new(false); + let db = chess_import::open(&pgn, &mut |_| {}, &never).unwrap().db; counts.opened(&pgn, &db); assert!(wait(&mut counts, &pgn, 1)); assert!(!counts.get(&pgn).unwrap().locked); diff --git a/apps/desktop/src/engine_download.rs b/apps/desktop/src/engine_download.rs index d892832..45dc123 100644 --- a/apps/desktop/src/engine_download.rs +++ b/apps/desktop/src/engine_download.rs @@ -533,7 +533,10 @@ mod tests { .output() .expect("runs"); assert!(String::from_utf8_lossy(&out.stdout).contains("Stockfish")); - assert_eq!(installed(), Some(exe)); + assert_eq!( + installed(), + Some(crate::engines::EngineLocation::Program(exe)) + ); } #[test] diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 291d8bf..e739298 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -218,15 +218,37 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String { const ROWS: &[[&str; 9]] = &[ // --- the web version --- [ - "There is an unsaved game: {title}, {n} moves.", - "Есть несохранённая партия: {title}, {n} ходов.", - "Il y a une partie non enregistrée : {title}, {n} coups.", - "Es gibt eine nicht gespeicherte Partie: {title}, {n} Züge.", - "Hay una partida sin guardar: {title}, {n} jugadas.", - "C'è una partita non salvata: {title}, {n} mosse.", - "Há uma partida não salva: {title}, {n} lances.", - "Saqlanmagan partiya bor: {title}, {n} yurish.", - "Сақталмаған партия бар: {title}, {n} жүріс.", + "🔒 Allow reading", + "🔒 Разрешить чтение", + "🔒 Autoriser la lecture", + "🔒 Lesen erlauben", + "🔒 Permitir lectura", + "🔒 Consenti la lettura", + "🔒 Permitir leitura", + "🔒 O‘qishga ruxsat berish", + "🔒 Оқуға рұқсат беру", + ], + [ + "The browser remembers this file and asks before the page reads it again.", + "Браузер помнит этот файл и спрашивает, прежде чем страница прочитает его снова.", + "Le navigateur se souvient de ce fichier et demande avant que la page le relise.", + "Der Browser merkt sich diese Datei und fragt, bevor die Seite sie erneut liest.", + "El navegador recuerda este archivo y pregunta antes de que la página vuelva a leerlo.", + "Il browser ricorda questo file e chiede prima che la pagina lo rilegga.", + "O navegador lembra este arquivo e pergunta antes que a página o leia novamente.", + "Brauzer bu faylni eslab qoladi va sahifa uni qayta o‘qishidan oldin so‘raydi.", + "Браузер бұл файлды есте сақтайды және бет оны қайта оқымас бұрын сұрайды.", + ], + [ + "There is an unsaved game: {title}, moves: {n}.", + "Есть несохранённая партия: {title}, ходов: {n}.", + "Il y a une partie non enregistrée : {title}, coups : {n}.", + "Es gibt eine nicht gespeicherte Partie: {title}, Züge: {n}.", + "Hay una partida sin guardar: {title}, jugadas: {n}.", + "C'è una partita non salvata: {title}, mosse: {n}.", + "Há uma partida não salva: {title}, lances: {n}.", + "Saqlanmagan partiya bor: {title}, yurishlar: {n}.", + "Сақталмаған партия бар: {title}, жүрістер: {n}.", ], [ "📋 Keep a copy in the browser", diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs index f01e35f..d7cae22 100644 --- a/apps/desktop/src/lib.rs +++ b/apps/desktop/src/lib.rs @@ -71,6 +71,7 @@ pub async fn start_web( lang: Option, ) -> Result<(), wasm_bindgen::JsValue> { platform::web::vfs::load().await; + platform::web::remembered::restore().await; platform::web::engine::probe().await; platform::web::storage::refresh(|| {}); let mut settings = settings::Settings::load(); @@ -93,6 +94,14 @@ pub async fn start_web( .await } +/// The page's reader (`import-worker.js`, a worker with an instance of its own): reads +/// the file `name` and answers with its text and index, or only how many games it holds +/// (`count`; `platform::web::import`). +#[cfg(web)] +pub fn read_database(name: &str, bytes: Vec, count: bool) -> wasm_bindgen::JsValue { + platform::web::import::answer(name, bytes, count) +} + /// The desktop program: `chesspenguin [--bench [report.txt]]`. #[cfg(not(web))] pub fn run_native() -> eframe::Result { diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 0b4a126..abe2f08 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -60,6 +60,9 @@ pub enum LibraryAction { /// A file the browser held for the last visit only: choose it again, the new one /// taking its place on the shelf. ChooseAgain(PathBuf), + /// Let the page read the remembered file again (the browser asks the user). + #[cfg(web)] + AllowReading(PathBuf), /// Keep a copy of a file in the browser (it opens then without choosing it). KeepCopy(PathBuf), OpenSettings, @@ -267,33 +270,29 @@ impl Library { })); let cancel = Arc::new(AtomicBool::new(false)); let (tx, rx) = channel(); - let (p, c, path_owned, ctx) = ( - progress.clone(), + let (p, ctx, wake) = (progress.clone(), ctx.clone(), ctx.clone()); + let spawned = crate::platform::open_database( + path, + move |sp| { + if let Ok(mut g) = p.lock() { + *g = sp; + } + wake.request_repaint(); + }, cancel.clone(), - path.to_path_buf(), - ctx.clone(), + move |res| { + // The filters' index of a PGN is built here, not on the screen's thread + // (a large download takes a second, §9.7; in a browser, which reads + // smaller files, it is the page's thread). + if let Ok(opened) = &res + && let Database::Pgn(pgn) = &opened.db + { + pgn.catalog(); + } + let _ = tx.send(res); + ctx.request_repaint(); + }, ); - let spawned = crate::platform::spawn("db-open", move || { - let res = crate::platform::open_database( - &path_owned, - &mut |sp| { - if let Ok(mut g) = p.lock() { - *g = sp; - } - ctx.request_repaint(); - }, - &c, - ); - // The filters' index of a PGN is built here, not on the screen's thread - // (a large download takes a second, §9.7). - if let Ok(opened) = &res - && let Database::Pgn(pgn) = &opened.db - { - pgn.catalog(); - } - let _ = tx.send(res); - ctx.request_repaint(); - }); let slot = match spawned { Ok(_) => Slot::Loading { progress, @@ -1100,6 +1099,9 @@ impl Library { }); trf("loading… {n}", &[("n", &p.games)]) } + Some(Slot::Failed(_)) | None if crate::platform::files::waiting_to_read(path) => { + tr("🔒 Allow reading").into() + } Some(Slot::Failed(_)) | None if crate::platform::files::session_only(path) && !self.files.exists(path) => { @@ -1275,6 +1277,27 @@ impl Library { }); return; } + #[cfg(web)] + Some(Slot::Failed(_)) if crate::platform::files::waiting_to_read(&path) => { + // Chrome, Edge: the file is remembered; the browser asks before the + // page reads it again. + ui.vertical_centered(|ui| { + ui.add_space(40.0); + ui.label(tr( + "The browser remembers this file and asks before the page reads it again.", + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("🔒 Allow reading")).clicked() { + actions.push(LibraryAction::AllowReading(path.clone())); + } + if ui.button(tr("Remove from list")).clicked() { + actions.push(LibraryAction::RemoveDatabase(path.clone())); + } + }); + }); + return; + } Some(Slot::Failed(_)) if crate::platform::files::session_only(&path) && !self.files.exists(&path) => { diff --git a/apps/desktop/src/platform/files.rs b/apps/desktop/src/platform/files.rs index 6acc603..57e1194 100644 --- a/apps/desktop/src/platform/files.rs +++ b/apps/desktop/src/platform/files.rs @@ -1,7 +1,8 @@ //! The files the user opens and saves: the system's dialogs on a computer; in a //! browser its file chooser, files dropped on the page, and downloads. A file the user //! gives the page is only read (decisions «Веб-версия»): it gets a path of the page's -//! file tree for the session and is opened by that path like a file on a disk. +//! file tree for the session and is opened by that path like a file on a disk. Chrome +//! and Edge remember a chosen file for the next visit ([`super::web::remembered`]). use std::path::PathBuf; @@ -97,16 +98,48 @@ pub fn pick_databases(then: impl FnOnce(Picked) + Send + 'static) { } #[cfg(web)] { - let accept = DATABASES + let extensions: Vec = DATABASES .iter() .step_by(2) .map(|e| format!(".{e}")) - .collect::>() - .join(","); - super::web::page::pick_files(&accept, move |files| then(opened(files))); + .collect(); + if super::web::remembered::supported() { + super::web::remembered::pick(&extensions, move |paths, too_big| { + then(Picked { paths, too_big }) + }); + } else { + super::web::page::pick_files(&extensions.join(","), move |files| then(opened(files))); + } } } +/// The browser remembers the file `path` of an earlier visit and asks the user before +/// the page reads it again ([`allow_reading`]). Never on a computer. +pub fn waiting_to_read(path: &std::path::Path) -> bool { + #[cfg(web)] + return super::web::remembered::waiting(path); + #[cfg(not(web))] + { + let _ = path; + false + } +} + +/// Asks the browser to let the page read the remembered file `path` again (soon after +/// the user's click); `then`: whether it is back. +#[cfg(web)] +pub fn allow_reading(path: &std::path::Path, then: impl FnOnce(bool) + 'static) { + super::web::remembered::allow(path, then); +} + +/// The file `path` left the library: a browser forgets it too. +pub fn forget(path: &std::path::Path) { + #[cfg(web)] + super::web::remembered::forget(path); + #[cfg(not(web))] + let _ = path; +} + /// The files dropped on the window in this frame, as databases to open: `then` gets /// their paths once read (in a browser they are kept for the session like chosen /// ones). The desktop program does not take dropped files: nothing comes there. diff --git a/apps/desktop/src/platform/mod.rs b/apps/desktop/src/platform/mod.rs index cd6c144..18e4aeb 100644 --- a/apps/desktop/src/platform/mod.rs +++ b/apps/desktop/src/platform/mod.rs @@ -141,12 +141,15 @@ pub fn log(line: &str) { log::info!("{line}"); } -/// Opens a database the library shows: its file on the disk, or in a browser the file -/// the user gave the page (or a sample built in). +/// Reads a database the library shows away from the screen's thread: its file on the +/// disk on a thread of its own (`progress` follows the reading), or in a browser the +/// file the user gave the page (or a sample built in) in the page's reader, a worker +/// (no progress). `done` gets the database: on that thread, or on the page's. pub fn open_database( path: &std::path::Path, - progress: &mut dyn FnMut(chess_core::ScanProgress), - cancel: &std::sync::atomic::AtomicBool, -) -> Result { - imp::open_database(path, progress, cancel) + progress: impl FnMut(chess_core::ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + imp::open_database(path, progress, cancel, done) } diff --git a/apps/desktop/src/platform/native.rs b/apps/desktop/src/platform/native.rs index 49ab101..b416015 100644 --- a/apps/desktop/src/platform/native.rs +++ b/apps/desktop/src/platform/native.rs @@ -35,8 +35,12 @@ pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result pub fn open_database( path: &Path, - progress: &mut dyn FnMut(ScanProgress), - cancel: &AtomicBool, -) -> Result { - chess_import::open(path, progress, cancel) + mut progress: impl FnMut(ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + let path = path.to_owned(); + spawn("db-open", move || { + done(chess_import::open(&path, &mut progress, &cancel)); + }) } diff --git a/apps/desktop/src/platform/web/idb.rs b/apps/desktop/src/platform/web/idb.rs index 76e4d78..3641f1c 100644 --- a/apps/desktop/src/platform/web/idb.rs +++ b/apps/desktop/src/platform/web/idb.rs @@ -1,12 +1,16 @@ -//! The program's data in the browser's storage: one IndexedDB database, one store of -//! files by path. Read whole at the start (settings and marks are small); every write -//! goes there behind the interface, in the order made. +//! The program's data in the browser's storage: one IndexedDB database, a store of +//! files by path, read whole at the start (settings and marks are small), every write +//! going there behind the interface, in the order made; and a store of the user's files +//! a Chromium browser remembers (their handles, by the page's path: [`super::remembered`]). use wasm_bindgen::JsCast; use wasm_bindgen::prelude::*; const DB: &str = "chesspenguin"; const STORE: &str = "files"; +const HANDLES: &str = "handles"; +/// 2: the store of handles. +const VERSION: u32 = 2; /// The request's outcome once it is done. async fn done(request: &web_sys::IdbRequest) -> Result { @@ -33,16 +37,19 @@ async fn open() -> Result { .ok_or("no window")? .indexed_db()? .ok_or("no IndexedDB")?; - let request = factory.open_with_u32(DB, 1)?; + let request = factory.open_with_u32(DB, VERSION)?; let upgrade = Closure::once_into_js(move |ev: web_sys::Event| { if let Some(db) = ev .target() .and_then(|t| t.dyn_into::().ok()) .and_then(|r| r.result().ok()) .and_then(|r| r.dyn_into::().ok()) - && !db.object_store_names().contains(STORE) { - let _ = db.create_object_store(STORE); + for store in [STORE, HANDLES] { + if !db.object_store_names().contains(store) { + let _ = db.create_object_store(store); + } + } } }); request.set_onupgradeneeded(Some(upgrade.unchecked_ref())); @@ -90,16 +97,57 @@ pub async fn load_all() -> Vec<(String, Vec)> { files } -fn store() -> Option { +fn store_named(name: &str) -> Option { OPENED.with_borrow(|db| { let tx = db .as_ref()? - .transaction_with_str_and_mode(STORE, web_sys::IdbTransactionMode::Readwrite) + .transaction_with_str_and_mode(name, web_sys::IdbTransactionMode::Readwrite) .ok()?; - tx.object_store(STORE).ok() + tx.object_store(name).ok() }) } +fn store() -> Option { + store_named(STORE) +} + +/// The handles kept: (the page's path, the handle). Read after [`load_all`]. +pub async fn handles() -> Vec<(String, JsValue)> { + let Some(db) = OPENED.with_borrow(|db| db.clone()) else { + return Vec::new(); + }; + let read = async { + let tx = db.transaction_with_str(HANDLES)?; + let store = tx.object_store(HANDLES)?; + let keys: js_sys::Array = done(&store.get_all_keys()?).await?.dyn_into()?; + let values: js_sys::Array = done(&store.get_all()?).await?.dyn_into()?; + Ok::<_, JsValue>( + keys.iter() + .zip(values.iter()) + .filter_map(|(k, v)| Some((k.as_string()?, v))) + .collect(), + ) + }; + read.await.unwrap_or_else(|e: JsValue| { + log::warn!("browser storage: remembered files unreadable: {e:?}"); + Vec::new() + }) +} + +pub fn put_handle(path: &str, handle: &JsValue) { + if let Some(store) = store_named(HANDLES) + && let Err(e) = store.put_with_key(handle, &JsValue::from_str(path)) + { + log::warn!("browser storage: cannot remember {path}: {e:?}"); + } +} + +pub fn delete_handle(path: &str) { + if let Some(store) = store_named(HANDLES) { + let _ = store.delete(&JsValue::from_str(path)); + } +} + /// Keeps `bytes` as `path` (transactions of one page run in the order made). pub fn put(path: String, bytes: Vec) { if let Some(store) = store() { diff --git a/apps/desktop/src/platform/web/import.rs b/apps/desktop/src/platform/web/import.rs new file mode 100644 index 0000000..2a8447d --- /dev/null +++ b/apps/desktop/src/platform/web/import.rs @@ -0,0 +1,245 @@ +//! Opening a database without holding the page: a Web Worker runs a second instance of +//! the program (`import-worker.js` → [`answer`]) that reads the file — PGN, CBV, ZIP, +//! 7Z, converted and indexed — and gives back its text and index; the page puts the +//! database together from them without reading it again +//! (`chess_core::PgnDatabase::from_index`); the cards of the shelf only ask it how many +//! games a file holds. One worker serves the visit and reads the files one after +//! another, in the order they were given. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use chess_core::{PgnDatabase, PgnIndex}; +use chess_import::{Database, Format, ImportError, Opened, PgnDb, Unsupported}; +use serde::{Deserialize, Serialize}; +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The worker's script, beside the page. +const SCRIPT: &str = "import-worker.js"; + +/// What the worker gives back besides the text. +#[derive(Serialize, Deserialize)] +struct Read { + index: PgnIndex, + /// Its place in [`Format::ALL`]. + format: usize, + notes: Vec, +} + +/// Why the worker could not read a file: [`ImportError`] in serde's terms. +#[derive(Serialize, Deserialize)] +enum Failure { + Io(String), + Corrupt(String), + Encrypted, + ChessBase2, + Empty, + Cancelled, +} + +impl Failure { + fn of(e: ImportError) -> Failure { + match e { + ImportError::Io { source, .. } => Failure::Io(source.to_string()), + ImportError::Corrupt(s) => Failure::Corrupt(s), + ImportError::Unsupported(Unsupported::Encrypted) => Failure::Encrypted, + ImportError::Unsupported(Unsupported::ChessBase2) => Failure::ChessBase2, + ImportError::Empty => Failure::Empty, + ImportError::Cancelled => Failure::Cancelled, + } + } + + fn error(self, path: &Path) -> ImportError { + match self { + Failure::Io(e) => io_error(path, e), + Failure::Corrupt(s) => ImportError::Corrupt(s), + Failure::Encrypted => ImportError::Unsupported(Unsupported::Encrypted), + Failure::ChessBase2 => ImportError::Unsupported(Unsupported::ChessBase2), + Failure::Empty => ImportError::Empty, + Failure::Cancelled => ImportError::Cancelled, + } + } +} + +fn io_error(path: &Path, e: impl ToString) -> ImportError { + ImportError::Io { + path: path.to_owned(), + source: std::io::Error::other(e.to_string()), + } +} + +fn set(object: &js_sys::Object, key: &str, value: &JsValue) { + let _ = js_sys::Reflect::set(object, &key.into(), value); +} + +/// The worker's side: reads `bytes` of the file `name`. The answer: `{text, index}` +/// (the text and the index in JSON), only `{games}` when `count` is asked, or `{error}` +/// (a [`Failure`] in JSON). +pub fn answer(name: &str, bytes: Vec, count: bool) -> JsValue { + let never = std::sync::atomic::AtomicBool::new(false); + let answer = js_sys::Object::new(); + let read = chess_import::open_bytes(name, bytes, &mut |_| {}, &never).and_then(|opened| { + // Read from bytes, a database is always converted to PGN. + let Database::Pgn(pgn) = opened.db else { + return Err(ImportError::Corrupt("not a PGN database".into())); + }; + Ok((pgn.db, opened.format, opened.notes)) + }); + match read { + Ok((db, _, _)) if count => set(&answer, "games", &JsValue::from(db.len() as f64)), + Ok((db, format, notes)) => { + let (text, index) = db.into_index(); + let read = Read { + index, + format: Format::ALL.iter().position(|f| *f == format).unwrap_or(0), + notes, + }; + set(&answer, "text", &js_sys::Uint8Array::from(text.as_slice())); + let json = serde_json::to_string(&read).unwrap_or_default(); + set(&answer, "index", &JsValue::from_str(&json)); + } + Err(e) => { + let json = serde_json::to_string(&Failure::of(e)).unwrap_or_default(); + set(&answer, "error", &JsValue::from_str(&json)); + } + } + answer.into() +} + +/// Who waits for an answer. +enum Waiting { + Open(PathBuf, Box)>), + Count(Box)>), +} + +impl Waiting { + fn failed(self, e: impl ToString) { + match self { + Waiting::Open(path, done) => done(Err(io_error(&path, e))), + Waiting::Count(done) => done(None), + } + } +} + +thread_local! { + static WORKER: RefCell> = const { RefCell::new(None) }; + static WAITING: RefCell> = RefCell::new(HashMap::new()); + static NEXT: RefCell = const { RefCell::new(0) }; +} + +/// The worker's answer to a request: the database, or why there is none. +fn answered(data: JsValue) { + let get = |k: &str| js_sys::Reflect::get(&data, &k.into()).unwrap_or(JsValue::UNDEFINED); + let id = get("id").as_f64().unwrap_or(-1.0) as u32; + let (path, done) = match WAITING.with_borrow_mut(|w| w.remove(&id)) { + Some(Waiting::Open(path, done)) => (path, done), + Some(Waiting::Count(done)) => { + done(get("games").as_f64().map(|n| n as usize)); + return; + } + None => return, + }; + if let Some(json) = get("error").as_string() { + let e = serde_json::from_str::(&json) + .map_or_else(|_| io_error(&path, json.clone()), |f| f.error(&path)); + done(Err(e)); + return; + } + let text = get("text") + .dyn_into::() + .map(|a| a.to_vec()); + let read = get("index") + .as_string() + .and_then(|j| serde_json::from_str::(&j).ok()); + let (Ok(text), Some(read)) = (text, read) else { + done(Err(io_error( + &path, + "the reader's answer is not a database", + ))); + return; + }; + done(Ok(Opened { + db: Database::Pgn(PgnDb::new(PgnDatabase::from_index(text, read.index))), + format: Format::ALL.get(read.format).copied().unwrap_or(Format::Pgn), + notes: read.notes, + })) +} + +fn worker() -> Result { + if let Some(w) = WORKER.with_borrow(|w| w.clone()) { + return Ok(w); + } + let options = web_sys::WorkerOptions::new(); + options.set_type(web_sys::WorkerType::Module); + let w = web_sys::Worker::new_with_options(SCRIPT, &options)?; + let on_message = + Closure::::new(|e: web_sys::MessageEvent| { + answered(e.data()); + }); + w.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + // The worker serves the whole visit. + on_message.forget(); + let on_error = Closure::::new(|e: web_sys::ErrorEvent| { + // The worker itself failed (out of memory, its script not loaded): the files + // waiting for it fail, and the next one gets a new worker. + let message = e.message(); + if let Some(w) = WORKER.with_borrow_mut(Option::take) { + w.terminate(); + } + for (_, waiting) in WAITING.with_borrow_mut(std::mem::take) { + waiting.failed(&message); + } + }); + w.set_onerror(Some(on_error.as_ref().unchecked_ref())); + on_error.forget(); + WORKER.with_borrow_mut(|slot| *slot = Some(w.clone())); + Ok(w) +} + +/// Reads the page's file `path` in the worker; `done` gets the database on the page's +/// thread. +pub fn open(path: &Path, done: impl FnOnce(Result) + 'static) { + ask(path, false, Waiting::Open(path.to_owned(), Box::new(done))); +} + +/// How many games the page's file `path` holds (`None`: it cannot be read), read in +/// the worker; `done` gets it on the page's thread. +pub fn count(path: &Path, done: impl FnOnce(Option) + 'static) { + ask(path, true, Waiting::Count(Box::new(done))); +} + +fn ask(path: &Path, count: bool, waiting: Waiting) { + let bytes = match super::vfs::read(path) { + Ok(b) => b, + Err(e) => return waiting.failed(e), + }; + let w = match worker() { + Ok(w) => w, + Err(e) => return waiting.failed(format!("{e:?}")), + }; + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let id = NEXT.with_borrow_mut(|n| { + *n += 1; + *n + }); + WAITING.with_borrow_mut(|m| m.insert(id, waiting)); + let array = js_sys::Uint8Array::from(bytes.as_slice()); + drop(bytes); + let message = js_sys::Object::new(); + set(&message, "id", &JsValue::from(id)); + set(&message, "name", &JsValue::from_str(&name)); + set(&message, "bytes", &array); + set(&message, "count", &JsValue::from_bool(count)); + // The copy goes to the worker, not copied again. + let transfer = js_sys::Array::of1(&array.buffer()); + if let Err(e) = w.post_message_with_transfer(&message, &transfer) + && let Some(waiting) = WAITING.with_borrow_mut(|m| m.remove(&id)) + { + waiting.failed(format!("{e:?}")); + } +} diff --git a/apps/desktop/src/platform/web/mod.rs b/apps/desktop/src/platform/web/mod.rs index 09d1651..4515a21 100644 --- a/apps/desktop/src/platform/web/mod.rs +++ b/apps/desktop/src/platform/web/mod.rs @@ -8,7 +8,9 @@ pub mod engine; pub mod idb; +pub mod import; pub mod page; +pub mod remembered; pub mod storage; pub mod vfs; @@ -46,16 +48,16 @@ pub fn spawn(_name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Resul pub fn open_database( path: &Path, - progress: &mut dyn FnMut(ScanProgress), - cancel: &AtomicBool, -) -> Result { - let bytes = vfs::read(path).map_err(|source| ImportError::Io { - path: path.to_owned(), - source, - })?; - let name = path - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default(); - chess_import::open_bytes(&name, bytes, progress, cancel) + _progress: impl FnMut(ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + import::open(path, move |read| { + done(if cancel.load(std::sync::atomic::Ordering::Relaxed) { + Err(ImportError::Cancelled) + } else { + read + }) + }); + Ok(()) } diff --git a/apps/desktop/src/platform/web/remembered.rs b/apps/desktop/src/platform/web/remembered.rs new file mode 100644 index 0000000..21809f1 --- /dev/null +++ b/apps/desktop/src/platform/web/remembered.rs @@ -0,0 +1,195 @@ +//! Files a Chromium browser remembers (Chrome, Edge: the File System Access API): a +//! file chosen through `showOpenFilePicker` leaves a handle the page keeps in the +//! browser's storage; at the next visit the file is read again through it — at once +//! when the browser still allows it, else after the user's «Allow reading» (the +//! browser's own question). Only reading: the page never writes the user's files +//! (decisions «Веб-версия»). Firefox and Safari have no such handles: there the user +//! chooses the file again ([`super::page::pick_files`]). + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +use super::page::Read; + +thread_local! { + /// Files of earlier visits the browser asks about first: the page's path, the handle. + static WAITING: RefCell> = RefCell::new(HashMap::new()); +} + +fn get(object: &JsValue, key: &str) -> JsValue { + js_sys::Reflect::get(object, &key.into()).unwrap_or(JsValue::UNDEFINED) +} + +/// Calls `object.method(arg)` and waits for the promise it gives. +async fn call(object: &JsValue, method: &str, arg: &JsValue) -> Result { + let f: js_sys::Function = get(object, method).dyn_into()?; + let promise: js_sys::Promise = f.call1(object, arg)?.dyn_into()?; + wasm_bindgen_futures::JsFuture::from(promise).await +} + +/// `{mode: "read"}`: the permission asked for. +fn read_mode() -> JsValue { + let o = js_sys::Object::new(); + let _ = js_sys::Reflect::set(&o, &"mode".into(), &"read".into()); + o.into() +} + +/// The browser remembers chosen files (it has `showOpenFilePicker`). +pub fn supported() -> bool { + web_sys::window().is_some_and(|w| get(&w, "showOpenFilePicker").is_function()) +} + +/// Reads the file behind `handle` (`None`: too big, its name and size go to `read`). +async fn read_file(handle: &JsValue, read: &mut Read) -> Result>, JsValue> { + let file: web_sys::File = call(handle, "getFile", &JsValue::UNDEFINED) + .await? + .dyn_into()?; + let size = file.size() as u64; + if size > crate::platform::files::TOO_BIG { + read.too_big.push((file.name(), size)); + return Ok(None); + } + let buf = wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await?; + Ok(Some(js_sys::Uint8Array::new(&buf).to_vec())) +} + +/// Asks the user for files (the browser's dialog, `extensions` like `.pgn`); `then` +/// gets the paths of those read, each remembered. Must run soon after the user's click +/// or key, like [`super::page::pick_files`]. +pub fn pick(extensions: &[String], then: impl FnOnce(Vec, Vec<(String, u64)>) + 'static) { + let Some(window) = web_sys::window() else { + return; + }; + let types = js_sys::Array::new(); + let accept = js_sys::Object::new(); + let list = extensions + .iter() + .map(|e| JsValue::from_str(e)) + .collect::(); + let _ = js_sys::Reflect::set(&accept, &"application/octet-stream".into(), &list); + let kind = js_sys::Object::new(); + let _ = js_sys::Reflect::set(&kind, &"accept".into(), &accept); + types.push(&kind); + let options = js_sys::Object::new(); + let _ = js_sys::Reflect::set(&options, &"multiple".into(), &JsValue::TRUE); + let _ = js_sys::Reflect::set(&options, &"types".into(), &types); + let _ = js_sys::Reflect::set(&options, &"id".into(), &"chesspenguin-databases".into()); + // The dialog is opened now, within the user's gesture; the rest waits for it. + let chosen = get(&window, "showOpenFilePicker") + .dyn_into::() + .and_then(|f| f.call1(&window, &options)) + .and_then(|p| p.dyn_into::()); + wasm_bindgen_futures::spawn_local(async move { + let mut read = Read { + read: Vec::new(), + too_big: Vec::new(), + }; + let mut paths = Vec::new(); + // Cancelled by the user: an error, nothing chosen. + let handles = match chosen { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p).await, + Err(e) => Err(e), + }; + if let Ok(handles) = handles.and_then(|h| h.dyn_into::()) { + for handle in handles.iter() { + let name = get(&handle, "name").as_string().unwrap_or_default(); + match read_file(&handle, &mut read).await { + Ok(Some(bytes)) => { + let path = super::vfs::add_opened(&name, bytes); + super::idb::put_handle(&path.to_string_lossy(), &handle); + paths.push(path); + } + Ok(None) => {} + Err(e) => log::warn!("cannot read {name}: {e:?}"), + } + } + } + then(paths, read.too_big); + }); +} + +/// Reads again the files remembered at earlier visits that the browser still lets the +/// page read; the others wait for the user ([`waiting`], [`allow`]). Called once +/// before the interface starts. +pub async fn restore() { + if !supported() { + return; + } + for (path, handle) in super::idb::handles().await { + let path = PathBuf::from(path); + let state = call(&handle, "queryPermission", &read_mode()) + .await + .ok() + .and_then(|s| s.as_string()); + if state.as_deref() == Some("granted") + && let Ok(Some(bytes)) = read_file( + &handle, + &mut Read { + read: Vec::new(), + too_big: Vec::new(), + }, + ) + .await + { + log::info!("remembered file read again: {}", path.display()); + super::vfs::put_opened(&path, bytes); + } else { + WAITING.with_borrow_mut(|w| w.insert(path, handle)); + } + } +} + +/// The browser remembers the file `path` and asks the user before it is read again. +pub fn waiting(path: &Path) -> bool { + WAITING.with_borrow(|w| w.contains_key(path)) +} + +/// Asks the browser to let the page read `path` again (its question to the user; soon +/// after the user's click). `then`: whether the file is read and back at its path. +pub fn allow(path: &Path, then: impl FnOnce(bool) + 'static) { + let Some(handle) = WAITING.with_borrow(|w| w.get(path).cloned()) else { + then(false); + return; + }; + let path = path.to_owned(); + // Asked now, within the user's gesture. + let asked = get(&handle, "requestPermission") + .dyn_into::() + .and_then(|f| f.call1(&handle, &read_mode())) + .and_then(|p| p.dyn_into::()); + wasm_bindgen_futures::spawn_local(async move { + let granted = match asked { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p) + .await + .ok() + .and_then(|s| s.as_string()) + .is_some_and(|s| s == "granted"), + Err(_) => false, + }; + let mut read = Read { + read: Vec::new(), + too_big: Vec::new(), + }; + let bytes = if granted { + read_file(&handle, &mut read).await.ok().flatten() + } else { + None + }; + let back = bytes.is_some(); + if let Some(bytes) = bytes { + WAITING.with_borrow_mut(|w| w.remove(&path)); + super::vfs::put_opened(&path, bytes); + } + then(back); + }); +} + +/// The file `path` is no longer the library's: the browser's handle is let go. +pub fn forget(path: &Path) { + WAITING.with_borrow_mut(|w| w.remove(path)); + super::idb::delete_handle(&path.to_string_lossy()); +} diff --git a/apps/desktop/src/platform/web/vfs.rs b/apps/desktop/src/platform/web/vfs.rs index b4b0eb2..9536271 100644 --- a/apps/desktop/src/platform/web/vfs.rs +++ b/apps/desktop/src/platform/web/vfs.rs @@ -26,8 +26,9 @@ struct Entry { thread_local! { static FILES: RefCell> = const { RefCell::new(BTreeMap::new()) }; - /// The number of the last file opened (each gets a folder of its own). - static OPENED_COUNT: RefCell = const { RefCell::new(0) }; + /// The number of the last file opened (each gets a folder of its own; numbered from + /// the visit's start time, so that a file of an earlier visit keeps its own). + static OPENED_COUNT: RefCell = const { RefCell::new(0) }; } fn now_ms() -> u64 { @@ -133,15 +134,21 @@ pub fn list(dir: &Path) -> Vec { /// Its path ends with its own name, in a folder of its own. pub fn add_opened(name: &str, bytes: Vec) -> PathBuf { let n = OPENED_COUNT.with_borrow_mut(|n| { - *n += 1; + *n = (*n + 1).max(now_ms()); *n }); // A name is a file's, not a path (a browser gives no folders; this makes sure). let name = name.rsplit(['/', '\\']).next().unwrap_or(name); let path = Path::new(OPENED).join(n.to_string()).join(name); + put_opened(&path, bytes); + path +} + +/// A file of an earlier visit the browser let the page read again, at its old path. +pub fn put_opened(path: &Path, bytes: Vec) { FILES.with_borrow_mut(|files| { files.insert( - path.clone(), + path.to_owned(), Entry { bytes, modified_ms: now_ms(), @@ -149,5 +156,4 @@ pub fn add_opened(name: &str, bytes: Vec) -> PathBuf { }, ); }); - path } diff --git a/apps/web/build.sh b/apps/web/build.sh index 4b5db4b..b17514a 100755 --- a/apps/web/build.sh +++ b/apps/web/build.sh @@ -36,7 +36,7 @@ if command -v wasm-opt >/dev/null 2>&1; then "$out/chesspenguin_web_bg.wasm" -o "$out/chesspenguin_web_bg.wasm" fi -cp "$here/page/device.js" "$here/page/page.js" "$out/" +cp "$here/page/device.js" "$here/page/page.js" "$here/page/import-worker.js" "$out/" # The engine: Stockfish.js 19.0.1 (npm `stockfish`, GPL-3.0), its single-threaded build, # checked against the registry's integrity (THIRD_PARTY_NOTICES.md). STOCKFISH_TGZ= points diff --git a/apps/web/check/app.mjs b/apps/web/check/app.mjs index 57207ab..021a118 100644 --- a/apps/web/check/app.mjs +++ b/apps/web/check/app.mjs @@ -57,9 +57,7 @@ try { // Open a PGN by the button's shortcut: the browser's file chooser gets the file. const pgn = join(s.b.profile, 'Test games.pgn'); copyFileSync(join(root, 'examples/alekhine.pgn'), pgn); - await t.key('o', ['ctrl']); - await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - await t.setFiles('cp-open-files', [pgn]); + await t.choose([pgn], () => t.key('o', ['ctrl'])); await sleep(3000); await shot('web-2-opened.png'); @@ -109,11 +107,31 @@ try { await sleep(1000); await shot('web-8-e4.png'); - // The settings and the shelf after a reload (the browser's storage). + // An unsaved game: the browser asks before the page is left, and its draft is kept. + check(await t.evaluate(`typeof window.onbeforeunload === 'function'`), 'unsaved: the browser asks before leaving'); + await sleep(1500); + const draft = () => t.evaluate(`new Promise((ok) => { + const q = indexedDB.open('chesspenguin'); + q.onsuccess = () => { + const r = q.result.transaction('files').objectStore('files').get('/data/draft.json'); + r.onsuccess = () => ok(r.result ? JSON.parse(new TextDecoder().decode(r.result)).pgn : ''); + }; + q.onerror = () => ok(''); + })`); + check(/1\. e4/.test(await draft()), 'the draft of the unsaved game is kept'); + + // The settings and the shelf after a reload (the browser's storage). The question on + // leaving is answered «Leave». + await t.evaluate(`(window.onbeforeunload = null, true)`); await t.navigate(`${s.base}?lang=en`); await started(); await sleep(2500); await shot('web-9-reloaded.png'); + check(/1\. e4/.test(await draft()), 'the draft is there after the reload (offered over the library)'); + if (await t.evaluate(`typeof window.showOpenFilePicker === 'function'`)) { + // Chrome, Edge: the file chosen before the reload is read again by itself. + check(s.logs.some((l) => /remembered file read again: .*Test games\.pgn/.test(l)), 'the chosen file is remembered (File System Access)'); + } } finally { await s.stop(); } diff --git a/apps/web/check/browser.mjs b/apps/web/check/browser.mjs index 0f0bf07..5fae3ae 100644 --- a/apps/web/check/browser.mjs +++ b/apps/web/check/browser.mjs @@ -6,10 +6,11 @@ // const b = await open(port); const t = await b.tab(1400, 860, log); // t.navigate(url) · t.evaluate(js) · t.waitFor(js, ms) · t.screenshot() // t.click(x, y, {double, right}) · t.key(key, mods, times) · t.setFiles(inputId, paths) +// t.choose(paths, open): the user chooses the files in the dialog open() brings up import { spawn } from 'node:child_process'; -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { basename, join } from 'node:path'; import { launch as launchFirefox } from './firefox.mjs'; import { sleep, tab as bidiTab } from './bidi.mjs'; @@ -85,6 +86,12 @@ async function firefox(port) { }); await ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: node.result.sharedId }, files }); }, + // The user chooses `files` in the dialog `open()` brings up (the page's file input). + async choose(files, open) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); + await this.setFiles('cp-open-files', files); + }, }; }, }; @@ -207,6 +214,36 @@ async function chromium(port) { const { result } = await s('Runtime.evaluate', { expression: `document.getElementById(${JSON.stringify(id)})` }); await s('DOM.setFileInputFiles', { objectId: result.objectId, files }); }, + // The user chooses `files` in the dialog `open()` brings up. Chrome's own dialog + // (showOpenFilePicker, the files remembered) cannot be driven headless: the files + // are put into the site's private file system and its handles are what the + // dialog gives — the same kind of handle, kept and read again the same way. + async choose(files, open) { + const picker = await this.evaluate(`typeof window.showOpenFilePicker === 'function'`); + if (!picker) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); + return this.setFiles('cp-open-files', files); + } + const given = files.map((f) => ({ name: basename(f), b64: readFileSync(f).toString('base64') })); + await this.evaluate(`(() => { + const given = ${JSON.stringify(given)}; + window.showOpenFilePicker = async () => { + const root = await navigator.storage.getDirectory(); + const handles = []; + for (const g of given) { + const h = await root.getFileHandle(g.name, { create: true }); + const w = await h.createWritable(); + await w.write(Uint8Array.from(atob(g.b64), (c) => c.charCodeAt(0))); + await w.close(); + handles.push(h); + } + return handles; + }; + return true; + })()`); + await open(); + }, }; }, }; diff --git a/apps/web/check/review.mjs b/apps/web/check/review.mjs index 07a71c6..c6e8892 100644 --- a/apps/web/check/review.mjs +++ b/apps/web/check/review.mjs @@ -33,9 +33,7 @@ try { await s.run({ url: '?lang=en' }, outDir); await sleep(2000); // The games in one file, reviewed one by one. - await s.run({ key: 'o', mods: ['ctrl'] }, outDir); - await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - await t.setFiles('cp-open-files', [all]); + await t.choose([all], () => s.run({ key: 'o', mods: ['ctrl'] }, outDir)); await sleep(3000); await s.run({ shot: 'review-0-opened.png' }, outDir); for (let i = 0; i < games.length; i++) { diff --git a/apps/web/check/stage2.mjs b/apps/web/check/stage2.mjs index 64b7a01..ee49678 100644 --- a/apps/web/check/stage2.mjs +++ b/apps/web/check/stage2.mjs @@ -57,9 +57,7 @@ try { copyFileSync(join(root, 'examples/alekhine.pgn'), a); copyFileSync(join(root, 'examples/classics.pgn'), b); for (const file of [b, a]) { - await step({ key: 'o', mods: ['ctrl'] }); - await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - await t.setFiles('cp-open-files', [file]); + await t.choose([file], () => step({ key: 'o', mods: ['ctrl'] })); await sleep(2500); } await step({ shot: 's2-5-opened.png' }); diff --git a/apps/web/check/steps.mjs b/apps/web/check/steps.mjs index a32eadf..559cbbf 100644 --- a/apps/web/check/steps.mjs +++ b/apps/web/check/steps.mjs @@ -19,7 +19,9 @@ export async function session(appDir, port = Number(process.env.CP_CHECK_PORT || const server = spawn('python3', ['-I', join(root, 'apps/web/check/serve.py'), resolve(appDir), join(root, 'website/static'), String(port)], { stdio: 'ignore' }); const b = await open(port + 457); const errors = []; + const logs = []; const t = await b.tab(1400, 860, (line) => { + logs.push(line); if (/panicked|RuntimeError|\[error\]/.test(line) && !/favicon|404/.test(line)) errors.push(line); if (process.env.CONSOLE) console.log(line); }); @@ -43,7 +45,7 @@ export async function session(appDir, port = Number(process.env.CP_CHECK_PORT || if (step.shot) writeFileSync(join(outDir, step.shot), await t.screenshot()); }; return { - t, b, base, errors, run, + t, b, base, errors, logs, run, stop: async () => { await b.stop(); server.kill(); }, }; } diff --git a/apps/web/page/import-worker.js b/apps/web/page/import-worker.js new file mode 100644 index 0000000..20e4a61 --- /dev/null +++ b/apps/web/page/import-worker.js @@ -0,0 +1,14 @@ +// The page's reader: a second instance of the program that reads the databases the user +// opens, so that the page does not stop while a large one is read +// (apps/desktop/src/platform/web/import.rs). One file at a time, in order. +import init, { read_database } from './chesspenguin_web.js'; + +const ready = init(); + +self.onmessage = async (e) => { + await ready; + const { id, name, bytes, count } = e.data; + const answer = read_database(name, bytes, count); + answer.id = id; + self.postMessage(answer, answer.text ? [answer.text.buffer] : []); +}; diff --git a/apps/web/src/lib.rs b/apps/web/src/lib.rs index 5280429..9267482 100644 --- a/apps/web/src/lib.rs +++ b/apps/web/src/lib.rs @@ -6,6 +6,13 @@ use wasm_bindgen::JsCast; use wasm_bindgen::prelude::*; +/// The reader worker's work (`page/import-worker.js`): the database in the file `name`, +/// read and indexed away from the page (or only its games counted). +#[wasm_bindgen] +pub fn read_database(name: String, bytes: Vec, count: bool) -> JsValue { + chesspenguin_app::read_database(&name, bytes, count) +} + /// Starts ChessPenguin in the page's canvas `canvas_id`. Resolves once the interface /// runs; an error says why it could not start (no WebGL, …). #[wasm_bindgen] diff --git a/crates/chess-core/Cargo.toml b/crates/chess-core/Cargo.toml index 2f0293e..a66c3b8 100644 --- a/crates/chess-core/Cargo.toml +++ b/crates/chess-core/Cargo.toml @@ -9,6 +9,12 @@ license.workspace = true shakmaty.workspace = true encoding_rs.workspace = true thiserror.workspace = true +# The index of a database in serde's terms: the web version reads a database in a +# worker and gives its index to the page (`PgnIndex`). +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] [dev-dependencies] # Independent oracle in corpus tests: the core uses its own lexer (byte offsets, diff --git a/crates/chess-core/src/database.rs b/crates/chess-core/src/database.rs index 731fe23..34678df 100644 --- a/crates/chess-core/src/database.rs +++ b/crates/chess-core/src/database.rs @@ -32,6 +32,18 @@ impl From for OpenError { } } +/// What reading a database's text found: everything of a [`PgnDatabase`] but the text. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PgnIndex { + detected: EncodingGuess, + encoding: TextEncoding, + entries: Vec, + content_hash: u64, + letter_repair: LetterRepairDetection, + repair_letters: bool, +} + /// Identity of the source content, for change detection and cache keys. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct SourceFingerprint { @@ -113,6 +125,39 @@ impl PgnDatabase { }) } + /// The database taken apart: its text and its index (to rebuild it elsewhere — + /// the web version reads a database in a worker and gives it to the page). + pub fn into_index(self) -> (Vec, PgnIndex) { + let index = PgnIndex { + detected: self.detected, + encoding: self.encoding, + entries: self.entries, + content_hash: self.fingerprint.content_hash, + letter_repair: self.letter_repair, + repair_letters: self.repair_letters, + }; + (self.bytes, index) + } + + /// The database again from its text and the index [`Self::into_index`] gave, + /// without reading the text once more. + pub fn from_index(bytes: Vec, index: PgnIndex) -> Self { + PgnDatabase { + path: None, + fingerprint: SourceFingerprint { + len: bytes.len() as u64, + modified: None, + content_hash: index.content_hash, + }, + bytes, + detected: index.detected, + encoding: index.encoding, + entries: index.entries, + letter_repair: index.letter_repair, + repair_letters: index.repair_letters, + } + } + pub fn path(&self) -> Option<&Path> { self.path.as_deref() } @@ -223,6 +268,26 @@ impl PgnDatabase { mod tests { use super::*; + /// A database taken apart and put together again is the same database. + #[test] + fn index_round_trip() { + let text = "[White \"A\"]\n[Black \"B\"]\n\n1. e4 e5 *\n\n[White \"C\"]\n\n1. d4 {x} *\n"; + let db = PgnDatabase::from_bytes( + text.as_bytes().to_vec(), + None, + &mut |_| {}, + &AtomicBool::new(false), + ) + .unwrap(); + let (entries, hash) = (db.entries().to_vec(), db.fingerprint.content_hash); + let (bytes, index) = db.into_index(); + let again = PgnDatabase::from_index(bytes, index); + assert_eq!(again.entries(), entries.as_slice()); + assert_eq!(again.fingerprint.content_hash, hash); + assert_eq!(again.bytes(), text.as_bytes()); + assert_eq!(again.load_game(1).unwrap().game.tag("White"), Some("C")); + } + fn assert_send_sync() {} #[test] diff --git a/crates/chess-core/src/encoding.rs b/crates/chess-core/src/encoding.rs index bc06a00..19fa4bb 100644 --- a/crates/chess-core/src/encoding.rs +++ b/crates/chess-core/src/encoding.rs @@ -8,6 +8,7 @@ use std::borrow::Cow; /// Encodings supported for PGN sources. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum TextEncoding { Utf8, @@ -65,6 +66,7 @@ impl TextEncoding { } /// How sure the detector is. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Confidence { /// Valid UTF-8 (or pure ASCII), or a UTF-8 BOM. @@ -74,6 +76,7 @@ pub enum Confidence { } /// Result of [`detect_encoding`]. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct EncodingGuess { pub encoding: TextEncoding, diff --git a/crates/chess-core/src/lib.rs b/crates/chess-core/src/lib.rs index 01d2f39..94c0e7e 100644 --- a/crates/chess-core/src/lib.rs +++ b/crates/chess-core/src/lib.rs @@ -19,7 +19,7 @@ pub use comment::{ Annotation, CommentPart, ShapeColor, comment_display_text, parse_comment, shapes, with_shapes, with_text, }; -pub use database::{OpenError, PgnDatabase, SourceFingerprint}; +pub use database::{OpenError, PgnDatabase, PgnIndex, SourceFingerprint}; pub use diagnostic::{Diagnostic, DiagnosticCode, Severity, SourceLocation}; pub use edit::{EditError, EditOutcome}; pub use encoding::{Confidence, EncodingGuess, TextEncoding, detect_encoding}; diff --git a/crates/chess-core/src/pgn/scan.rs b/crates/chess-core/src/pgn/scan.rs index db47a62..87b1c9e 100644 --- a/crates/chess-core/src/pgn/scan.rs +++ b/crates/chess-core/src/pgn/scan.rs @@ -7,6 +7,7 @@ use crate::encoding::TextEncoding; use crate::pgn::lexer::{Lexer, TokKind, parse_tag}; /// Summary flags computed while scanning. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct EntryFlags { pub has_fen: bool, @@ -28,6 +29,7 @@ pub struct EntryFlags { } /// One record of a PGN file. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct GameEntry { /// 0-based ordinal in the file. diff --git a/crates/chess-core/src/repair.rs b/crates/chess-core/src/repair.rs index d095cb3..b7a8fb4 100644 --- a/crates/chess-core/src/repair.rs +++ b/crates/chess-core/src/repair.rs @@ -45,6 +45,7 @@ impl LetterRepairCounts { } /// Source-level detection result. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct LetterRepairDetection { /// Substitution pattern found (see [`detect_letter_substitution`]). diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index 930e11a..72a339f 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -79,6 +79,14 @@ pub enum Format { } impl Format { + pub const ALL: [Format; 5] = [ + Format::Pgn, + Format::ChessBase, + Format::ChessBaseArchive, + Format::Zip, + Format::SevenZip, + ]; + pub fn label(self) -> &'static str { match self { Format::Pgn => "PGN",