Web version: ChessBase databases of several files and folders, a 2 GB limit with a polite refusal, messages without the page's paths

A .cbh chosen alone brings a window: its folder (Chrome, Edge:
showDirectoryPicker opening beside the file, the folder remembered; others:
webkitdirectory) or all its files; the files are grouped into databases by
name (chess_import::group_chosen), the reader opens a ChessBase one with
open_chessbase_owned. The user's files stay the browser's File objects: the
worker reads them, the page never holds a database's bytes; a kept copy
takes the whole database. Over 2 GB of the files read: refused with the way
to the desktop program. A reader out of memory says so in the user's words.
Paths like /opened/... are no longer shown (platform::files::shown).

chess-core: detect_letter_substitution decodes the text a piece at a time;
it held the whole text as chars (four times its size): a 1 GB cp1251 PGN
could not be read in a browser (capacity overflow) and cost gigabytes on a
computer. Now 1.95 GB opens in Firefox and Chromium.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 20:42:18 +03:00
parent bda92c5675
commit bc104c55b4
21 changed files with 1337 additions and 341 deletions

View file

@ -26,6 +26,7 @@ use crate::sound::SoundPlayer;
enum Async {
DatabasesPicked(Vec<PathBuf>),
/// Files not opened: too big for a browser (name, bytes).
#[cfg(web)]
TooBig(Vec<(String, u64)>),
SavePicked(PathBuf),
SaveCancelled,
@ -35,6 +36,24 @@ enum Async {
/// A remembered file the browser let the page read again.
#[cfg(web)]
ReadAllowed(PathBuf),
/// ChessBase databases not all files of which were chosen (their `.cbh` names).
#[cfg(web)]
Incomplete(Vec<String>),
/// A folder was chosen with no database in it.
#[cfg(web)]
EmptyFolder,
/// A copy of the visit's database `.0` kept in the browser, or why not.
#[cfg(web)]
CopyKept(PathBuf, Result<PathBuf, crate::platform::files::KeepCopy>),
}
/// What the web version tells in a window of its own about the files chosen.
#[cfg(web)]
enum WebNotice {
/// Databases too big for a browser (name, bytes).
TooBig(Vec<(String, u64)>),
/// A ChessBase database's `.cbh` chosen without its other files (its name).
Incomplete(String),
}
/// A passing message at the bottom; `undo`: with the button that puts a deleted game back.
@ -230,6 +249,8 @@ pub struct App {
draft_offer: Option<crate::my_games::Draft>,
#[cfg(web)]
draft_at: Option<f64>,
#[cfg(web)]
web_notice: Option<WebNotice>,
confirm_close: Option<CloseIntent>,
/// Close the game once the pending "save as" succeeds.
close_after_save: Option<CloseIntent>,
@ -470,6 +491,8 @@ impl App {
draft_offer: crate::my_games::read_draft(),
#[cfg(web)]
draft_at: None,
#[cfg(web)]
web_notice: None,
confirm_close: None,
close_after_save: None,
find_after_close: None,
@ -2179,7 +2202,13 @@ impl App {
self.settings.last_target = Some(dest.clone());
self.settings_dirty = true;
self.library.select_db(&dest, ctx);
self.toast(ctx, trf("Copy made: {path}", &[("path", &dest.display())]));
self.toast(
ctx,
trf(
"Copy made: {path}",
&[("path", &crate::platform::files::shown(&dest))],
),
);
}
Err(e) => {
self.toast(ctx, trf("Could not make the copy: {e}", &[("e", &e)]))
@ -2438,16 +2467,23 @@ impl App {
self.pasted(ctx);
while let Ok(msg) = self.rx.try_recv() {
match msg {
Async::TooBig(files) => {
for (_, size) in files {
let size = crate::platform::size_text(size);
self.toast_for(
ctx,
trf("This database is too big for the web version ({size}). Open it in the desktop program — it has no such limit.", &[("size", &size)]),
8.0,
);
#[cfg(web)]
Async::TooBig(files) => self.web_notice = Some(WebNotice::TooBig(files)),
#[cfg(web)]
Async::Incomplete(names) => {
if let Some(name) = names.into_iter().next() {
self.web_notice = Some(WebNotice::Incomplete(name));
}
}
#[cfg(web)]
Async::EmptyFolder => {
self.toast(
ctx,
tr("There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z)."),
);
}
#[cfg(web)]
Async::CopyKept(path, kept) => self.copy_kept(ctx, path, kept),
Async::DatabasesPicked(paths) => {
// The file chosen again takes the place of the one gone.
if let Some(old) = self.choosing_again.take() {
@ -2527,7 +2563,13 @@ impl App {
match chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) {
Ok(()) => {
g.game.mark_saved();
self.toast(ctx, trf("Saved: {path}", &[("path", &path.display())]));
self.toast(
ctx,
trf(
"Saved: {path}",
&[("path", &crate::platform::files::shown(&path))],
),
);
if let Some(intent) = self.close_after_save.take() {
self.finish_close(ctx, intent);
}
@ -2875,10 +2917,29 @@ impl App {
/// the shelf. Only a browser has such files.
fn keep_copy(&mut self, ctx: &egui::Context, path: PathBuf) {
#[cfg(web)]
{
let (tx, wake) = (self.tx.clone(), ctx.clone());
crate::platform::files::keep_copy(&path.clone(), move |kept| {
let _ = tx.send(Async::CopyKept(path, kept));
wake.request_repaint();
});
}
#[cfg(not(web))]
let _ = (ctx, path);
}
/// The copy of `path` is kept (or not): it takes the file's place on the shelf.
#[cfg(web)]
fn copy_kept(
&mut self,
ctx: &egui::Context,
path: PathBuf,
kept: Result<PathBuf, crate::platform::files::KeepCopy>,
) {
{
use crate::platform::files::KeepCopy;
use crate::platform::size_text;
match crate::platform::files::keep_copy(&path) {
match kept {
Ok(copy) => {
for d in self.settings.databases.iter_mut().filter(|d| **d == path) {
*d = copy.clone();
@ -2905,8 +2966,96 @@ impl App {
Err(KeepCopy::Failed(e)) => self.toast(ctx, e),
}
}
#[cfg(not(web))]
let _ = (ctx, path);
}
/// The window of [`WebNotice`]: a database too big for a browser (with the way to
/// the program for the computer), or a ChessBase database's other files to choose.
#[cfg(web)]
fn web_notice(&mut self, ctx: &egui::Context) {
let Some(notice) = &self.web_notice else {
return;
};
let mut close = false;
let mut folder = false;
let mut files = false;
let modal = egui::Modal::new(egui::Id::new("web_notice")).show(ctx, |ui| {
ui.set_width(460.0);
match notice {
WebNotice::TooBig(dbs) => {
for (name, size) in dbs {
ui.label(RichText::new(name.as_str()).strong());
ui.label(trf(
"This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.",
&[
("size", &crate::platform::size_text(*size)),
("limit", &crate::platform::size_text(crate::platform::files::TOO_BIG)),
],
));
}
ui.add_space(6.0);
let lang = match crate::i18n::current() {
crate::i18n::Lang::En => "",
crate::i18n::Lang::Ru => "ru/",
crate::i18n::Lang::Fr => "fr/",
crate::i18n::Lang::De => "de/",
crate::i18n::Lang::Es => "es/",
crate::i18n::Lang::It => "it/",
crate::i18n::Lang::Pt => "pt/",
crate::i18n::Lang::Uz => "uz/",
crate::i18n::Lang::Kk => "kk/",
};
ui.hyperlink_to(
tr("Download ChessPenguin for the computer"),
format!("/{lang}#download"),
);
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
close = ui.button(tr("Close")).clicked();
});
}
WebNotice::Incomplete(name) => {
ui.label(RichText::new(name.as_str()).strong());
ui.label(tr(
"A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.",
));
ui.add_space(4.0);
ui.label(
RichText::new(if crate::platform::files::remembers_chosen() {
tr("Allow access to the database's folder — its other files will be found by themselves.")
} else {
tr("Choose the database's folder — its other files will be found by themselves.")
})
.weak(),
);
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
folder = ui.button(tr("📁 Choose the database's folder")).clicked();
files = ui.button(tr("Choose the database's files")).clicked();
close = ui.button(tr("Cancel")).clicked();
});
}
}
});
if close || modal.should_close() {
self.web_notice = None;
}
if folder {
self.web_notice = None;
self.pick_database_folder(ctx);
}
if files {
self.web_notice = None;
self.pick_databases(ctx);
}
}
#[cfg(web)]
fn pick_database_folder(&self, ctx: &egui::Context) {
let (tx, ctx) = (self.tx.clone(), ctx.clone());
crate::platform::files::pick_database_folder(move |picked| {
send_picked(&tx, picked);
ctx.request_repaint();
});
}
/// The open game's PGN, downloaded as a file named after the game.
@ -3261,6 +3410,8 @@ impl eframe::App for App {
}
self.offer_events(&ctx);
self.page_frame(&ctx);
#[cfg(web)]
self.web_notice(&ctx);
self.debug_step(&ctx);
self.debug_keys(&ctx);
self.debug_screenshot(&ctx);
@ -3591,7 +3742,7 @@ impl eframe::App for App {
self.toast = Some(Toast {
text: trf(
"Removed from the shelf; the file stays: {path}",
&[("path", &p.display())],
&[("path", &crate::platform::files::shown(&p))],
),
until: ctx.input(|i| i.time) + 6.0,
undo: false,
@ -3611,6 +3762,11 @@ impl eframe::App for App {
self.choosing_again = Some(p);
self.pick_databases(&ctx);
}
#[cfg(web)]
LibraryAction::ChooseFolderAgain(p) => {
self.choosing_again = Some(p);
self.pick_database_folder(&ctx);
}
LibraryAction::KeepCopy(p) => self.keep_copy(&ctx, p),
LibraryAction::OpenSettings => self.settings_ui.open = true,
LibraryAction::NewDatabase => {
@ -3827,8 +3983,17 @@ fn send_picked(tx: &Sender<Async>, picked: crate::platform::files::Picked) {
if !picked.paths.is_empty() {
let _ = tx.send(Async::DatabasesPicked(picked.paths));
}
if !picked.too_big.is_empty() {
let _ = tx.send(Async::TooBig(picked.too_big));
#[cfg(web)]
{
if !picked.too_big.is_empty() {
let _ = tx.send(Async::TooBig(picked.too_big));
}
if !picked.incomplete.is_empty() {
let _ = tx.send(Async::Incomplete(picked.incomplete));
}
if picked.empty_folder {
let _ = tx.send(Async::EmptyFolder);
}
}
}

View file

@ -217,6 +217,105 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String {
// Uzbek o‘ and g‘ are written with ‘ (U+2018): the interface font has no U+02BB.
const ROWS: &[[&str; 9]] = &[
// --- the web version ---
[
"This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.",
"База слишком большая для браузера ({size}, предел {limit}). Извините — откройте её в программе для компьютера.",
"Cette base est trop grande pour le navigateur ({size}, la limite est de {limit}). Désolé — ouvrez-la dans le programme pour ordinateur.",
"Diese Datenbank ist zu groß für den Browser ({size}, die Grenze liegt bei {limit}). Entschuldigung – öffnen Sie sie im Programm für den Computer.",
"Esta base es demasiado grande para el navegador ({size}, el límite es {limit}). Lo sentimos: ábrela en el programa para ordenador.",
"Questo database è troppo grande per il browser ({size}, il limite è {limit}). Ci dispiace: aprilo nel programma per computer.",
"Esta base é grande demais para o navegador ({size}, o limite é {limit}). Desculpe — abra no programa para computador.",
"Bu baza brauzer uchun juda katta ({size}, chegara {limit}). Kechirasiz — uni kompyuter dasturida oching.",
"Бұл база браузер үшін тым үлкен ({size}, шегі {limit}). Кешіріңіз — оны компьютерге арналған бағдарламада ашыңыз.",
],
[
"Download ChessPenguin for the computer",
"Скачать ChessPenguin для компьютера",
"Télécharger ChessPenguin pour ordinateur",
"ChessPenguin für den Computer herunterladen",
"Descargar ChessPenguin para ordenador",
"Scarica ChessPenguin per computer",
"Baixar o ChessPenguin para computador",
"ChessPenguin’ni kompyuter uchun yuklab olish",
"ChessPenguin-ді компьютерге жүктеп алу",
],
[
"A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.",
"База ChessBase состоит из нескольких файлов (.cbh, .cbg, .cba…). Выберите её папку или сразу все её файлы.",
"Une base ChessBase se compose de plusieurs fichiers (.cbh, .cbg, .cba…). Choisissez son dossier ou tous ses fichiers à la fois.",
"Eine ChessBase-Datenbank besteht aus mehreren Dateien (.cbh, .cbg, .cba…). Wählen Sie ihren Ordner oder alle ihre Dateien auf einmal.",
"Una base de ChessBase consta de varios archivos (.cbh, .cbg, .cba…). Elige su carpeta o todos sus archivos a la vez.",
"Un database ChessBase è composto da più file (.cbh, .cbg, .cba…). Scegli la sua cartella o tutti i suoi file insieme.",
"Uma base do ChessBase é formada por vários arquivos (.cbh, .cbg, .cba…). Escolha a pasta dela ou todos os arquivos de uma vez.",
"ChessBase bazasi bir nechta fayldan iborat (.cbh, .cbg, .cba…). Uning papkasini yoki barcha fayllarini birdaniga tanlang.",
"ChessBase базасы бірнеше файлдан тұрады (.cbh, .cbg, .cba…). Оның қалтасын немесе барлық файлдарын бірден таңдаңыз.",
],
[
"Allow access to the database's folder — its other files will be found by themselves.",
"Разрешите доступ к папке базы — остальные файлы базы найдутся сами.",
"Autorisez l'accès au dossier de la base — ses autres fichiers seront trouvés automatiquement.",
"Erlauben Sie den Zugriff auf den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.",
"Permite el acceso a la carpeta de la base: sus demás archivos se encontrarán solos.",
"Consenti l'accesso alla cartella del database: gli altri suoi file verranno trovati da soli.",
"Permita o acesso à pasta da base — os outros arquivos dela serão encontrados sozinhos.",
"Baza papkasiga ruxsat bering — uning qolgan fayllari o‘zi topiladi.",
"База қалтасына рұқсат беріңіз — оның қалған файлдары өздігінен табылады.",
],
[
"Choose the database's folder — its other files will be found by themselves.",
"Выберите папку базы — остальные файлы базы найдутся сами.",
"Choisissez le dossier de la base — ses autres fichiers seront trouvés automatiquement.",
"Wählen Sie den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.",
"Elige la carpeta de la base: sus demás archivos se encontrarán solos.",
"Scegli la cartella del database: gli altri suoi file verranno trovati da soli.",
"Escolha a pasta da base — os outros arquivos dela serão encontrados sozinhos.",
"Baza papkasini tanlang — uning qolgan fayllari o‘zi topiladi.",
"База қалтасын таңдаңыз — оның қалған файлдары өздігінен табылады.",
],
[
"📁 Choose the database's folder",
"📁 Выбрать папку базы",
"📁 Choisir le dossier de la base",
"📁 Ordner der Datenbank wählen",
"📁 Elegir la carpeta de la base",
"📁 Scegli la cartella del database",
"📁 Escolher a pasta da base",
"📁 Baza papkasini tanlash",
"📁 База қалтасын таңдау",
],
[
"Choose the database's files",
"Выбрать файлы базы",
"Choisir les fichiers de la base",
"Dateien der Datenbank wählen",
"Elegir los archivos de la base",
"Scegli i file del database",
"Escolher os arquivos da base",
"Baza fayllarini tanlash",
"База файлдарын таңдау",
],
[
"There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z).",
"В этой папке нет базы (.pgn, .cbh, .cbv, .zip, .7z).",
"Ce dossier ne contient aucune base (.pgn, .cbh, .cbv, .zip, .7z).",
"In diesem Ordner gibt es keine Datenbank (.pgn, .cbh, .cbv, .zip, .7z).",
"En esta carpeta no hay ninguna base (.pgn, .cbh, .cbv, .zip, .7z).",
"In questa cartella non c'è nessun database (.pgn, .cbh, .cbv, .zip, .7z).",
"Não há nenhuma base nesta pasta (.pgn, .cbh, .cbv, .zip, .7z).",
"Bu papkada baza yo‘q (.pgn, .cbh, .cbv, .zip, .7z).",
"Бұл қалтада база жоқ (.pgn, .cbh, .cbv, .zip, .7z).",
],
[
"The browser doesn't have enough memory for this database. Open it in the desktop program.",
"Браузеру не хватает памяти для этой базы. Откройте её в программе для компьютера.",
"Le navigateur n'a pas assez de mémoire pour cette base. Ouvrez-la dans le programme pour ordinateur.",
"Dem Browser fehlt der Speicher für diese Datenbank. Öffnen Sie sie im Programm für den Computer.",
"Al navegador le falta memoria para esta base. Ábrela en el programa para ordenador.",
"Al browser manca la memoria per questo database. Aprilo nel programma per computer.",
"O navegador não tem memória suficiente para esta base. Abra no programa para computador.",
"Brauzerda bu baza uchun xotira yetmaydi. Uni kompyuter dasturida oching.",
"Браузерге бұл база үшін жад жетпейді. Оны компьютерге арналған бағдарламада ашыңыз.",
],
[
"A dropped file is not remembered: after a reload, choose the file again or keep a copy in the browser.",
"Перетащенный файл не запоминается: после перезагрузки выберите его снова или сохраните копию в браузере.",
@ -327,17 +426,6 @@ const ROWS: &[[&str; 9]] = &[
"Sig‘maydi: nusxaga {need} kerak, brauzer esa saytga yana {free} beradi. «Brauzerdagi ma’lumotlar»da joy bo‘shating yoki faylni diskdan oching.",
"Сыймайды: көшірмеге {need} керек, ал браузер сайтқа тағы {free} береді. «Браузердегі деректер» бөлімінде орын босатыңыз немесе файлды дисктен ашыңыз.",
],
[
"This database is too big for the web version ({size}). Open it in the desktop program — it has no such limit.",
"Эта база слишком большая для веб-версии ({size}). Откройте её в программе для компьютера — там нет такого предела.",
"Cette base est trop grande pour la version web ({size}). Ouvrez-la dans le programme pour ordinateur — il n'a pas cette limite.",
"Diese Datenbank ist zu groß für die Web-Version ({size}). Öffnen Sie sie im Programm für den Computer – dort gibt es diese Grenze nicht.",
"Esta base es demasiado grande para la versión web ({size}). Ábrela en el programa para ordenador, que no tiene ese límite.",
"Questo database è troppo grande per la versione web ({size}). Aprilo nel programma per computer: lì non c'è questo limite.",
"Esta base é grande demais para a versão web ({size}). Abra no programa para computador — lá não há esse limite.",
"Bu baza veb-versiya uchun juda katta ({size}). Uni kompyuter dasturida oching — u yerda bunday cheklov yo‘q.",
"Бұл база веб-нұсқа үшін тым үлкен ({size}). Оны компьютерге арналған бағдарламада ашыңыз — онда мұндай шек жоқ.",
],
[
"My games",
"Мои партии",

View file

@ -1701,7 +1701,7 @@ impl LargeView {
.weak(),
);
ui.add_space(6.0);
ui.label(RichText::new(trf("File: {path}", &[("path", &path.display())])).weak());
ui.label(RichText::new(trf("File: {path}", &[("path", &crate::platform::files::shown(path))])).weak());
});
return open_notes;
}

View file

@ -94,12 +94,17 @@ 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`).
/// The page's reader (`import-worker.js`, a worker with an instance of its own): takes
/// the files of a database one by one ([`reader_give`]), reads it 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)
pub fn reader_give(name: String, bytes: Vec<u8>) {
platform::web::import::give(name, bytes);
}
#[cfg(web)]
pub fn reader_read(count: bool) -> wasm_bindgen::JsValue {
platform::web::import::answer(count)
}
/// The desktop program: `chesspenguin [--bench <database> [report.txt]]`.

View file

@ -63,6 +63,9 @@ pub enum LibraryAction {
/// Let the page read the remembered file again (the browser asks the user).
#[cfg(web)]
AllowReading(PathBuf),
/// Choose the folder of the ChessBase database whose `.cbh` alone is there.
#[cfg(web)]
ChooseFolderAgain(PathBuf),
/// Keep a copy of a file in the browser (it opens then without choosing it).
KeepCopy(PathBuf),
OpenSettings,
@ -1099,6 +1102,9 @@ impl Library {
});
trf("loading… {n}", &[("n", &p.games)])
}
Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(path) => {
tr("📁 Choose the database's folder").into()
}
Some(Slot::Failed(_)) | None if crate::platform::files::waiting_to_read(path) => {
tr("🔒 Allow reading").into()
}
@ -1170,9 +1176,9 @@ impl Library {
&[("name", name)],
)
};
resp.on_hover_text(format!("{whose}\n{}", path.display()))
resp.on_hover_text(format!("{whose}\n{}", crate::platform::files::shown(path)))
}
None => resp.on_hover_text(path.display().to_string()),
None => resp.on_hover_text(crate::platform::files::shown(path)),
};
if resp.clicked() {
self.select_db(path, ui.ctx());
@ -1268,7 +1274,10 @@ impl Library {
ui.add_space(40.0);
ui.label(trf(
"Reading {path} — games found: {n}",
&[("path", &path.display()), ("n", &p.games)],
&[
("path", &crate::platform::files::shown(&path)),
("n", &p.games),
],
));
ui.add(egui::ProgressBar::new(frac).desired_width(400.0));
if ui.button(tr("Cancel")).clicked() {
@ -1278,6 +1287,30 @@ impl Library {
return;
}
#[cfg(web)]
Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(&path) => {
// A ChessBase database's .cbh without its other files (one chosen
// alone at an earlier visit): its folder or all its files.
ui.vertical_centered(|ui| {
ui.add_space(40.0);
ui.label(tr(
"A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.",
));
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui.button(tr("📁 Choose the database's folder")).clicked() {
actions.push(LibraryAction::ChooseFolderAgain(path.clone()));
}
if ui.button(tr("Choose the database's files")).clicked() {
actions.push(LibraryAction::ChooseAgain(path.clone()));
}
if ui.button(tr("Remove from list")).clicked() {
actions.push(LibraryAction::RemoveDatabase(path.clone()));
}
});
});
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.
@ -1329,7 +1362,7 @@ impl Library {
ui.label(
RichText::new(trf(
"Could not open {path}: {e}",
&[("path", &path.display()), ("e", &e)],
&[("path", &crate::platform::files::shown(&path)), ("e", &e)],
))
.color(ui.visuals().error_fg_color),
);
@ -1439,6 +1472,17 @@ fn import_error(e: &ImportError) -> String {
"The ChessBase 2CBH format is not supported: export the database from ChessBase as CBH or PGN",
)
.into(),
ImportError::Unsupported(Unsupported::ChessBaseFiles) => tr(
"A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.",
)
.into(),
ImportError::Io { source, .. } if source.kind() == std::io::ErrorKind::OutOfMemory => tr(
"The browser doesn't have enough memory for this database. Open it in the desktop program.",
)
.into(),
// A browser's places of files mean nothing to the user: only what happened.
#[cfg(web)]
ImportError::Io { source, .. } => source.to_string(),
e => e.to_string(),
}
}

View file

@ -12,16 +12,87 @@ const DATABASES: [&str; 10] = [
"pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z",
];
/// Files a browser does not open: larger than this (decisions «Веб-версия»: a warning
/// above 1 GB — the program for the computer opens them).
pub const TOO_BIG: u64 = 1 << 30;
/// Databases a browser does not open: their files together larger than this (the
/// program for the computer opens them).
pub const TOO_BIG: u64 = 2_000_000_000;
/// What the user chose or dropped: the databases to open, and the files left out
/// because they are too big for a browser (name, bytes).
/// What the user chose or dropped: the databases to open, the ones left out because
/// they are too big for a browser (name, bytes of their files), the ChessBase
/// databases not all files of which were given (the name of their `.cbh`), and
/// whether a chosen folder held no database.
#[derive(Default)]
pub struct Picked {
pub paths: Vec<PathBuf>,
pub too_big: Vec<(String, u64)>,
pub incomplete: Vec<String>,
pub empty_folder: bool,
}
/// The files the user gave the page, made databases: the ChessBase ones of their
/// several files (`chess_import::group_chosen`), each kept for the session in a folder
/// of its own. Also the files of each database kept (its path, their places in
/// `files`), for the browser to remember.
#[cfg(web)]
pub(super) fn gather(
files: &[web_sys::File],
folder: bool,
) -> (Picked, Vec<(PathBuf, Vec<usize>)>) {
let names: Vec<String> = files.iter().map(|f| f.name()).collect();
let refs: Vec<&str> = names.iter().map(String::as_str).collect();
let chosen = chess_import::group_chosen(&refs, folder);
let mut picked = Picked {
incomplete: chosen.incomplete,
..Picked::default()
};
let mut kept = Vec::new();
for db in chosen.databases {
let size: u64 = db.iter().map(|&i| files[i].size() as u64).sum();
if size > TOO_BIG {
picked.too_big.push((names[db[0]].clone(), size));
continue;
}
let path = super::web::vfs::add_opened(db.iter().map(|&i| files[i].clone()).collect());
picked.paths.push(path.clone());
kept.push((path, db));
}
picked.empty_folder = folder
&& picked.paths.is_empty()
&& picked.too_big.is_empty()
&& picked.incomplete.is_empty();
(picked, kept)
}
/// A ChessBase database's `.cbh` given without the files it cannot be read without
/// (a browser has only the files the user gave it).
pub fn chessbase_incomplete(path: &std::path::Path) -> bool {
#[cfg(web)]
{
let cbh = path
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("cbh"));
cbh && super::web::vfs::database_files(path).is_ok_and(|files| {
!files
.iter()
.any(|(name, _)| name.to_lowercase().ends_with(".cbg"))
})
}
#[cfg(not(web))]
{
let _ = path;
false
}
}
/// How the user's file `path` is named to the user: on a computer its path, in a
/// browser its name (the page's own places, `/opened/…`, mean nothing to the user).
pub fn shown(path: &std::path::Path) -> String {
#[cfg(web)]
return path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
#[cfg(not(web))]
path.display().to_string()
}
/// A file the browser holds for this visit only (one the user chose or dropped): after
@ -36,36 +107,53 @@ pub fn session_only(path: &std::path::Path) -> bool {
}
}
/// Keeps a copy of the session file `path` in the browser's storage, where it stays
/// between visits; the copy's path. Refused when the browser gives the site too little
/// room (the size and what is free, for the message).
/// Keeps a copy of the session database `path` (all its files) in the browser's
/// storage, where it stays between visits; `then` gets the copy's path. Refused when
/// the browser gives the site too little room (the size and what is free, for the
/// message).
#[cfg(web)]
pub fn keep_copy(path: &std::path::Path) -> Result<PathBuf, KeepCopy> {
let bytes = super::fs::read(path).map_err(|e| KeepCopy::Failed(e.to_string()))?;
let need = bytes.len() as u64;
pub fn keep_copy(path: &std::path::Path, then: impl FnOnce(Result<PathBuf, KeepCopy>) + 'static) {
use wasm_bindgen::JsCast;
let parts = match super::web::vfs::database_files(path) {
Ok(p) => p,
Err(e) => return then(Err(KeepCopy::Failed(e.to_string()))),
};
let need: u64 = parts
.iter()
.map(|(_, s)| match s.dyn_ref::<web_sys::Blob>() {
Some(b) => b.size() as u64,
None => js_sys::Reflect::get(s, &"length".into())
.ok()
.and_then(|l| l.as_f64())
.unwrap_or(0.0) as u64,
})
.sum();
if let Some(free) = super::storage_free()
&& need + need / 10 > free
{
return Err(KeepCopy::NoRoom { need, free });
return then(Err(KeepCopy::NoRoom { need, free }));
}
let name = path.file_name().map(|n| n.to_owned()).unwrap_or_default();
let dir = super::data_dir().unwrap_or_default().join("copies");
let mut copy = dir.join(&name);
let mut n = 1;
while super::fs::exists(&copy) {
n += 1;
let stem = std::path::Path::new(&name)
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let ext = std::path::Path::new(&name)
.extension()
.map(|e| e.to_string_lossy().into_owned())
.unwrap_or_default();
copy = dir.join(format!("{stem} ({n}).{ext}"));
}
super::fs::write_atomic(&copy, &bytes).map_err(|e| KeepCopy::Failed(e.to_string()))?;
Ok(copy)
// A folder of its own, as the database had: the names stay as they were.
let dir = super::data_dir()
.unwrap_or_default()
.join("copies")
.join((js_sys::Date::now() as u64).to_string());
let first = dir.join(&parts[0].0);
wasm_bindgen_futures::spawn_local(async move {
for (name, source) in parts {
let bytes = match source.dyn_into::<web_sys::Blob>() {
Ok(blob) => match wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await {
Ok(buf) => js_sys::Uint8Array::new(&buf).to_vec(),
Err(e) => return then(Err(KeepCopy::Failed(format!("{e:?}")))),
},
Err(array) => js_sys::Uint8Array::new(&array).to_vec(),
};
if let Err(e) = super::fs::write_atomic(&dir.join(name), &bytes) {
return then(Err(KeepCopy::Failed(e.to_string())));
}
}
then(Ok(first));
});
}
/// Why no copy was kept.
@ -92,7 +180,7 @@ pub fn pick_databases(then: impl FnOnce(Picked) + Send + 'static) {
.pick_files();
then(Picked {
paths: picked.unwrap_or_default(),
too_big: Vec::new(),
..Picked::default()
});
});
}
@ -104,15 +192,26 @@ pub fn pick_databases(then: impl FnOnce(Picked) + Send + 'static) {
.map(|e| format!(".{e}"))
.collect();
if super::web::remembered::supported() {
super::web::remembered::pick(&extensions, move |paths, too_big| {
then(Picked { paths, too_big })
});
super::web::remembered::pick(&extensions, then);
} else {
super::web::page::pick_files(&extensions.join(","), move |files| then(opened(files)));
super::web::page::pick_files(&extensions.join(","), move |files| {
then(gather(&files, false).0)
});
}
}
}
/// Asks the user for a database's folder (a ChessBase database is several files): its
/// databases are found by their files' names. Chrome and Edge remember the folder.
#[cfg(web)]
pub fn pick_database_folder(then: impl FnOnce(Picked) + Send + 'static) {
if super::web::remembered::supported_folder() {
super::web::remembered::pick_folder(then);
} else {
super::web::page::pick_folder(move |files| then(gather(&files, true).0));
}
}
/// The browser remembers the files chosen in its dialog for the next visit (Chrome,
/// Edge); the others, and a computer, have no need or no way.
pub fn remembers_chosen() -> bool {
@ -169,22 +268,7 @@ pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Picked) + Send + 'sta
if files.is_empty() {
return;
}
wasm_bindgen_futures::spawn_local(async move {
then(opened(super::web::page::read_files(files).await));
});
}
}
/// The files read, kept for the session.
#[cfg(web)]
fn opened(files: super::web::page::Read) -> Picked {
Picked {
paths: files
.read
.into_iter()
.map(|(name, bytes)| super::web::vfs::add_opened(&name, bytes))
.collect(),
too_big: files.too_big,
then(gather(&files, false).0);
}
}

View file

@ -35,6 +35,7 @@ enum Failure {
Corrupt(String),
Encrypted,
ChessBase2,
ChessBaseFiles,
Empty,
Cancelled,
}
@ -46,6 +47,7 @@ impl Failure {
ImportError::Corrupt(s) => Failure::Corrupt(s),
ImportError::Unsupported(Unsupported::Encrypted) => Failure::Encrypted,
ImportError::Unsupported(Unsupported::ChessBase2) => Failure::ChessBase2,
ImportError::Unsupported(Unsupported::ChessBaseFiles) => Failure::ChessBaseFiles,
ImportError::Empty => Failure::Empty,
ImportError::Cancelled => Failure::Cancelled,
}
@ -57,6 +59,7 @@ impl Failure {
Failure::Corrupt(s) => ImportError::Corrupt(s),
Failure::Encrypted => ImportError::Unsupported(Unsupported::Encrypted),
Failure::ChessBase2 => ImportError::Unsupported(Unsupported::ChessBase2),
Failure::ChessBaseFiles => ImportError::Unsupported(Unsupported::ChessBaseFiles),
Failure::Empty => ImportError::Empty,
Failure::Cancelled => ImportError::Cancelled,
}
@ -74,13 +77,44 @@ 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}`
thread_local! {
/// The worker's side: the files of the database being given, one by one (so that
/// the worker holds each file's bytes once: in the program, not also in the page's
/// script).
static GIVEN: RefCell<Vec<(String, Vec<u8>)>> = const { RefCell::new(Vec::new()) };
}
/// The worker's side: one more file of the database to read (its own file first).
pub fn give(name: String, bytes: Vec<u8>) {
// The reader's panics to the console (the page's own hook is eframe's).
static HOOK: std::sync::Once = std::sync::Once::new();
HOOK.call_once(|| {
std::panic::set_hook(Box::new(|info| {
web_sys::console::error_1(&format!("the reader: {info}").into());
}));
});
GIVEN.with_borrow_mut(|g| g.push((name, bytes)));
}
/// The worker's side: reads the database given ([`give`]). 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 {
pub fn answer(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| {
let mut files = GIVEN.with_borrow_mut(std::mem::take);
if files.is_empty() {
files.push((String::new(), Vec::new()));
}
let name = files[0].0.clone();
let chessbase = name.to_lowercase().ends_with(".cbh");
let opened = if chessbase {
chess_import::open_chessbase_owned(&name, files, &mut |_| {}, &never)
} else {
let bytes = files.swap_remove(0).1;
chess_import::open_bytes(&name, bytes, &mut |_| {}, &never)
};
let read = opened.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()));
@ -115,6 +149,16 @@ enum Waiting {
}
impl Waiting {
fn out_of_memory(self) {
match self {
Waiting::Open(path, done) => done(Err(ImportError::Io {
path,
source: std::io::Error::from(std::io::ErrorKind::OutOfMemory),
})),
Waiting::Count(done) => done(None),
}
}
fn failed(self, e: impl ToString) {
match self {
Waiting::Open(path, done) => done(Err(io_error(&path, e))),
@ -133,6 +177,23 @@ thread_local! {
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;
if let Some(e) = get("crashed").as_string() {
// The worker's program stopped (out of its memory, most likely: a browser gives
// a page at most 4 GB): this database cannot be read here; the others waiting
// go to a new worker's program — they fail too, to be opened again.
log::warn!("the reader stopped: {e}");
if let Some(w) = WORKER.with_borrow_mut(Option::take) {
w.terminate();
}
for (n, waiting) in WAITING.with_borrow_mut(std::mem::take) {
if n == id {
waiting.out_of_memory();
} else {
waiting.failed(&e);
}
}
return;
}
let (path, done) = match WAITING.with_borrow_mut(|w| w.remove(&id)) {
Some(Waiting::Open(path, done)) => (path, done),
Some(Waiting::Count(done)) => {
@ -160,8 +221,14 @@ fn answered(data: JsValue) {
)));
return;
};
let db = PgnDatabase::from_index(text, read.index);
log::info!(
"database read: {} ({} games)",
path.file_name().unwrap_or_default().to_string_lossy(),
db.len()
);
done(Ok(Opened {
db: Database::Pgn(PgnDb::new(PgnDatabase::from_index(text, read.index))),
db: Database::Pgn(PgnDb::new(db)),
format: Format::ALL.get(read.format).copied().unwrap_or(Format::Pgn),
notes: read.notes,
}))
@ -211,32 +278,36 @@ pub fn count(path: &Path, done: impl FnOnce(Option<usize>) + 'static) {
}
fn ask(path: &Path, count: bool, waiting: Waiting) {
let bytes = match super::vfs::read(path) {
Ok(b) => b,
let files = match super::vfs::database_files(path) {
Ok(f) => f,
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 names = js_sys::Array::new();
let parts = js_sys::Array::new();
// The bytes the page holds go over without a copy; the user's files are the
// browser's, read by the worker.
let transfer = js_sys::Array::new();
for (name, source) in files {
names.push(&JsValue::from_str(&name));
if let Some(array) = source.dyn_ref::<js_sys::Uint8Array>() {
transfer.push(&array.buffer());
}
parts.push(&source);
}
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, "names", &names);
set(&message, "parts", &parts);
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))
{

View file

@ -5,8 +5,12 @@ use std::cell::RefCell;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
/// The element through which files are chosen (one for the page; checks give it files).
/// The elements through which files and a folder are chosen (one each for the page;
/// checks give them files).
pub const OPEN_INPUT_ID: &str = "cp-open-files";
pub const OPEN_FOLDER_ID: &str = "cp-open-folder";
/// The program's canvas (`page/index.html`).
const CANVAS_ID: &str = "cp-canvas";
fn document() -> Option<web_sys::Document> {
web_sys::window()?.document()
@ -22,32 +26,30 @@ pub async fn next_task() {
let _ = wasm_bindgen_futures::JsFuture::from(promise).await;
}
type Picked = Box<dyn FnOnce(Read)>;
/// Files read: their names and contents, and the ones too big to read (name, bytes).
pub struct Read {
pub read: Vec<(String, Vec<u8>)>,
pub too_big: Vec<(String, u64)>,
}
type Picked = Box<dyn FnOnce(Vec<web_sys::File>)>;
thread_local! {
/// What to do with the files chosen next.
static ON_PICKED: RefCell<Option<Picked>> = const { RefCell::new(None) };
}
/// The page's file input, made once: hidden, several files, `accept` the extensions.
fn open_input(accept: &str) -> Result<web_sys::HtmlInputElement, JsValue> {
/// The page's file input `id`, made once: hidden, several files, `accept` the
/// extensions; `folder`: it chooses a folder (`webkitdirectory`, every browser has it).
fn open_input(id: &str, accept: &str, folder: bool) -> Result<web_sys::HtmlInputElement, JsValue> {
let doc = document().ok_or("no document")?;
if let Some(el) = doc.get_element_by_id(OPEN_INPUT_ID) {
if let Some(el) = doc.get_element_by_id(id) {
let input: web_sys::HtmlInputElement = el.dyn_into()?;
input.set_accept(accept);
return Ok(input);
}
let input: web_sys::HtmlInputElement = doc.create_element("input")?.dyn_into()?;
input.set_id(OPEN_INPUT_ID);
input.set_id(id);
input.set_type("file");
input.set_multiple(true);
input.set_accept(accept);
if folder {
input.set_attribute("webkitdirectory", "")?;
}
input.style().set_property("display", "none")?;
let on_change = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
let Some(input) = ev
@ -62,12 +64,30 @@ fn open_input(accept: &str) -> Result<web_sys::HtmlInputElement, JsValue> {
.unwrap_or_default();
// The same file chosen again is a change too.
input.set_value("");
let Some(then) = ON_PICKED.with_borrow_mut(Option::take) else {
return;
// The keys go to the program again, not to the hidden input.
if let Some(canvas) = document()
.and_then(|d| d.get_element_by_id(CANVAS_ID))
.and_then(|c| c.dyn_into::<web_sys::HtmlElement>().ok())
{
let _ = canvas.focus();
}
let files = if folder {
// The folder's own files: a database's folder, not what is below it.
files
.into_iter()
.filter(|f| {
js_sys::Reflect::get(f, &"webkitRelativePath".into())
.ok()
.and_then(|p| p.as_string())
.is_none_or(|p| p.matches('/').count() <= 1)
})
.collect()
} else {
files
};
wasm_bindgen_futures::spawn_local(async move {
then(read_files(files).await);
});
if let Some(then) = ON_PICKED.with_borrow_mut(Option::take) {
then(files);
}
});
input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref())?;
// The input lives as long as the page.
@ -76,34 +96,21 @@ fn open_input(accept: &str) -> Result<web_sys::HtmlInputElement, JsValue> {
Ok(input)
}
/// The contents of `files`, with their names (a file that cannot be read is left
/// out; one larger than [`crate::platform::files::TOO_BIG`] is not read).
pub async fn read_files(files: Vec<web_sys::File>) -> Read {
let mut out = Read {
read: Vec::with_capacity(files.len()),
too_big: Vec::new(),
};
for f in files {
let size = f.size() as u64;
if size > crate::platform::files::TOO_BIG {
out.too_big.push((f.name(), size));
continue;
}
match wasm_bindgen_futures::JsFuture::from(f.array_buffer()).await {
Ok(buf) => out
.read
.push((f.name(), js_sys::Uint8Array::new(&buf).to_vec())),
Err(e) => log::warn!("cannot read {}: {e:?}", f.name()),
}
}
out
/// Asks the user for files (the browser's dialog); `then` gets them once chosen (not
/// read: the page's reader reads them). Must run soon after the user's click or key (a
/// browser opens the dialog only then: egui handles input in the next frame, well
/// within that time).
pub fn pick_files(accept: &str, then: impl FnOnce(Vec<web_sys::File>) + 'static) {
pick(OPEN_INPUT_ID, accept, false, then);
}
/// Asks the user for files (the browser's dialog); `then` gets their contents once
/// chosen. Must run soon after the user's click or key (a browser opens the dialog
/// only then: egui handles input in the next frame, well within that time).
pub fn pick_files(accept: &str, then: impl FnOnce(Read) + 'static) {
match open_input(accept) {
/// Asks the user for a folder; `then` gets the files right in it.
pub fn pick_folder(then: impl FnOnce(Vec<web_sys::File>) + 'static) {
pick(OPEN_FOLDER_ID, "", true, then);
}
fn pick(id: &str, accept: &str, folder: bool, then: impl FnOnce(Vec<web_sys::File>) + 'static) {
match open_input(id, accept, folder) {
Ok(input) => {
ON_PICKED.with_borrow_mut(|p| *p = Some(Box::new(then)));
input.click();

View file

@ -1,10 +1,15 @@
//! 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`]).
//! Databases a Chromium browser remembers (Chrome, Edge: the File System Access API):
//! files chosen through `showOpenFilePicker`, or a database's folder chosen through
//! `showDirectoryPicker`, leave handles the page keeps in the browser's storage; at the
//! next visit the database is there again through them — at once when the browser still
//! allows reading, 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`]).
//!
//! What is kept for a database (its path on the page): `{handles: [file handles]}`, its
//! own file first, or `{dir: folder handle, names: [its files' names]}`; a bare file
//! handle (an earlier version) is a database of one file.
use std::cell::RefCell;
use std::collections::HashMap;
@ -13,28 +18,39 @@ use std::path::{Path, PathBuf};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use super::page::Read;
use crate::platform::files::{Picked, gather};
thread_local! {
/// Files of earlier visits the browser asks about first: the page's path, the handle.
/// Databases of earlier visits the browser asks about first: the page's path, what
/// is kept for it.
static WAITING: RefCell<HashMap<PathBuf, JsValue>> = RefCell::new(HashMap::new());
/// The handle of a `.cbh` chosen alone: the folder's dialog opens where it is.
static LONE_CBH: RefCell<Option<JsValue>> = const { RefCell::new(None) };
}
fn get(object: &JsValue, key: &str) -> JsValue {
js_sys::Reflect::get(object, &key.into()).unwrap_or(JsValue::UNDEFINED)
}
fn set(object: &JsValue, key: &str, value: &JsValue) {
let _ = js_sys::Reflect::set(object, &key.into(), value);
}
/// Calls `object.method(arg)` (its promise, not awaited): within the user's gesture.
fn start(object: &JsValue, method: &str, arg: &JsValue) -> Result<js_sys::Promise, JsValue> {
let f: js_sys::Function = get(object, method).dyn_into()?;
f.call1(object, arg)?.dyn_into()
}
/// 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
wasm_bindgen_futures::JsFuture::from(start(object, method, arg)?).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());
set(&o, "mode", &"read".into());
o.into()
}
@ -43,153 +59,247 @@ 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)
/// The browser remembers a chosen folder (it has `showDirectoryPicker`).
pub fn supported_folder() -> bool {
web_sys::window().is_some_and(|w| get(&w, "showDirectoryPicker").is_function())
}
async fn file_of(handle: &JsValue) -> Result<web_sys::File, JsValue> {
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()))
.dyn_into()
}
/// Opens a dialog of the window (`showOpenFilePicker`, `showDirectoryPicker`) now,
/// within the user's gesture.
fn dialog(method: &str, options: &js_sys::Object) -> Result<js_sys::Promise, JsValue> {
let window = web_sys::window().ok_or("no window")?;
start(&window, method, options)
}
/// 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
/// gets the databases they make, 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();
pub fn pick(extensions: &[String], then: impl FnOnce(Picked) + 'static) {
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);
set(&accept, "application/octet-stream", &list);
let kind = js_sys::Object::new();
let _ = js_sys::Reflect::set(&kind, &"accept".into(), &accept);
types.push(&kind);
set(&kind, "accept", &accept);
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>());
set(&options, "multiple", &JsValue::TRUE);
set(&options, "types", &js_sys::Array::of1(&kind));
set(&options, "id", &"chesspenguin-databases".into());
let chosen = dialog("showOpenFilePicker", &options);
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),
let handles: Vec<JsValue> = match chosen {
Ok(p) => wasm_bindgen_futures::JsFuture::from(p)
.await
.and_then(|h| h.dyn_into::<js_sys::Array>())
.map(|a| a.to_vec())
.unwrap_or_default(),
Err(_) => Vec::new(),
};
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:?}"),
let mut files = Vec::new();
let mut kept_handles = Vec::new();
for h in handles {
match file_of(&h).await {
Ok(f) => {
files.push(f);
kept_handles.push(h);
}
Err(e) => log::warn!("cannot read a chosen file: {e:?}"),
}
}
then(paths, read.too_big);
let (picked, kept) = gather(&files, false);
for (path, members) in kept {
let entry = js_sys::Object::new();
let list: js_sys::Array = members.iter().map(|&i| kept_handles[i].clone()).collect();
set(&entry, "handles", &list);
super::idb::put_handle(&path.to_string_lossy(), &entry);
}
// A .cbh alone: the folder's dialog will open beside it.
let lone = picked.incomplete.first().and_then(|name| {
files
.iter()
.position(|f| f.name() == *name)
.map(|i| kept_handles[i].clone())
});
LONE_CBH.with_borrow_mut(|l| *l = lone);
then(picked);
});
}
/// 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.
/// Asks the user for a database's folder; `then` gets the databases in it (the files
/// right in it, found by their names), each remembered with the folder.
pub fn pick_folder(then: impl FnOnce(Picked) + 'static) {
let options = js_sys::Object::new();
set(&options, "id", &"chesspenguin-databases".into());
set(&options, "mode", &"read".into());
if let Some(cbh) = LONE_CBH.with_borrow_mut(Option::take) {
set(&options, "startIn", &cbh);
}
let chosen = dialog("showDirectoryPicker", &options);
wasm_bindgen_futures::spawn_local(async move {
let dir = match chosen {
Ok(p) => wasm_bindgen_futures::JsFuture::from(p).await.ok(),
Err(_) => None,
};
let Some(dir) = dir else {
return then(Picked::default());
};
let mut files = Vec::new();
if let Err(e) = folder_files(&dir, &mut files).await {
log::warn!("cannot read the folder: {e:?}");
}
let (mut picked, kept) = gather(&files, true);
for (path, members) in kept {
let entry = js_sys::Object::new();
set(&entry, "dir", &dir);
let names: js_sys::Array = members
.iter()
.map(|&i| JsValue::from_str(&files[i].name()))
.collect();
set(&entry, "names", &names);
super::idb::put_handle(&path.to_string_lossy(), &entry);
}
picked.empty_folder =
picked.paths.is_empty() && picked.too_big.is_empty() && picked.incomplete.is_empty();
then(picked);
});
}
/// The files right in the folder `dir` (its `values()`, an asynchronous iterator).
async fn folder_files(dir: &JsValue, out: &mut Vec<web_sys::File>) -> Result<(), JsValue> {
let entries = js_sys::Reflect::apply(
&get(dir, "values").dyn_into::<js_sys::Function>()?,
dir,
&js_sys::Array::new(),
)?;
loop {
let step = call(&entries, "next", &JsValue::UNDEFINED).await?;
if get(&step, "done").is_truthy() {
return Ok(());
}
let handle = get(&step, "value");
if get(&handle, "kind").as_string().as_deref() == Some("file") {
out.push(file_of(&handle).await?);
}
}
}
/// What the browser is asked to let the page read: the folder, or the files.
fn targets(kept: &JsValue) -> Vec<JsValue> {
let dir = get(kept, "dir");
if !dir.is_undefined() {
return vec![dir];
}
match get(kept, "handles").dyn_into::<js_sys::Array>() {
Ok(list) => list.to_vec(),
// A bare file handle.
Err(_) => vec![kept.clone()],
}
}
/// The database's files through what is kept for it, its own first.
async fn files_of(kept: &JsValue) -> Result<Vec<web_sys::File>, JsValue> {
let dir = get(kept, "dir");
let mut files = Vec::new();
if dir.is_undefined() {
for h in targets(kept) {
files.push(file_of(&h).await?);
}
} else {
let names: js_sys::Array = get(kept, "names").dyn_into()?;
for name in names.iter() {
files.push(file_of(&call(&dir, "getFileHandle", &name).await?).await?);
}
}
Ok(files)
}
/// Brings back the databases remembered at earlier visits that the browser still lets
/// the page read (nothing is read now: the page's reader reads them when opened); 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 {
for (path, kept) 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));
let mut granted = true;
for t in targets(&kept) {
let state = call(&t, "queryPermission", &read_mode())
.await
.ok()
.and_then(|s| s.as_string());
granted &= state.as_deref() == Some("granted");
}
if !granted {
WAITING.with_borrow_mut(|w| w.insert(path, kept));
continue;
}
match files_of(&kept).await {
Ok(files) => {
log::info!("remembered file read again: {}", path.display());
super::vfs::put_opened(&path, files);
}
Err(e) => log::warn!("a remembered file is gone: {e:?}"),
}
}
}
/// The browser remembers the file `path` and asks the user before it is read again.
/// The browser remembers the database `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.
/// after the user's click). `then`: whether the database is 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 {
let Some(kept) = 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>());
// Asked now, all within the user's gesture.
let asked: Vec<_> = targets(&kept)
.iter()
.map(|t| start(t, "requestPermission", &read_mode()))
.collect();
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()
let mut granted = true;
for a in asked {
granted &= match a {
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 files = if granted {
files_of(&kept).await.ok()
} else {
None
};
let back = bytes.is_some();
if let Some(bytes) = bytes {
let back = files.is_some();
if let Some(files) = files {
log::info!("remembered file allowed again: {}", path.display());
WAITING.with_borrow_mut(|w| w.remove(&path));
super::vfs::put_opened(&path, bytes);
super::vfs::put_opened(&path, files);
}
then(back);
});
}
/// The file `path` is no longer the library's: the browser's handle is let go.
/// The database `path` is no longer the library's: the browser's handles are 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

@ -1,6 +1,8 @@
//! The page's file tree: files by path, in memory. The program's data (`/config`,
//! `/data`, `/cache`) is written through to the browser's storage ([`super::idb`]) and
//! read from it at the start ([`load`]); the rest lives for the session.
//! read from it at the start ([`load`]); the rest lives for the session. The user's
//! files are the browser's `File`s, not their contents: the page's reader reads them
//! (`super::import`), so a database's bytes never fill the page's memory.
use std::cell::RefCell;
use std::collections::BTreeMap;
@ -19,11 +21,26 @@ pub const OPENED: &str = "/opened";
const KEPT: [&str; 3] = [CONFIG, DATA, CACHE];
struct Entry {
bytes: Vec<u8>,
content: Content,
modified_ms: u64,
readonly: bool,
}
enum Content {
Bytes(Vec<u8>),
/// A file the user gave the page: the browser reads it when asked.
File(web_sys::File),
}
impl Content {
fn len(&self) -> u64 {
match self {
Content::Bytes(b) => b.len() as u64,
Content::File(f) => f.size() as u64,
}
}
}
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; numbered from
@ -54,7 +71,7 @@ pub async fn load() {
files.insert(
PathBuf::from(path),
Entry {
bytes,
content: Content::Bytes(bytes),
modified_ms: 0,
readonly: false,
},
@ -63,12 +80,29 @@ pub async fn load() {
});
}
/// The file's bytes; a user's file is read by the page's reader instead
/// ([`source`]).
pub fn read(path: &Path) -> io::Result<Vec<u8>> {
FILES.with_borrow(
|files| match &files.get(path).ok_or_else(|| not_found(path))?.content {
Content::Bytes(b) => Ok(b.clone()),
Content::File(_) => Err(io::Error::new(
io::ErrorKind::Unsupported,
"the user's file is read by the page's reader",
)),
},
)
}
/// The file for the page's reader: its bytes (a `Uint8Array`) or the user's `File`.
pub fn source(path: &Path) -> io::Result<wasm_bindgen::JsValue> {
FILES.with_borrow(|files| {
files
.get(path)
.map(|e| e.bytes.clone())
.ok_or_else(|| not_found(path))
Ok(
match &files.get(path).ok_or_else(|| not_found(path))?.content {
Content::Bytes(b) => js_sys::Uint8Array::from(b.as_slice()).into(),
Content::File(f) => f.clone().into(),
},
)
})
}
@ -77,7 +111,7 @@ pub fn meta(path: &Path) -> io::Result<Meta> {
files
.get(path)
.map(|e| Meta {
len: e.bytes.len() as u64,
len: e.content.len(),
modified_ms: e.modified_ms,
readonly: e.readonly,
})
@ -100,7 +134,7 @@ pub fn write(path: &Path, bytes: Vec<u8>) -> io::Result<()> {
files.insert(
path.to_owned(),
Entry {
bytes,
content: Content::Bytes(bytes),
modified_ms: now_ms(),
readonly: false,
},
@ -130,30 +164,73 @@ pub fn list(dir: &Path) -> Vec<PathBuf> {
})
}
/// A file the user gave the page (chosen or dropped): kept for the session, only read.
/// Its path ends with its own name, in a folder of its own.
pub fn add_opened(name: &str, bytes: Vec<u8>) -> PathBuf {
/// A database the user gave the page (chosen, dropped, found in a chosen folder):
/// its files (its own first: a ChessBase database's `.cbh`, then its other files),
/// kept for the session, only read, in a folder of their own; the path of the first.
pub fn add_opened(files: Vec<web_sys::File>) -> PathBuf {
let n = OPENED_COUNT.with_borrow_mut(|n| {
*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);
let path = Path::new(OPENED)
.join(n.to_string())
.join(files.first().map(name_of).unwrap_or_default());
put_opened(&path, files);
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.to_owned(),
Entry {
bytes,
modified_ms: now_ms(),
readonly: true,
},
);
/// A database of an earlier visit the browser let the page read again, at its old
/// path (its other files beside it).
pub fn put_opened(path: &Path, files: Vec<web_sys::File>) {
let dir = path.parent().unwrap_or(Path::new(OPENED)).to_owned();
FILES.with_borrow_mut(|entries| {
for (i, f) in files.into_iter().enumerate() {
let at = if i == 0 {
path.to_owned()
} else {
dir.join(name_of(&f))
};
entries.insert(
at,
Entry {
content: Content::File(f),
modified_ms: now_ms(),
readonly: true,
},
);
}
});
}
/// A file's name, not a path (a browser gives no folders; this makes sure).
fn name_of(f: &web_sys::File) -> String {
let name = f.name();
name.rsplit(['/', '\\']).next().unwrap_or(&name).to_owned()
}
/// The files of the database `path` for the page's reader: (name, [`source`]); a
/// ChessBase database's `.cbh` with the files of its name beside it.
pub fn database_files(path: &Path) -> io::Result<Vec<(String, wasm_bindgen::JsValue)>> {
let name = |p: &Path| {
p.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
};
let mut out = vec![(name(path), source(path)?)];
let cbh = path
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("cbh"));
if cbh && let Some(dir) = path.parent() {
let stem = |p: &Path| {
p.file_stem()
.map(|s| s.to_string_lossy().to_lowercase())
.unwrap_or_default()
};
for p in list(dir) {
if p != path && stem(&p) == stem(path) {
out.push((name(&p), source(&p)?));
}
}
}
Ok(out)
}

View file

@ -7,9 +7,10 @@
// 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
// t.chooseFolder(dir, open): … the folder
// t.beforeLoad(js): js runs in every page loaded later, before its scripts
import { spawn } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
import { launch as launchFirefox } from './firefox.mjs';
@ -95,6 +96,15 @@ async function firefox(port) {
await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000);
await this.setFiles('cp-open-files', files);
},
// The user chooses the folder `dir` (the page's folder input, webkitdirectory).
// WebDriver gives such an input no folder in Firefox ("Is directory"): the
// folder's own files are given, as the browser would give them.
async chooseFolder(dir, open) {
await open();
await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000);
const files = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => join(dir, e.name));
await this.setFiles('cp-open-folder', files);
},
};
},
};
@ -248,6 +258,34 @@ async function chromium(port) {
})()`);
await open();
},
// The user chooses the folder `dir`: in Chromium showDirectoryPicker, its files
// put into a folder of the site's private file system (as for choose()).
async chooseFolder(dir, open) {
const picker = await this.evaluate(`typeof window.showDirectoryPicker === 'function'`);
if (!picker) {
await open();
await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000);
return this.setFiles('cp-open-folder', [dir]);
}
const given = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile())
.map((e) => ({ name: e.name, b64: readFileSync(join(dir, e.name)).toString('base64') }));
await this.evaluate(`(() => {
const given = ${JSON.stringify(given)};
window.showDirectoryPicker = async () => {
const root = await navigator.storage.getDirectory();
const d = await root.getDirectoryHandle(${JSON.stringify(basename(dir))}, { create: true });
for (const g of given) {
const h = await d.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();
}
return d;
};
return true;
})()`);
await open();
},
};
},
};

View file

@ -0,0 +1,80 @@
// ChessBase databases in the browser (several files): a .cbh chosen alone asks for its
// folder, the folder's files make the database; all its files chosen at once; one too
// big for a browser is refused politely; Chrome remembers the folder.
//
// node apps/web/check/chessbase.mjs <app-dir> <out-dir> <database-folder> [<folder-of-a-database-over-2-GB>]
//
// <database-folder>: a small ChessBase database's folder (.cbh, .cbg, …), only that
// database in it. Firefox by default, Chromium with CP_BROWSER=chromium (browser.mjs).
import { readdirSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { session } from './steps.mjs';
import { sleep } from './bidi.mjs';
const [appDir, outDir, baseDir, bigDir] = process.argv.slice(2).map((p) => p && resolve(p));
let failures = 0;
const check = (ok, what) => {
console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`);
if (!ok) failures++;
};
// «📁 Choose the database's folder» in the window about a .cbh chosen alone (1400×860).
const ADD = [155, 20];
const FOLDER = (process.env.FOLDER || '833,471').split(',').map(Number);
const s = await session(appDir, 18768);
const { t } = s;
const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot());
const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000);
const read = (name) => s.logs.filter((l) => l.includes(`database read: ${name}`));
const cbh = readdirSync(baseDir).find((n) => n.toLowerCase().endsWith('.cbh'));
const stem = cbh.slice(0, -4);
try {
await t.navigate(`${s.base}?lang=en`);
await started();
await sleep(2500);
// A .cbh alone: the window asks for the database's folder; nothing is opened yet.
await t.choose([join(baseDir, cbh)], () => t.key('o', ['ctrl']));
await sleep(2000);
await shot('cb-1-lone.png');
check(read(stem).length === 0, 'a .cbh alone is not opened');
// The folder: the database's files are found by their names.
await t.chooseFolder(baseDir, () => t.click(...FOLDER));
await sleep(4000);
await shot('cb-2-folder.png');
check(read(stem).length === 1, `the folder makes the database: ${read(stem)[0] || 'not read'}`);
// All its files chosen at once.
const all = readdirSync(baseDir).map((n) => join(baseDir, n));
// By the shelf's «+ Add database».
await t.choose(all, () => t.click(...ADD));
await sleep(4000);
await shot('cb-3-files.png');
check(read(stem).length === 2, 'all its files chosen at once make the database');
if (bigDir) {
// A database over the limit: refused before it is read, with the way to the
// desktop program.
const big = readdirSync(bigDir).find((n) => n.toLowerCase().endsWith('.cbh'));
await t.choose([join(bigDir, big)], () => t.click(...ADD));
await sleep(2000);
await t.chooseFolder(bigDir, () => t.click(...FOLDER));
await sleep(3000);
await shot('cb-4-too-big.png');
check(read(big.slice(0, -4)).length === 0, 'a database over 2 GB is not read');
}
// The next visit: Chrome reads the remembered folder's database again by itself.
await t.navigate(`${s.base}?lang=en`);
await started();
await sleep(3000);
await shot('cb-5-reloaded.png');
if (await t.evaluate(`typeof window.showDirectoryPicker === 'function'`)) {
check(s.logs.some((l) => l.includes('remembered file read again') && l.includes(cbh)), 'the folder is remembered (File System Access)');
}
} finally {
await s.stop();
}
for (const e of s.errors) console.log('console:', e);
check(s.errors.length === 0, 'no panic or error in the console');
console.log(failures ? `${failures} failed` : 'all ok');
process.exit(failures ? 1 : 0);

View file

@ -66,7 +66,7 @@ try {
await sleep(2000);
await step({ shot: 's2-6-kept.png' });
f = await files();
check([...f.keys()].some((k) => k.startsWith('/data/copies/Kept games')), 'a copy of the file is kept in the browser');
check([...f.keys()].some((k) => /^\/data\/copies\/[0-9]+\/Kept games\.pgn$/.test(k)), 'a copy of the file is kept in the browser');
}
// After a reload: «My games» and the copy are there, the other file is to be chosen again.
await step({ url: '?lang=en' });

View file

@ -1,14 +1,29 @@
// 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';
// (apps/desktop/src/platform/web/import.rs). One database at a time, in order: its files
// one by one (the user's are the browser's File objects, read here), then the reading.
import init, { reader_give, reader_read } 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);
const { id, names, parts, count } = e.data;
let answer;
try {
for (let i = 0; i < names.length; i++) {
const part = parts[i];
const bytes = part instanceof Blob ? new Uint8Array(await part.arrayBuffer()) : part;
parts[i] = null;
reader_give(names[i], bytes);
}
answer = reader_read(count);
} catch (err) {
// The program stopped (out of memory, most likely): this instance is spent.
self.postMessage({ id, crashed: String(err) });
self.close();
return;
}
answer.id = id;
self.postMessage(answer, answer.text ? [answer.text.buffer] : []);
};

View file

@ -6,11 +6,17 @@
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).
/// The reader worker's work (`page/import-worker.js`): one more file of the database
/// to read (its own file first) …
#[wasm_bindgen]
pub fn read_database(name: String, bytes: Vec<u8>, count: bool) -> JsValue {
chesspenguin_app::read_database(&name, bytes, count)
pub fn reader_give(name: String, bytes: Vec<u8>) {
chesspenguin_app::reader_give(name, bytes);
}
/// … and the database read and indexed away from the page (or only its games counted).
#[wasm_bindgen]
pub fn reader_read(count: bool) -> JsValue {
chesspenguin_app::reader_read(count)
}
/// Starts ChessPenguin in the page's canvas `canvas_id`. Resolves once the interface

View file

@ -74,37 +74,18 @@ pub fn detect_letter_substitution(bytes: &[u8], encoding: TextEncoding) -> Lette
) {
return LetterRepairDetection::default();
}
let (text, _) = encoding.decode(bytes);
let genuine_letters = text
.chars()
// The source's letters as they come, never all at once: a large file's text is
// twice its size in UTF-8, four times as `char`s (more than a browser's memory).
let chars = || source_chars(bytes, encoding);
let genuine_letters = chars()
.filter(|c| matches!(c, 'ч' | 'Ч' | 'ю' | 'Ю'))
.count();
let chars: Vec<char> = text.chars().collect();
let is_cyr =
|c: Option<&char>| c.is_some_and(|c| matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё'));
let mut sequences = 0usize;
let mut i = 0;
while i + 1 < chars.len() {
let pair = [chars[i], chars[i + 1]];
if TABLE
.iter()
.any(|(s, _)| s.chars().eq(pair.iter().copied()))
{
let before = i.checked_sub(1).and_then(|p| chars.get(p));
let after = chars.get(i + 2);
if is_cyr(before) || is_cyr(after) {
sequences += 1;
}
i += 2;
} else {
i += 1;
}
}
let markers = chars.iter().filter(|c| matches!(c, '~' | '^')).count();
let sequences = sequences(chars());
let markers = chars().filter(|c| matches!(c, '~' | '^')).count();
// Each `~~` has two markers, each `x^` one; `><` has none.
let detected = sequences >= MIN_SEQUENCES
&& genuine_letters * 50 < sequences
&& markers * 9 <= sequence_markers(&chars) * 10;
&& markers * 9 <= sequence_markers(chars()) * 10;
LetterRepairDetection {
detected,
sequences,
@ -112,20 +93,53 @@ pub fn detect_letter_substitution(bytes: &[u8], encoding: TextEncoding) -> Lette
}
}
fn sequence_markers(chars: &[char]) -> usize {
/// The letters of `bytes` in a single-byte `encoding`, decoded a piece at a time (a
/// byte is a letter: any place splits the text).
fn source_chars(bytes: &[u8], encoding: TextEncoding) -> impl Iterator<Item = char> + '_ {
bytes.chunks(1 << 20).flat_map(move |piece| {
let (text, _) = encoding.decode(piece);
text.chars().collect::<Vec<char>>()
})
}
/// The sequences of the table next to a Cyrillic letter (a pair taken is not looked at
/// again).
fn sequences(chars: impl Iterator<Item = char>) -> usize {
let is_cyr =
|c: Option<char>| c.is_some_and(|c| matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё'));
let mut chars = chars.peekable();
let mut n = 0;
let mut i = 0;
while i + 1 < chars.len() {
match (chars[i], chars[i + 1]) {
let mut before = None;
while let Some(a) = chars.next() {
let Some(&b) = chars.peek() else { break };
if TABLE.iter().any(|(s, _)| s.chars().eq([a, b])) {
chars.next();
if is_cyr(before) || is_cyr(chars.peek().copied()) {
n += 1;
}
before = Some(b);
} else {
before = Some(a);
}
}
n
}
fn sequence_markers(chars: impl Iterator<Item = char>) -> usize {
let mut chars = chars.peekable();
let mut n = 0;
while let Some(a) = chars.next() {
let Some(&b) = chars.peek() else { break };
match (a, b) {
('~', '~') => {
n += 2;
i += 2;
chars.next();
}
('o' | 'о' | 'O' | 'О', '^') => {
n += 1;
i += 2;
chars.next();
}
_ => i += 1,
_ => {}
}
}
n

View file

@ -62,6 +62,22 @@ impl Files {
Ok(files)
}
/// The database whose `.cbh` file is `cbh_name` from files given as (name, content),
/// taking the contents (others are left out).
pub fn from_owned(cbh_name: &str, members: Vec<(String, Vec<u8>)>) -> Files {
let stem = stem_of(cbh_name).to_owned();
let mut files = Files {
name: stem.rsplit('/').next().unwrap_or(&stem).to_owned(),
files: HashMap::new(),
};
for (name, data) in members {
if let Some(ext) = part_of(&name, &stem) {
files.files.insert(ext, data);
}
}
files
}
/// Picks the files of the database whose `.cbh` member is `cbh_name` from archive
/// members (`name`, bytes).
pub fn from_members<'a>(
@ -74,11 +90,7 @@ impl Files {
files: HashMap::new(),
};
for (name, data) in members {
// Names differ in case in sets copied from Windows ("Base.CBH", "base.cbg").
if let Some(ext) = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())
&& stem_of(name).to_lowercase() == stem.to_lowercase()
&& USED.contains(&ext.as_str())
{
if let Some(ext) = part_of(name, &stem) {
files.files.insert(ext, data.to_vec());
}
}
@ -100,7 +112,18 @@ impl Files {
}
/// Files the reader uses; the others (search boosters, settings, media) are ignored.
const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"];
pub const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"];
/// The files a database cannot be read without (the others hold names and comments).
pub const REQUIRED: [&str; 2] = ["cbh", "cbg"];
/// The extension of `name` when it is a file of the database `stem` the reader uses
/// (names differ in case in sets copied from Windows: "Base.CBH", "base.cbg").
fn part_of(name: &str, stem: &str) -> Option<String> {
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())?;
(stem_of(name).to_lowercase() == stem.to_lowercase() && USED.contains(&ext.as_str()))
.then_some(ext)
}
fn stem_of(name: &str) -> &str {
name.rsplit_once('.').map_or(name, |(s, _)| s)

View file

@ -66,6 +66,9 @@ pub enum Unsupported {
Encrypted,
#[error("the ChessBase 2CBH format is not supported; export the database as CBH or PGN")]
ChessBase2,
/// A ChessBase database's `.cbh` given alone: its other files are needed too.
#[error("a ChessBase database is several files: open its folder")]
ChessBaseFiles,
}
/// What a database was read from.
@ -572,11 +575,7 @@ pub fn open_bytes(
match ext.as_str() {
"cbz" => return Err(ImportError::Unsupported(Unsupported::Encrypted)),
"2cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBase2)),
"cbh" => {
return Err(ImportError::Corrupt(
"a ChessBase database is several files: open its folder".into(),
));
}
"cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBaseFiles)),
_ => {}
}
if let Some(kind) = archive::sniff(&bytes) {
@ -622,6 +621,93 @@ pub fn open_chessbase_files(
finish(part.pgn, Format::ChessBase, part.notes, progress, cancel)
}
/// [`open_chessbase_files`] taking the contents: each file's bytes are let go once
/// the database is converted (the browser reads databases near its memory's limit).
pub fn open_chessbase_owned(
cbh_name: &str,
files: Vec<(String, Vec<u8>)>,
progress: &mut dyn FnMut(ScanProgress),
cancel: &AtomicBool,
) -> Result<Opened, ImportError> {
let members = chessbase::Files::from_owned(cbh_name, files);
let part = convert_chessbase(&members)?;
drop(members);
finish(part.pgn, Format::ChessBase, part.notes, progress, cancel)
}
/// What files the user chose (or found in a chosen folder) make: databases, each its
/// files' places in the list (the database's own file first: its `.cbh` for a
/// ChessBase one, with the files the reader uses after it), and ChessBase databases
/// some files of which are not among them.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Chosen {
pub databases: Vec<Vec<usize>>,
/// The database's name (the `.cbh` file's, or a part's when it is not there).
pub incomplete: Vec<String>,
}
/// Groups the files `names` into databases (see [`Chosen`]). A ChessBase database is
/// its `.cbh` and the files of the same name beside it; files of other kinds are
/// databases of their own — in a folder only those of [`EXTENSIONS`], when the user
/// chose them, any (the content decides, as in [`open`]).
pub fn group_chosen(names: &[&str], folder: bool) -> Chosen {
let lower: Vec<String> = names.iter().map(|n| n.to_lowercase()).collect();
let ext = |i: usize| {
lower[i]
.rsplit_once('.')
.map(|(_, e)| e.to_owned())
.unwrap_or_default()
};
let stem = |i: usize| {
lower[i]
.rsplit_once('.')
.map_or(lower[i].as_str(), |(s, _)| s)
.to_owned()
};
let bases: Vec<usize> = (0..names.len()).filter(|&i| ext(i) == "cbh").collect();
let mut chosen = Chosen::default();
let mut taken = vec![false; names.len()];
for &cbh in &bases {
let parts: Vec<usize> = (0..names.len())
.filter(|&j| j != cbh && stem(j) == stem(cbh))
.collect();
for &j in &parts {
taken[j] = true;
}
taken[cbh] = true;
let has = |e: &str| e == "cbh" || parts.iter().any(|&j| ext(j) == e);
if chessbase::REQUIRED.iter().all(|e| has(e)) {
let mut db = vec![cbh];
db.extend(
parts
.into_iter()
.filter(|&j| chessbase::USED.contains(&ext(j).as_str())),
);
chosen.databases.push(db);
} else {
chosen.incomplete.push(names[cbh].to_owned());
}
}
for i in 0..names.len() {
if taken[i] {
continue;
}
let e = ext(i);
if chessbase::USED.contains(&e.as_str()) {
// A part of a ChessBase database without its .cbh: one note per database.
taken[i] = true;
let own = names[i].rsplit_once('.').map_or(names[i], |(s, _)| s);
let name = format!("{own}.cbh");
if !chosen.incomplete.contains(&name) {
chosen.incomplete.push(name);
}
} else if !folder || EXTENSIONS.contains(&e.as_str()) {
chosen.databases.push(vec![i]);
}
}
chosen
}
/// A converted part of a database: UTF-8 PGN and notes.
struct Part {
pgn: String,
@ -756,3 +842,39 @@ fn finish(
notes,
})
}
#[cfg(test)]
mod chosen_tests {
use super::*;
#[test]
fn files_chosen_make_databases() {
// A whole ChessBase set (case of Windows copies), a PGN, a text file.
let names = [
"Base.CBH",
"base.cbg",
"Base.cba",
"Base.cbj",
"Base.ini",
"games.pgn",
"x.txt",
];
let c = group_chosen(&names, false);
// The settings file is the database's (ignored); a file chosen opens by content.
assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5], vec![6]]);
assert!(c.incomplete.is_empty());
// In a folder only databases: no text files.
let c = group_chosen(&names, true);
assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5]]);
}
#[test]
fn a_cbh_alone_or_parts_alone_are_incomplete() {
let c = group_chosen(&["Mega Database 2026.cbh"], false);
assert!(c.databases.is_empty());
assert_eq!(c.incomplete, vec!["Mega Database 2026.cbh".to_owned()]);
let c = group_chosen(&["Mega.cbg", "Mega.cba"], false);
assert!(c.databases.is_empty());
assert_eq!(c.incomplete, vec!["Mega.cbh".to_owned()]);
}
}

View file

@ -61,10 +61,12 @@ fn pgn_and_archives_open_from_bytes() {
let z = chess_import::open_bytes("games.zip", bytes, &mut |_| {}, &never).expect("opens");
assert_eq!(z.format, Format::Zip);
assert_eq!(z.db.raw_text(0), pgn.db.raw_text(0));
// A .cbh alone is not a database.
// A .cbh alone is not a database: its other files are needed.
assert!(matches!(
chess_import::open_bytes("base.cbh", vec![0; 46], &mut |_| {}, &never),
Err(ImportError::Corrupt(_))
Err(ImportError::Unsupported(
chess_import::Unsupported::ChessBaseFiles
))
));
}

View file

@ -71,6 +71,11 @@ impl From<chess_import::ImportError> for ApiError {
E::Io { source, .. } => ApiError::Io {
detail: source.to_string(),
},
// A .cbh alone: reported as before (the app opens a ChessBase database
// by all its files, `open_chessbase`).
E::Unsupported(u @ chess_import::Unsupported::ChessBaseFiles) => ApiError::Corrupt {
detail: u.to_string(),
},
E::Unsupported(u) => ApiError::Unsupported {
detail: u.to_string(),
},

View file

@ -235,8 +235,7 @@ Chrome for Testing 156.0.8078.80 (linux64) взят с официального
- **Файлы.** Файл прошлого посещения (Firefox/Safari не дают к нему дороги): карточка «↻ Выбрать файл снова»
и экран с «Выбрать файл снова» / «Убрать из списка»; выбранный заново занимает его место на полке.
«Оставить копию в браузере» (кнопка в строке базы): копия в `/data/copies/`, отказ с объяснением, если
копии нужно больше (с запасом 10 %), чем браузер даёт сайту. Файлы больше 1 ГБ не читаются — сообщение
«слишком большая для веб-версии… откройте в программе для компьютера».
копии нужно больше (с запасом 10 %), чем браузер даёт сайту. Предел размера — §10.
- **Без справочника и поиска по позиции** (решение: в лёгкой версии нет): `CAPS.reference` прячет вкладку,
«Найти в базе», «Доска» в библиотеке и их клавиши.
- **Клавиши** (§4 дизайна): Alt+← — назад (Ctrl+W у браузера), 1…6 без модификатора — знаки, Ctrl+C —
@ -277,9 +276,48 @@ Chrome for Testing 156.0.8078.80 (linux64) взят с официального
`Worker(String)` (адрес скрипта) в браузере; анализ, задание разбора/подготовки, судья игры и настройки
берут его вместо пути. Настройки движка в вебе (без потоков и памяти) — сделано на этапе 2.
## 10. Базы ChessBase в браузере и предел размера
- **Файлы пользователя — `File` браузера, а не байты** (`vfs`: `Content::File`): страница не держит базу в
памяти, воркер-читатель получает `File` (без копии) и читает его сам, по одному файлу базы
(`reader_give`, затем `reader_read`). Копия в браузере («Оставить копию») читает файлы асинхронно и
кладёт всю базу в свою папку `/data/copies/<мс>/`.
- **ChessBase — несколько файлов.** Выбранные (или найденные в папке) файлы группируются
`chess_import::group_chosen`: `.cbh` и файлы того же имени рядом (регистр не важен), нужны `.cbh` и `.cbg`
(`chessbase::REQUIRED`), читаются `cbh, cbg, cba, cbp, cbt, cbc` (`chessbase::USED`); база кладётся в
одну папку на странице, путь — её `.cbh`; воркер собирает соседние файлы и вызывает
`chess_import::open_chessbase_owned` (байты отдаются, не копируются).
- **Выбран один `.cbh`** — сразу окно: «База ChessBase состоит из нескольких файлов… Выберите её папку
или сразу все её файлы» и подсказка «Разрешите доступ к папке базы — остальные файлы базы найдутся сами»
(Chrome/Edge) / «Выберите папку базы — …» (Firefox/Safari); кнопки «📁 Выбрать папку базы», «Выбрать
файлы базы», «Отмена». Без жеста пользователя браузер диалог папки не откроет, поэтому шаг — одно
нажатие в этом окне. Chrome/Edge: `showDirectoryPicker({mode:"read", startIn: <ручка .cbh>})` — диалог
открывается в папке выбранного файла, ручка папки запоминается (`{dir, names}` в IndexedDB) и при
следующем визите база появляется сама или через «🔒 Разрешить чтение». Firefox/Safari:
`<input webkitdirectory>` (берутся файлы прямо в папке). Папка без баз — сообщение «В этой папке нет
базы…». База с одним `.cbh` на полке (с прошлого визита) — экран с теми же кнопками.
- **Предел — 2 ГБ** по сумме файлов базы, которые читаются (`TOO_BIG`, для ChessBase — `USED`): больше —
окно «База слишком большая для браузера (N ГБ, предел 2,0 ГБ). Извините — откройте её в программе для
компьютера» со ссылкой «Скачать ChessPenguin для компьютера» (`/<язык>/#download`). Mega Database 2026
(≈ 4,7 ГБ всего, читаемых файлов 2,2 ГБ) — отказ.
- **Память, замер 2026-10-30**: PGN 1,95 ГБ (cp1251, 194 643 партии) открывается — Firefox 64 с, Chrome 60 с;
1 ГБ — 32 с. Для этого исправлена `chess_core::repair::detect_letter_substitution`: она декодировала весь
текст и собирала `Vec<char>` (×4 размера) — на компьютере лишние гигабайты, в wasm32 переполнение
`isize` (паника `capacity overflow` уже на 1 ГБ); теперь текст идёт кусками по 1 МБ. Если читателю всё же
не хватает памяти (wasm32: 4 ГБ, а один буфер — не больше 2 ГБ; база ChessBase превращается в PGN, который
может быть больше её файлов), воркер сообщает о сбое, страница пишет «Браузеру не хватает памяти для
этой базы. Откройте её в программе для компьютера» и заводит новый воркер.
- **Без служебных путей в текстах**: `platform::files::shown(path)` — имя файла в браузере, путь на
компьютере; ошибки чтения в вебе — без пути (`import_error`).
- Проверка `apps/web/check/chessbase.mjs <app> <out> <папка небольшой базы> [<папка базы > 2 ГБ>]`:
одиночный `.cbh` → окно → папка → база прочитана; все файлы сразу; > 2 ГБ — отказ; в Chrome папка
запоминается. Firefox 159 и Chrome for Testing 156 — ok (тестовая база из `pgnFilesforExample/` только
локально, в репозиторий не входит).
### Что не сделано
- Прогресс чтения базы в воркере (сообщения о ходе разбора).
- Перетаскивание папки (egui отдаёт только файлы); несколько файлов базы перетащить можно.
- Запоминание перетащенных файлов в Chrome (`DataTransferItem.getAsFileSystemHandle` — egui его не отдаёт).
- Настоящий диалог `showOpenFilePicker` и настоящий вопрос «Разрешить» в Chrome headless не проверить:
проверены та же ручка из OPFS и ветки `granted` / `prompt` через подмену ответов браузера.
@ -291,3 +329,5 @@ Chrome for Testing 156.0.8078.80 (linux64) взят с официального
браузере, файлы, клавиши; решение без COOP/COEP (§7).
- 2026-10-30: доработка (§9) — база в воркере, счётчики, Chrome/Edge помнят файлы, черновик, вопрос при
уходе, «Назад», `EngineLocation`; проверки в Chromium (Chrome for Testing 156).
- 2026-10-30: базы ChessBase из нескольких файлов и папки, предел 2 ГБ с вежливым отказом, понятные
сообщения без служебных путей, файлы пользователя читает воркер (§10).