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:
parent
bda92c5675
commit
bc104c55b4
21 changed files with 1337 additions and 341 deletions
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
"Мои партии",
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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]]`.
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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(©) {
|
||||
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(©, &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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue