Web version: databases read in a worker, the shelf's counts, Chrome and Edge remember chosen files

The page's reader: a Web Worker with a second instance of the program reads
a database (PGN, CBV, ZIP, 7Z) and gives back its text and index; the page
puts it together without reading it again (chess_core::PgnIndex,
PgnDatabase::into_index / from_index, serde behind a feature). A 13 MB CBV:
the longest frame 17 ms in Firefox, 67 ms in Chromium (1000 ms before).
platform::open_database is the same on both sides: away from the screen,
done when read. The shelf's cards count the games the same way (one file
at a time); the counts are kept through platform::fs.

Chrome, Edge (File System Access): a chosen file's handle is kept in the
browser's storage; at the next visit the file is read again by itself when
the browser allows it, else the card offers «Allow reading» (the browser's
own question). Files of different visits get folders of their own.

Checks: t.choose(files, open) for both browsers (in Chromium the handles of
the site's private file system stand for the dialog's); app.mjs checks the
draft, the question on leaving and the remembered file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 17:50:54 +03:00
parent 000821887f
commit f694bc768b
31 changed files with 1048 additions and 190 deletions

1
Cargo.lock generated
View file

@ -778,6 +778,7 @@ version = "2.1.1"
dependencies = [
"encoding_rs",
"pgn-reader",
"serde",
"shakmaty",
"thiserror 2.0.21",
]

View file

@ -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]

View file

@ -32,6 +32,9 @@ enum Async {
EngineChecked(Result<(PathBuf, String), String>),
/// The folder for new databases (`None`: the dialog was cancelled).
FolderPicked(Option<PathBuf>),
/// 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);

View file

@ -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<PathBuf, Entry>,
/// 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<Mutex<HashMap<PathBuf, Entry>>>,
/// `None`: for this run only.
file: Option<PathBuf>,
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<ToCount> {
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<Job>) -> 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<Job>) -> 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<Job>,
busy: bool,
}
#[cfg(web)]
thread_local! {
static WEB: std::cell::RefCell<Option<Web>> = const { std::cell::RefCell::new(None) };
}
pub struct Counts {
shared: Arc<Mutex<Shared>>,
known: Arc<Mutex<HashMap<PathBuf, Entry>>>,
asked: HashSet<PathBuf>,
jobs: Option<Sender<Job>>,
}
@ -73,100 +204,51 @@ impl Counts {
fn kept_in(file: Option<PathBuf>, ctx: &egui::Context) -> Self {
let known: HashMap<PathBuf, Entry> = 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::<Job>();
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<Count> {
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);

View file

@ -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]

View file

@ -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",

View file

@ -71,6 +71,7 @@ pub async fn start_web(
lang: Option<String>,
) -> 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<u8>, count: bool) -> wasm_bindgen::JsValue {
platform::web::import::answer(name, bytes, count)
}
/// The desktop program: `chesspenguin [--bench <database> [report.txt]]`.
#[cfg(not(web))]
pub fn run_native() -> eframe::Result {

View file

@ -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) =>
{

View file

@ -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<String> = DATABASES
.iter()
.step_by(2)
.map(|e| format!(".{e}"))
.collect::<Vec<_>>()
.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.

View file

@ -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<chess_import::Opened, chess_import::ImportError> {
imp::open_database(path, progress, cancel)
progress: impl FnMut(chess_core::ScanProgress) + Send + 'static,
cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
done: impl FnOnce(Result<chess_import::Opened, chess_import::ImportError>) + Send + 'static,
) -> std::io::Result<()> {
imp::open_database(path, progress, cancel, done)
}

View file

@ -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<Opened, ImportError> {
chess_import::open(path, progress, cancel)
mut progress: impl FnMut(ScanProgress) + Send + 'static,
cancel: std::sync::Arc<AtomicBool>,
done: impl FnOnce(Result<Opened, ImportError>) + Send + 'static,
) -> std::io::Result<()> {
let path = path.to_owned();
spawn("db-open", move || {
done(chess_import::open(&path, &mut progress, &cancel));
})
}

View file

@ -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<JsValue, JsValue> {
@ -33,16 +37,19 @@ async fn open() -> Result<web_sys::IdbDatabase, JsValue> {
.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::<web_sys::IdbOpenDbRequest>().ok())
.and_then(|r| r.result().ok())
.and_then(|r| r.dyn_into::<web_sys::IdbDatabase>().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<u8>)> {
files
}
fn store() -> Option<web_sys::IdbObjectStore> {
fn store_named(name: &str) -> Option<web_sys::IdbObjectStore> {
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<web_sys::IdbObjectStore> {
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<u8>) {
if let Some(store) = store() {

View file

@ -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<String>,
}
/// 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<u8>, 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<dyn FnOnce(Result<Opened, ImportError>)>),
Count(Box<dyn FnOnce(Option<usize>)>),
}
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<Option<web_sys::Worker>> = const { RefCell::new(None) };
static WAITING: RefCell<HashMap<u32, Waiting>> = RefCell::new(HashMap::new());
static NEXT: RefCell<u32> = 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::<Failure>(&json)
.map_or_else(|_| io_error(&path, json.clone()), |f| f.error(&path));
done(Err(e));
return;
}
let text = get("text")
.dyn_into::<js_sys::Uint8Array>()
.map(|a| a.to_vec());
let read = get("index")
.as_string()
.and_then(|j| serde_json::from_str::<Read>(&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<web_sys::Worker, JsValue> {
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::<dyn FnMut(web_sys::MessageEvent)>::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::<dyn FnMut(web_sys::ErrorEvent)>::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<Opened, ImportError>) + '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<usize>) + '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:?}"));
}
}

View file

@ -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<Opened, ImportError> {
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<AtomicBool>,
done: impl FnOnce(Result<Opened, ImportError>) + 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(())
}

View file

@ -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<HashMap<PathBuf, JsValue>> = 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<JsValue, JsValue> {
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<Option<Vec<u8>>, 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<PathBuf>, 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::<js_sys::Array>();
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::<js_sys::Function>()
.and_then(|f| f.call1(&window, &options))
.and_then(|p| p.dyn_into::<js_sys::Promise>());
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::<js_sys::Array>()) {
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::<js_sys::Function>()
.and_then(|f| f.call1(&handle, &read_mode()))
.and_then(|p| p.dyn_into::<js_sys::Promise>());
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());
}

View file

@ -26,8 +26,9 @@ struct Entry {
thread_local! {
static FILES: RefCell<BTreeMap<PathBuf, Entry>> = const { RefCell::new(BTreeMap::new()) };
/// The number of the last file opened (each gets a folder of its own).
static OPENED_COUNT: RefCell<u32> = 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<u64> = const { RefCell::new(0) };
}
fn now_ms() -> u64 {
@ -133,15 +134,21 @@ pub fn list(dir: &Path) -> Vec<PathBuf> {
/// Its path ends with its own name, in a folder of its own.
pub fn add_opened(name: &str, bytes: Vec<u8>) -> 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<u8>) {
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<u8>) -> PathBuf {
},
);
});
path
}

View file

@ -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

View file

@ -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();
}

View file

@ -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();
},
};
},
};

View file

@ -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++) {

View file

@ -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' });

View file

@ -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(); },
};
}

View file

@ -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] : []);
};

View file

@ -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<u8>, 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]

View file

@ -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,

View file

@ -32,6 +32,18 @@ impl From<Cancelled> 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<GameEntry>,
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<u8>, 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<u8>, 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<T: Send + Sync>() {}
#[test]

View file

@ -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,

View file

@ -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};

View file

@ -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.

View file

@ -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`]).

View file

@ -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",