diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 0ecda77..cdd038b 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -26,6 +26,7 @@ use crate::sound::SoundPlayer; enum Async { DatabasesPicked(Vec), /// 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), + /// 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), +} + +/// 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, #[cfg(web)] draft_at: Option, + #[cfg(web)] + web_notice: Option, confirm_close: Option, /// Close the game once the pending "save as" succeeds. close_after_save: Option, @@ -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, + ) { { 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, 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); + } } } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index cb20785..cdc4802 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -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", "Мои партии", diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 9afb7f1..0be27f7 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -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; } diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs index d7cae22..978557f 100644 --- a/apps/desktop/src/lib.rs +++ b/apps/desktop/src/lib.rs @@ -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, count: bool) -> wasm_bindgen::JsValue { - platform::web::import::answer(name, bytes, count) +pub fn reader_give(name: String, bytes: Vec) { + 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 [report.txt]]`. diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 59ed1a5..2ecc3fa 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -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(), } } diff --git a/apps/desktop/src/platform/files.rs b/apps/desktop/src/platform/files.rs index 9cf9cf1..8a429f0 100644 --- a/apps/desktop/src/platform/files.rs +++ b/apps/desktop/src/platform/files.rs @@ -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, pub too_big: Vec<(String, u64)>, + pub incomplete: Vec, + 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)>) { + let names: Vec = 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 { - 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) + '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::() { + 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::() { + 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); } } diff --git a/apps/desktop/src/platform/web/import.rs b/apps/desktop/src/platform/web/import.rs index 2a8447d..dde9afd 100644 --- a/apps/desktop/src/platform/web/import.rs +++ b/apps/desktop/src/platform/web/import.rs @@ -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)>> = 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) { + // 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, 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) + '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::() { + 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)) { diff --git a/apps/desktop/src/platform/web/page.rs b/apps/desktop/src/platform/web/page.rs index 7da2d06..e00806f 100644 --- a/apps/desktop/src/platform/web/page.rs +++ b/apps/desktop/src/platform/web/page.rs @@ -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::window()?.document() @@ -22,32 +26,30 @@ pub async fn next_task() { let _ = wasm_bindgen_futures::JsFuture::from(promise).await; } -type Picked = Box; - -/// Files read: their names and contents, and the ones too big to read (name, bytes). -pub struct Read { - pub read: Vec<(String, Vec)>, - pub too_big: Vec<(String, u64)>, -} +type Picked = Box)>; thread_local! { /// What to do with the files chosen next. static ON_PICKED: RefCell> = const { RefCell::new(None) }; } -/// The page's file input, made once: hidden, several files, `accept` the extensions. -fn open_input(accept: &str) -> Result { +/// 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 { 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::::new(move |ev: web_sys::Event| { let Some(input) = ev @@ -62,12 +64,30 @@ fn open_input(accept: &str) -> Result { .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::().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 { 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) -> 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) + '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) + 'static) { + pick(OPEN_FOLDER_ID, "", true, then); +} + +fn pick(id: &str, accept: &str, folder: bool, then: impl FnOnce(Vec) + 'static) { + match open_input(id, accept, folder) { Ok(input) => { ON_PICKED.with_borrow_mut(|p| *p = Some(Box::new(then))); input.click(); diff --git a/apps/desktop/src/platform/web/remembered.rs b/apps/desktop/src/platform/web/remembered.rs index 2b97f7d..21ae25e 100644 --- a/apps/desktop/src/platform/web/remembered.rs +++ b/apps/desktop/src/platform/web/remembered.rs @@ -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> = RefCell::new(HashMap::new()); + /// The handle of a `.cbh` chosen alone: the folder's dialog opens where it is. + static LONE_CBH: RefCell> = 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 { + 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 { - 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>, 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 { + 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 { + 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, 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::(); - 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::() - .and_then(|f| f.call1(&window, &options)) - .and_then(|p| p.dyn_into::()); + 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 = match chosen { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p) + .await + .and_then(|h| h.dyn_into::()) + .map(|a| a.to_vec()) + .unwrap_or_default(), + Err(_) => Vec::new(), }; - if let Ok(handles) = handles.and_then(|h| h.dyn_into::()) { - for handle in handles.iter() { - let name = get(&handle, "name").as_string().unwrap_or_default(); - match read_file(&handle, &mut read).await { - Ok(Some(bytes)) => { - let path = super::vfs::add_opened(&name, bytes); - super::idb::put_handle(&path.to_string_lossy(), &handle); - paths.push(path); - } - Ok(None) => {} - Err(e) => log::warn!("cannot read {name}: {e:?}"), + 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) -> Result<(), JsValue> { + let entries = js_sys::Reflect::apply( + &get(dir, "values").dyn_into::()?, + 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 { + let dir = get(kept, "dir"); + if !dir.is_undefined() { + return vec![dir]; + } + match get(kept, "handles").dyn_into::() { + 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, 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::() - .and_then(|f| f.call1(&handle, &read_mode())) - .and_then(|p| p.dyn_into::()); + // 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()); diff --git a/apps/desktop/src/platform/web/vfs.rs b/apps/desktop/src/platform/web/vfs.rs index 9536271..eee561c 100644 --- a/apps/desktop/src/platform/web/vfs.rs +++ b/apps/desktop/src/platform/web/vfs.rs @@ -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, + content: Content, modified_ms: u64, readonly: bool, } +enum Content { + Bytes(Vec), + /// 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> = 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> { + 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 { 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 { 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) -> 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 { }) } -/// 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) -> 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) -> 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) { - 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) { + 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> { + 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) +} diff --git a/apps/web/check/browser.mjs b/apps/web/check/browser.mjs index a59a1e3..45ae52a 100644 --- a/apps/web/check/browser.mjs +++ b/apps/web/check/browser.mjs @@ -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(); + }, }; }, }; diff --git a/apps/web/check/chessbase.mjs b/apps/web/check/chessbase.mjs new file mode 100644 index 0000000..c570449 --- /dev/null +++ b/apps/web/check/chessbase.mjs @@ -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 [] +// +// : 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); diff --git a/apps/web/check/stage2.mjs b/apps/web/check/stage2.mjs index ee49678..ab3588e 100644 --- a/apps/web/check/stage2.mjs +++ b/apps/web/check/stage2.mjs @@ -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' }); diff --git a/apps/web/page/import-worker.js b/apps/web/page/import-worker.js index 20e4a61..49365f9 100644 --- a/apps/web/page/import-worker.js +++ b/apps/web/page/import-worker.js @@ -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] : []); }; diff --git a/apps/web/src/lib.rs b/apps/web/src/lib.rs index 9267482..147a881 100644 --- a/apps/web/src/lib.rs +++ b/apps/web/src/lib.rs @@ -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, count: bool) -> JsValue { - chesspenguin_app::read_database(&name, bytes, count) +pub fn reader_give(name: String, bytes: Vec) { + 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 diff --git a/crates/chess-core/src/repair.rs b/crates/chess-core/src/repair.rs index b7a8fb4..77f0831 100644 --- a/crates/chess-core/src/repair.rs +++ b/crates/chess-core/src/repair.rs @@ -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 = 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 + '_ { + bytes.chunks(1 << 20).flat_map(move |piece| { + let (text, _) = encoding.decode(piece); + text.chars().collect::>() + }) +} + +/// The sequences of the table next to a Cyrillic letter (a pair taken is not looked at +/// again). +fn sequences(chars: impl Iterator) -> usize { + let is_cyr = + |c: Option| 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) -> 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 diff --git a/crates/chess-import/src/chessbase/mod.rs b/crates/chess-import/src/chessbase/mod.rs index cf2298b..8bdf4de 100644 --- a/crates/chess-import/src/chessbase/mod.rs +++ b/crates/chess-import/src/chessbase/mod.rs @@ -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)>) -> 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 { + 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) diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index 72a339f..fd7d0c0 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -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)>, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + 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>, + /// The database's name (the `.cbh` file's, or a part's when it is not there). + pub incomplete: Vec, +} + +/// 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 = 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 = (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 = (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()]); + } +} diff --git a/crates/chess-import/tests/formats.rs b/crates/chess-import/tests/formats.rs index cad488c..3903e43 100644 --- a/crates/chess-import/tests/formats.rs +++ b/crates/chess-import/tests/formats.rs @@ -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 + )) )); } diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index 3153958..a470468 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -71,6 +71,11 @@ impl From 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(), }, diff --git a/docs/dev/web.md b/docs/dev/web.md index 4724d64..899e65f 100644 --- a/docs/dev/web.md +++ b/docs/dev/web.md @@ -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: + `` (берутся файлы прямо в папке). Папка без баз — сообщение «В этой папке нет + базы…». База с одним `.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` (×4 размера) — на компьютере лишние гигабайты, в wasm32 переполнение + `isize` (паника `capacity overflow` уже на 1 ГБ); теперь текст идёт кусками по 1 МБ. Если читателю всё же + не хватает памяти (wasm32: 4 ГБ, а один буфер — не больше 2 ГБ; база ChessBase превращается в PGN, который + может быть больше её файлов), воркер сообщает о сбое, страница пишет «Браузеру не хватает памяти для + этой базы. Откройте её в программе для компьютера» и заводит новый воркер. +- **Без служебных путей в текстах**: `platform::files::shown(path)` — имя файла в браузере, путь на + компьютере; ошибки чтения в вебе — без пути (`import_error`). +- Проверка `apps/web/check/chessbase.mjs <папка небольшой базы> [<папка базы > 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).