Web version, stage 2: Stockfish 19 in workers, live analysis, game review on N workers, My games, files, keys
game-review: what the job does for one target (the full search, the second best without the move played, the shallow ones) becomes a machine without I/O (job/work.rs), driven by the engine processes on a computer (job/engines.rs, the same searches as before) and by Web Workers in a browser (job/workers.rs: a dispatcher polled from the frames, never blocking). The analysis cache goes through a CacheStore (a folder, or the program's files of the platform). The browser's engine: Stockfish.js 19.0.1 (npm stockfish, GPL-3.0), its single-threaded build served beside /app/ (engine/, build.sh checks the package's sha512), its 99 MB wasm downloaded only through the engine offer, checked against its SHA-256 and kept in Cache Storage; workers get it as a blob: address. Live analysis (lines, arrows, the bar) and the review run on it; the review uses one worker per logical CPU, at most 8. My games (the web version): a PGN in the browser's storage, always on the shelf; Ctrl+S puts a game there (its own record, or a new one); deleting with undo. chess-core's store gives the bytes of append/replace/remove/restore, so the platform writes them into the browser's files; on a computer the files are written as before. Settings: Browser data (used and free space, keeping the data for good, Download all as PGN, deleting the engine). Files: a file of the last visit offers Choose the file again; Keep a copy in the browser (refused with the room it needs when the browser gives too little); files over 1 GB are not opened, with a word on why. No reference tab and no search by position in the web version. Keys: Alt+Left, plain 1-6, Ctrl+C, N in the library (the browser keeps Ctrl+W/N/1-6/Shift+C). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4ccf8099a5
commit
61ccd763bc
34 changed files with 2063 additions and 253 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -1711,6 +1711,7 @@ dependencies = [
|
|||
"serde_json",
|
||||
"shakmaty",
|
||||
"uci",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -149,6 +149,23 @@ platform into the user's data directory and checks its SHA-256 (pinned in
|
|||
Open Database License (ODbL).
|
||||
- ChessPenguin runs Stockfish as a separate process over the UCI protocol.
|
||||
|
||||
### Stockfish.js (the web version)
|
||||
|
||||
The web version (`/app/` on the site) uses **Stockfish.js 19.0.1** by Nathan Rugg and Chess.com
|
||||
(https://github.com/nmrugg/stockfish.js), its single-threaded build `stockfish-19-single.js` +
|
||||
`stockfish-19-single.wasm`, unmodified, from the npm package `stockfish@19.0.1`
|
||||
(https://registry.npmjs.org/stockfish/-/stockfish-19.0.1.tgz, integrity
|
||||
`sha512-bTwsO4e9HAwPBKls1+szcfibmaWRNzTF20rQE/XPdB3LOSoT6XTZDr1zYwriwSRRFT5MkvqrglPmJrKEVXGnyQ==`,
|
||||
checked by `apps/web/build.sh`). It is Stockfish 19 compiled to WebAssembly with the network
|
||||
`nn-1a298aa575a0` built in. Our site serves the files beside the program (`/app/engine/`, with the
|
||||
package's `Copying.txt`); the browser downloads the `.wasm` only when the user agrees and keeps it
|
||||
in its Cache Storage; it runs in Web Workers over UCI.
|
||||
|
||||
- License: GNU General Public License version 3 (the engine; `Copying.txt`); the JavaScript
|
||||
wrapper as published in the package.
|
||||
- Source code: https://github.com/nmrugg/stockfish.js/tree/v19.0.1 (the build scripts and the
|
||||
emscripten glue) and the Stockfish source above.
|
||||
|
||||
## Opening names (preparing against an opponent)
|
||||
|
||||
`crates/openings/data/a.tsv` … `e.tsv` are the five files of the Lichess opening table
|
||||
|
|
|
|||
|
|
@ -79,7 +79,9 @@ web-sys = { version = "0.3", features = [
|
|||
"Storage", "UrlSearchParams", "EventTarget", "CssStyleDeclaration", "Clipboard",
|
||||
"IdbFactory", "IdbDatabase", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction",
|
||||
"IdbTransactionMode", "IdbObjectStore", "DomStringList", "HtmlAudioElement",
|
||||
"HtmlMediaElement", "HtmlCanvasElement", "console",
|
||||
"HtmlMediaElement", "HtmlCanvasElement", "console", "CacheStorage", "Cache",
|
||||
"Request", "Response", "ResponseInit", "Headers", "ReadableStream",
|
||||
"ReadableStreamDefaultReader", "StorageManager", "StorageEstimate",
|
||||
] }
|
||||
|
||||
[build-dependencies]
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ use crate::sound::SoundPlayer;
|
|||
/// Results of work done off the UI thread (file dialogs, engine checks).
|
||||
enum Async {
|
||||
DatabasesPicked(Vec<PathBuf>),
|
||||
/// Files not opened: too big for a browser (name, bytes).
|
||||
TooBig(Vec<(String, u64)>),
|
||||
SavePicked(PathBuf),
|
||||
SaveCancelled,
|
||||
EngineChecked(Result<(PathBuf, String), String>),
|
||||
|
|
@ -217,6 +219,8 @@ pub struct App {
|
|||
rx: Receiver<Async>,
|
||||
/// «Paste PGN»: the clipboard being read.
|
||||
pasting: Option<crate::platform::clipboard::Reading>,
|
||||
/// A file of the last visit being chosen again (a browser's).
|
||||
choosing_again: Option<PathBuf>,
|
||||
confirm_close: Option<CloseIntent>,
|
||||
/// Close the game once the pending "save as" succeeds.
|
||||
close_after_save: Option<CloseIntent>,
|
||||
|
|
@ -402,6 +406,10 @@ impl App {
|
|||
let _ = settings.save();
|
||||
}
|
||||
let engines_found = crate::engines::first_run_setup(&mut settings);
|
||||
#[cfg(web)]
|
||||
if crate::my_games::setup(&mut settings) {
|
||||
let _ = settings.save();
|
||||
}
|
||||
if crate::examples::setup(&mut settings) || engines_found {
|
||||
let _ = settings.save();
|
||||
}
|
||||
|
|
@ -447,6 +455,7 @@ impl App {
|
|||
tx,
|
||||
rx,
|
||||
pasting: None,
|
||||
choosing_again: None,
|
||||
confirm_close: None,
|
||||
close_after_save: None,
|
||||
find_after_close: None,
|
||||
|
|
@ -983,6 +992,16 @@ impl App {
|
|||
let target = self.current_target();
|
||||
let Some(g) = &self.game else { return };
|
||||
self.own.then_close = then_close;
|
||||
// The web version keeps the user's games in «My games»: a game from anywhere
|
||||
// else (a file, which is only read, a sample, a new one) goes there, no question.
|
||||
#[cfg(web)]
|
||||
if !matches!(&g.source, Some(src) if src.block.is_none()) {
|
||||
if crate::platform::web::storage::persisted() != Some(true) {
|
||||
crate::platform::web::storage::persist(|_| {});
|
||||
}
|
||||
self.add_current_to(ctx, crate::my_games::path());
|
||||
return;
|
||||
}
|
||||
match &g.source {
|
||||
Some(src) if src.block.is_none() => {
|
||||
if !g.game.is_modified() {
|
||||
|
|
@ -1030,7 +1049,7 @@ impl App {
|
|||
};
|
||||
let Some(pgn) = db.as_pgn() else { return };
|
||||
let text = g.game.to_pgn();
|
||||
match chess_core::pgn::store::replace(pgn, src.index, &text) {
|
||||
match crate::platform::pgn_store::replace(pgn, &src.path, src.index, &text) {
|
||||
Ok(()) => {
|
||||
let name = own_db::base_name(&src.path);
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
|
|
@ -1171,7 +1190,7 @@ impl App {
|
|||
return;
|
||||
};
|
||||
let Some(pgn) = db.as_pgn() else { return };
|
||||
match chess_core::pgn::store::append(pgn, &text) {
|
||||
match crate::platform::pgn_store::append(pgn, &target, &text) {
|
||||
Ok(_) => {
|
||||
let index = pgn.len();
|
||||
let name = own_db::base_name(&target);
|
||||
|
|
@ -1210,7 +1229,7 @@ impl App {
|
|||
return;
|
||||
};
|
||||
let Some(pgn) = db.as_pgn() else { return };
|
||||
match chess_core::pgn::store::replace(pgn, index, &text) {
|
||||
match crate::platform::pgn_store::replace(pgn, &target, index, &text) {
|
||||
Ok(()) => {
|
||||
let name = own_db::base_name(&target);
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
|
|
@ -1305,7 +1324,7 @@ impl App {
|
|||
return;
|
||||
};
|
||||
let Some(pgn) = db.as_pgn() else { return };
|
||||
match chess_core::pgn::store::append(pgn, &text) {
|
||||
match crate::platform::pgn_store::append(pgn, &target, &text) {
|
||||
Ok(_) => {
|
||||
let n = pgn.len();
|
||||
let name = own_db::base_name(&target);
|
||||
|
|
@ -1351,7 +1370,7 @@ impl App {
|
|||
return;
|
||||
};
|
||||
let Some(pgn) = db.as_pgn() else { return };
|
||||
match chess_core::pgn::store::replace(pgn, at, &text) {
|
||||
match crate::platform::pgn_store::replace(pgn, &target, at, &text) {
|
||||
Ok(()) => {
|
||||
let name = own_db::base_name(&target);
|
||||
self.settings.last_target = Some(target.clone());
|
||||
|
|
@ -1506,7 +1525,7 @@ impl App {
|
|||
return;
|
||||
};
|
||||
let Some(pgn) = db.as_pgn() else { return };
|
||||
match chess_core::pgn::store::remove(pgn, index) {
|
||||
match crate::platform::pgn_store::remove(pgn, &path, index) {
|
||||
Ok(removed) => {
|
||||
// Games open from this file: their records moved up by one.
|
||||
let mut open = None;
|
||||
|
|
@ -1563,7 +1582,7 @@ impl App {
|
|||
return;
|
||||
};
|
||||
let Some(pgn) = db.as_pgn() else { return };
|
||||
match chess_core::pgn::store::restore(pgn, &undo.removed) {
|
||||
match crate::platform::pgn_store::restore(pgn, &undo.path, &undo.removed) {
|
||||
Ok(()) => {
|
||||
let index = undo.removed.index;
|
||||
for g in self.game.iter_mut().chain(self.previous_games.iter_mut()) {
|
||||
|
|
@ -2349,10 +2368,8 @@ impl App {
|
|||
|
||||
fn pick_databases(&self, ctx: &egui::Context) {
|
||||
let (tx, ctx) = (self.tx.clone(), ctx.clone());
|
||||
crate::platform::files::pick_databases(move |paths| {
|
||||
if !paths.is_empty() {
|
||||
let _ = tx.send(Async::DatabasesPicked(paths));
|
||||
}
|
||||
crate::platform::files::pick_databases(move |picked| {
|
||||
send_picked(&tx, picked);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
|
|
@ -2407,7 +2424,22 @@ 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
Async::DatabasesPicked(paths) => {
|
||||
// The file chosen again takes the place of the one gone.
|
||||
if let Some(old) = self.choosing_again.take() {
|
||||
self.settings.databases.retain(|d| *d != old);
|
||||
self.library.forget(&old);
|
||||
}
|
||||
for p in paths.iter().rev() {
|
||||
self.settings.touch_database(p);
|
||||
}
|
||||
|
|
@ -2734,10 +2766,8 @@ impl App {
|
|||
/// dragged over it, the window says so.
|
||||
fn dropped_files(&mut self, ctx: &egui::Context) {
|
||||
let (tx, waker) = (self.tx.clone(), ctx.clone());
|
||||
crate::platform::files::take_dropped(ctx, move |paths| {
|
||||
if !paths.is_empty() {
|
||||
let _ = tx.send(Async::DatabasesPicked(paths));
|
||||
}
|
||||
crate::platform::files::take_dropped(ctx, move |picked| {
|
||||
send_picked(&tx, picked);
|
||||
waker.request_repaint();
|
||||
});
|
||||
if crate::platform::files::dragging(ctx) {
|
||||
|
|
@ -2759,6 +2789,43 @@ impl App {
|
|||
}
|
||||
}
|
||||
|
||||
/// A copy of a file of this visit kept in the browser: it takes the file's place on
|
||||
/// the shelf. Only a browser has such files.
|
||||
fn keep_copy(&mut self, ctx: &egui::Context, path: PathBuf) {
|
||||
#[cfg(web)]
|
||||
{
|
||||
use crate::platform::files::KeepCopy;
|
||||
use crate::platform::size_text;
|
||||
match crate::platform::files::keep_copy(&path) {
|
||||
Ok(copy) => {
|
||||
for d in self.settings.databases.iter_mut().filter(|d| **d == path) {
|
||||
*d = copy.clone();
|
||||
}
|
||||
self.library.forget(&path);
|
||||
self.library.select_db(©, ctx);
|
||||
self.settings_dirty = true;
|
||||
let ctx2 = ctx.clone();
|
||||
crate::platform::web::storage::refresh(move || ctx2.request_repaint());
|
||||
if crate::platform::web::storage::persisted() != Some(true) {
|
||||
crate::platform::web::storage::persist(|_| {});
|
||||
}
|
||||
self.toast(ctx, tr("A copy is kept in the browser"));
|
||||
}
|
||||
Err(KeepCopy::NoRoom { need, free }) => self.toast_for(
|
||||
ctx,
|
||||
trf(
|
||||
"Doesn't fit: the copy needs {need}, and the browser gives the site only {free} more. Free up space in “Browser data” or open the file from disk.",
|
||||
&[("need", &size_text(need)), ("free", &size_text(free))],
|
||||
),
|
||||
8.0,
|
||||
),
|
||||
Err(KeepCopy::Failed(e)) => self.toast(ctx, e),
|
||||
}
|
||||
}
|
||||
#[cfg(not(web))]
|
||||
let _ = (ctx, path);
|
||||
}
|
||||
|
||||
/// The open game's PGN, downloaded as a file named after the game.
|
||||
#[cfg(web)]
|
||||
fn download_pgn(&mut self, ctx: &egui::Context) {
|
||||
|
|
@ -3134,7 +3201,14 @@ impl eframe::App for App {
|
|||
{
|
||||
self.play_new(&ctx, PlayNext::Dialog(None));
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() {
|
||||
// A browser keeps Ctrl+N for its window: N in the library there (design §4).
|
||||
let new_game_key = cfg!(web)
|
||||
&& self.game.is_none()
|
||||
&& !ctx.egui_wants_keyboard_input()
|
||||
&& ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::N));
|
||||
if (new_game_key || ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))))
|
||||
&& self.game.is_none()
|
||||
{
|
||||
self.new_game();
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Comma))) {
|
||||
|
|
@ -3432,6 +3506,11 @@ impl eframe::App for App {
|
|||
undo: false,
|
||||
});
|
||||
}
|
||||
LibraryAction::ChooseAgain(p) => {
|
||||
self.choosing_again = Some(p);
|
||||
self.pick_databases(&ctx);
|
||||
}
|
||||
LibraryAction::KeepCopy(p) => self.keep_copy(&ctx, p),
|
||||
LibraryAction::OpenSettings => self.settings_ui.open = true,
|
||||
LibraryAction::NewDatabase => {
|
||||
self.own.then_close = None;
|
||||
|
|
@ -3485,6 +3564,20 @@ impl eframe::App for App {
|
|||
}
|
||||
#[cfg(not(web))]
|
||||
SettingsAction::OpenUpdate => self.desktop.update_ui.open = true,
|
||||
#[cfg(web)]
|
||||
SettingsAction::DownloadMyGames => {
|
||||
if let Err(e) = crate::my_games::download_all() {
|
||||
self.toast(
|
||||
&ctx,
|
||||
trf("The PGN could not be downloaded: {e}", &[("e", &e)]),
|
||||
);
|
||||
}
|
||||
}
|
||||
#[cfg(web)]
|
||||
SettingsAction::KeepData => {
|
||||
let ctx = ctx.clone();
|
||||
crate::platform::web::storage::persist(move |_| ctx.request_repaint());
|
||||
}
|
||||
SettingsAction::DownloadEngine => self.engine_offer.start(&ctx),
|
||||
SettingsAction::CancelDownload => self.engine_offer.cancel(),
|
||||
SettingsAction::RemoveDownloaded => {
|
||||
|
|
@ -3628,6 +3721,16 @@ impl eframe::App for App {
|
|||
}
|
||||
}
|
||||
|
||||
/// What the user chose or dropped, to the screen.
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize(s: &str) -> String {
|
||||
s.chars()
|
||||
.map(|c| match c {
|
||||
|
|
|
|||
|
|
@ -66,11 +66,14 @@ fn asset() -> Option<Asset> {
|
|||
|
||||
/// Whether a download is offered on this platform at all.
|
||||
pub fn available() -> bool {
|
||||
asset().is_some()
|
||||
cfg!(web) || asset().is_some()
|
||||
}
|
||||
|
||||
/// Size of the download in megabytes (rounded), for the offer.
|
||||
pub fn size_mb() -> u64 {
|
||||
#[cfg(web)]
|
||||
return crate::platform::web::engine::DOWNLOAD_MB;
|
||||
#[cfg(not(web))]
|
||||
asset().map_or(0, |a| a.size.div_ceil(1_000_000))
|
||||
}
|
||||
|
||||
|
|
@ -98,14 +101,25 @@ pub fn clean_leftovers() {
|
|||
}
|
||||
}
|
||||
|
||||
/// The downloaded engine, if it is there.
|
||||
/// The downloaded engine, if it is there (in a browser: the address of its worker).
|
||||
pub fn installed() -> Option<PathBuf> {
|
||||
#[cfg(web)]
|
||||
return crate::platform::web::engine::worker_script().map(PathBuf::from);
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let p = dir()?.join(EXE);
|
||||
p.is_file().then_some(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the downloaded engine (frees its space).
|
||||
pub fn remove() -> std::io::Result<()> {
|
||||
#[cfg(web)]
|
||||
{
|
||||
crate::platform::web::engine::remove();
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(web))]
|
||||
match dir() {
|
||||
Some(d) if d.exists() => std::fs::remove_dir_all(d),
|
||||
_ => Ok(()),
|
||||
|
|
@ -154,14 +168,42 @@ impl Download {
|
|||
Download::spawn(ctx, total, run)
|
||||
}
|
||||
|
||||
/// A browser downloads no engine programs: there is no download for it, as for a
|
||||
/// computer without a published build.
|
||||
/// The browser's engine: Stockfish 19 in WebAssembly from our site, into the
|
||||
/// browser's cache (`platform::web::engine`).
|
||||
#[cfg(web)]
|
||||
pub fn start(_ctx: &egui::Context) -> Download {
|
||||
Download::unsupported()
|
||||
pub fn start(ctx: &egui::Context) -> Download {
|
||||
use crate::platform::web::engine::{self, Fetch};
|
||||
let total = engine::WASM_BYTES;
|
||||
let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0, total }));
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone());
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let report = |st: Stage| {
|
||||
if let Ok(mut g) = s.lock() {
|
||||
*g = st;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
};
|
||||
let end =
|
||||
match engine::download(|done, total| report(Stage::Downloading { done, total }), c)
|
||||
.await
|
||||
{
|
||||
Ok(()) => match installed() {
|
||||
Some(p) => Stage::Done(p),
|
||||
None => Stage::Failed(Failure::Disk("not kept".into())),
|
||||
},
|
||||
Err(Fetch::Cancelled) => Stage::Cancelled,
|
||||
Err(Fetch::Network(e)) => Stage::Failed(Failure::Network(e)),
|
||||
Err(Fetch::Server(code)) => Stage::Failed(Failure::Server(code)),
|
||||
Err(Fetch::Checksum) => Stage::Failed(Failure::Checksum),
|
||||
Err(Fetch::Storage(e)) => Stage::Failed(Failure::Disk(e)),
|
||||
};
|
||||
report(end);
|
||||
});
|
||||
Download { stage, cancel }
|
||||
}
|
||||
|
||||
/// The download of a platform that has none.
|
||||
/// The download of a platform that has none (Rodent and the like in a browser).
|
||||
#[cfg(web)]
|
||||
pub fn unsupported() -> Download {
|
||||
Download {
|
||||
|
|
|
|||
|
|
@ -73,10 +73,7 @@ impl EngineOffer {
|
|||
|
||||
/// Whether the active engine can be started.
|
||||
pub fn engine_ready(settings: &Settings) -> bool {
|
||||
settings
|
||||
.active_engine()
|
||||
.and_then(|e| e.executable())
|
||||
.is_some_and(|p| p.is_file())
|
||||
settings.active_engine().is_some_and(|e| e.present())
|
||||
}
|
||||
|
||||
/// Opens the offer for an action that needs an engine.
|
||||
|
|
@ -247,6 +244,19 @@ impl EngineOffer {
|
|||
))
|
||||
.weak(),
|
||||
);
|
||||
} else if cfg!(web) {
|
||||
// The browser's engine: from our site, into this browser (design §1.4).
|
||||
ui.label(tr(
|
||||
"It evaluates the position, shows the best moves and reviews the game. It is downloaded once and kept in this browser.",
|
||||
));
|
||||
let free = crate::platform::storage_free().map(|f| {
|
||||
trf(
|
||||
"free for the site: {free}",
|
||||
&[("free", &crate::platform::size_text(f))],
|
||||
)
|
||||
});
|
||||
let size = trf("Size: {size}", &[("size", &format!("{size} MB"))]);
|
||||
ui.label(RichText::new(free.map_or(size.clone(), |f| format!("{size} · {f}"))).weak());
|
||||
} else {
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
|
|
@ -295,11 +305,12 @@ impl EngineOffer {
|
|||
}
|
||||
}
|
||||
}
|
||||
// Another engine does not do for the game analysis.
|
||||
// Another engine does not do for the game analysis (and a browser has
|
||||
// no engine programs).
|
||||
#[cfg(not(web))]
|
||||
if self.mode != Mode::Own {
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Choose engine file…")).clicked() {
|
||||
#[cfg(not(web))]
|
||||
events.push(OfferEvent::ChooseFile);
|
||||
self.open = false;
|
||||
self.pending = None;
|
||||
|
|
@ -406,10 +417,10 @@ impl EngineOffer {
|
|||
self.failure = None;
|
||||
self.pending = None;
|
||||
}
|
||||
#[cfg(not(web))]
|
||||
if self.mode != Mode::Own {
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Choose engine file…")).clicked() {
|
||||
#[cfg(not(web))]
|
||||
events.push(OfferEvent::ChooseFile);
|
||||
self.open = false;
|
||||
self.failure = None;
|
||||
|
|
|
|||
|
|
@ -981,7 +981,8 @@ impl GameView {
|
|||
} else {
|
||||
0.0
|
||||
}
|
||||
+ button(ui, "⏷")
|
||||
+ if crate::platform::CAPS.reference {
|
||||
button(ui, "⏷")
|
||||
+ button(
|
||||
ui,
|
||||
if compact {
|
||||
|
|
@ -990,6 +991,9 @@ impl GameView {
|
|||
tr("🔍 Find in database")
|
||||
},
|
||||
)
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
+ notes.as_ref().map_or(0.0, |n| button(ui, n.text()))
|
||||
};
|
||||
// The result, or during a game against the computer its time control («5+3», «∞»)
|
||||
|
|
@ -1129,7 +1133,7 @@ impl GameView {
|
|||
let why = tr("After a null move (--) this is a teaching scheme, not a position of a game: it is not searched");
|
||||
// Not during a game against Maia: it would leave the game.
|
||||
let playing = self.play.is_some() || self.train.is_some();
|
||||
if !playing { ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| {
|
||||
if !playing && crate::platform::CAPS.reference { ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| {
|
||||
ui.menu_button("⏷", |ui| {
|
||||
for db in databases {
|
||||
let name = db
|
||||
|
|
@ -1445,8 +1449,10 @@ impl GameView {
|
|||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut self.side_tab, SideTab::Notation, tr("Notation"));
|
||||
if crate::platform::CAPS.reference {
|
||||
ui.selectable_value(&mut self.side_tab, SideTab::Reference, tr("Reference"))
|
||||
.on_hover_text(tr("What was played in this position in a database"));
|
||||
}
|
||||
if report {
|
||||
ui.selectable_value(&mut self.side_tab, SideTab::Report, tr("Report"));
|
||||
}
|
||||
|
|
@ -1501,7 +1507,12 @@ impl GameView {
|
|||
}
|
||||
return;
|
||||
}
|
||||
match self.translation.strip(ui, settings, hub) {
|
||||
let strip = if crate::platform::CAPS.translation {
|
||||
self.translation.strip(ui, settings, hub)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match strip {
|
||||
Some(crate::translate_ui::StripAction::OpenSettings) => {
|
||||
actions.push(GameAction::OpenTranslationSettings)
|
||||
}
|
||||
|
|
@ -2154,8 +2165,10 @@ impl GameView {
|
|||
}
|
||||
|
||||
pub fn show_reference_tab(&mut self) {
|
||||
if crate::platform::CAPS.reference {
|
||||
self.side_tab = SideTab::Reference;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn search_line(&self) -> Option<(Chess, Vec<shakmaty::Move>, bool)> {
|
||||
let (start, line) = crate::board_search::line_to(&self.game, self.cursor)?;
|
||||
|
|
@ -4760,6 +4773,16 @@ impl GameView {
|
|||
if i.consume_shortcut(&ctrl(Key::W)) {
|
||||
cmds.push("back");
|
||||
}
|
||||
// A browser keeps Ctrl+W, Ctrl+1…6 and Ctrl+Shift+C for itself
|
||||
// (docs/design/web-version.md §4): Alt+←, plain 1…6 and Ctrl+C there.
|
||||
if cfg!(web) {
|
||||
if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::ALT, Key::ArrowLeft)) {
|
||||
cmds.push("back");
|
||||
}
|
||||
if i.consume_shortcut(&ctrl(Key::C)) {
|
||||
cmds.push("copy");
|
||||
}
|
||||
}
|
||||
if i.consume_shortcut(&ctrl(Key::G)) {
|
||||
cmds.push("play_from");
|
||||
}
|
||||
|
|
@ -4783,7 +4806,9 @@ impl GameView {
|
|||
(Key::Num5, "nag5"),
|
||||
(Key::Num6, "nag6"),
|
||||
] {
|
||||
if i.consume_shortcut(&ctrl(key)) {
|
||||
if i.consume_shortcut(&ctrl(key))
|
||||
|| (cfg!(web) && i.consume_key(Modifiers::NONE, key))
|
||||
{
|
||||
cmds.push(cmd);
|
||||
}
|
||||
}
|
||||
|
|
@ -4845,7 +4870,7 @@ impl GameView {
|
|||
}
|
||||
"game_data" => actions.push(GameAction::EditGameData),
|
||||
"back" => actions.push(GameAction::BackKey),
|
||||
"find" if self.search_line().is_some() => {
|
||||
"find" if crate::platform::CAPS.reference && self.search_line().is_some() => {
|
||||
actions.push(GameAction::FindPosition(None))
|
||||
}
|
||||
"back1" => self.step_back(),
|
||||
|
|
|
|||
|
|
@ -217,6 +217,237 @@ 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 ---
|
||||
[
|
||||
"📋 Keep a copy in the browser",
|
||||
"📋 Оставить копию в браузере",
|
||||
"📋 Garder une copie dans le navigateur",
|
||||
"📋 Kopie im Browser behalten",
|
||||
"📋 Guardar una copia en el navegador",
|
||||
"📋 Tieni una copia nel browser",
|
||||
"📋 Manter uma cópia no navegador",
|
||||
"📋 Brauzerda nusxa qoldirish",
|
||||
"📋 Браузерде көшірме қалдыру",
|
||||
],
|
||||
[
|
||||
"The copy opens right away, without choosing the file. It is stored in this browser on this device and is lost if you clear the site's data. The file on disk is not changed.",
|
||||
"Копия откроется сразу, без выбора файла. Она хранится в этом браузере на этом устройстве и пропадёт, если очистить данные сайта. Файл на диске не меняется.",
|
||||
"La copie s'ouvre aussitôt, sans choisir le fichier. Elle est stockée dans ce navigateur sur cet appareil et disparaît si vous effacez les données du site. Le fichier sur le disque n'est pas modifié.",
|
||||
"Die Kopie öffnet sich sofort, ohne die Datei zu wählen. Sie ist in diesem Browser auf diesem Gerät gespeichert und geht verloren, wenn Sie die Daten der Website löschen. Die Datei auf der Festplatte bleibt unverändert.",
|
||||
"La copia se abre al instante, sin elegir el archivo. Se guarda en este navegador en este dispositivo y se pierde si borras los datos del sitio. El archivo del disco no cambia.",
|
||||
"La copia si apre subito, senza scegliere il file. È salvata in questo browser su questo dispositivo e si perde se cancelli i dati del sito. Il file sul disco non cambia.",
|
||||
"A cópia abre na hora, sem escolher o arquivo. Ela fica guardada neste navegador neste aparelho e se perde se você limpar os dados do site. O arquivo no disco não muda.",
|
||||
"Nusxa faylni tanlamasdan darhol ochiladi. U shu qurilmadagi shu brauzerda saqlanadi va sayt ma’lumotlari tozalansa, yo‘qoladi. Diskdagi fayl o‘zgarmaydi.",
|
||||
"Көшірме файлды таңдамай-ақ бірден ашылады. Ол осы құрылғыдағы осы браузерде сақталады және сайт деректерін тазаласаңыз, жоғалады. Дисктегі файл өзгермейді.",
|
||||
],
|
||||
[
|
||||
"↻ Choose the file again",
|
||||
"↻ Выбрать файл снова",
|
||||
"↻ Choisir le fichier à nouveau",
|
||||
"↻ Datei erneut wählen",
|
||||
"↻ Elegir el archivo de nuevo",
|
||||
"↻ Scegli di nuovo il file",
|
||||
"↻ Escolher o arquivo de novo",
|
||||
"↻ Faylni qayta tanlash",
|
||||
"↻ Файлды қайта таңдау",
|
||||
],
|
||||
[
|
||||
"This browser doesn't remember files: after a reload, choose the file again or keep a copy in the browser.",
|
||||
"Этот браузер не запоминает файлы: после перезагрузки выберите файл снова или оставьте копию в браузере.",
|
||||
"Ce navigateur ne retient pas les fichiers : après un rechargement, choisissez à nouveau le fichier ou gardez-en une copie dans le navigateur.",
|
||||
"Dieser Browser merkt sich keine Dateien: Wählen Sie die Datei nach einem Neuladen erneut oder behalten Sie eine Kopie im Browser.",
|
||||
"Este navegador no recuerda los archivos: tras recargar, elige el archivo de nuevo o guarda una copia en el navegador.",
|
||||
"Questo browser non ricorda i file: dopo un ricaricamento scegli di nuovo il file o tienine una copia nel browser.",
|
||||
"Este navegador não lembra os arquivos: depois de recarregar, escolha o arquivo de novo ou mantenha uma cópia no navegador.",
|
||||
"Bu brauzer fayllarni eslab qolmaydi: qayta yuklangandan keyin faylni yana tanlang yoki brauzerda nusxa qoldiring.",
|
||||
"Бұл браузер файлдарды есте сақтамайды: қайта жүктегеннен кейін файлды қайта таңдаңыз немесе браузерде көшірме қалдырыңыз.",
|
||||
],
|
||||
[
|
||||
"A copy is kept in the browser",
|
||||
"Копия оставлена в браузере",
|
||||
"Une copie est gardée dans le navigateur",
|
||||
"Eine Kopie ist im Browser gespeichert",
|
||||
"Se guardó una copia en el navegador",
|
||||
"Una copia è conservata nel browser",
|
||||
"Uma cópia ficou no navegador",
|
||||
"Nusxa brauzerda qoldirildi",
|
||||
"Көшірме браузерде қалдырылды",
|
||||
],
|
||||
[
|
||||
"Doesn't fit: the copy needs {need}, and the browser gives the site only {free} more. Free up space in “Browser data” or open the file from disk.",
|
||||
"Не помещается: копии нужно {need}, а браузер даёт сайту ещё {free}. Освободите место в «Данных в браузере» или открывайте файл с диска.",
|
||||
"Ne tient pas : la copie a besoin de {need}, et le navigateur ne donne plus que {free} au site. Libérez de la place dans « Données du navigateur » ou ouvrez le fichier depuis le disque.",
|
||||
"Passt nicht: Die Kopie braucht {need}, der Browser gibt der Website nur noch {free}. Schaffen Sie Platz unter „Daten im Browser“ oder öffnen Sie die Datei von der Festplatte.",
|
||||
"No cabe: la copia necesita {need} y el navegador solo da al sitio {free} más. Libera espacio en «Datos del navegador» o abre el archivo desde el disco.",
|
||||
"Non ci sta: la copia richiede {need} e il browser concede al sito solo altri {free}. Libera spazio in «Dati del browser» o apri il file dal disco.",
|
||||
"Não cabe: a cópia precisa de {need}, e o navegador dá ao site só mais {free}. Libere espaço em “Dados do navegador” ou abra o arquivo do disco.",
|
||||
"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",
|
||||
"Мои партии",
|
||||
"Mes parties",
|
||||
"Meine Partien",
|
||||
"Mis partidas",
|
||||
"Le mie partite",
|
||||
"Minhas partidas",
|
||||
"Mening partiyalarim",
|
||||
"Менің партияларым",
|
||||
],
|
||||
[
|
||||
"Browser data",
|
||||
"Данные в браузере",
|
||||
"Données du navigateur",
|
||||
"Daten im Browser",
|
||||
"Datos del navegador",
|
||||
"Dati del browser",
|
||||
"Dados do navegador",
|
||||
"Brauzerdagi ma’lumotlar",
|
||||
"Браузердегі деректер",
|
||||
],
|
||||
[
|
||||
"Everything below is stored only here, on this device. Files on disk are not changed.",
|
||||
"Всё ниже хранится только здесь, на этом устройстве. Файлы на диске не меняются.",
|
||||
"Tout ce qui suit est stocké uniquement ici, sur cet appareil. Les fichiers sur le disque ne sont pas modifiés.",
|
||||
"Alles Folgende ist nur hier auf diesem Gerät gespeichert. Dateien auf der Festplatte werden nicht geändert.",
|
||||
"Todo lo de abajo se guarda solo aquí, en este dispositivo. Los archivos del disco no cambian.",
|
||||
"Tutto ciò che segue è salvato solo qui, su questo dispositivo. I file sul disco non cambiano.",
|
||||
"Tudo abaixo fica guardado só aqui, neste aparelho. Os arquivos no disco não mudam.",
|
||||
"Quyidagilarning barchasi faqat shu yerda, shu qurilmada saqlanadi. Diskdagi fayllar o‘zgarmaydi.",
|
||||
"Төмендегінің бәрі тек осында, осы құрылғыда сақталады. Дисктегі файлдар өзгермейді.",
|
||||
],
|
||||
[
|
||||
"Used {used} · free for the site {free}",
|
||||
"Занято {used} · свободно для сайта {free}",
|
||||
"Utilisé {used} · libre pour le site {free}",
|
||||
"Belegt {used} · frei für die Website {free}",
|
||||
"Ocupado {used} · libre para el sitio {free}",
|
||||
"Occupato {used} · libero per il sito {free}",
|
||||
"Ocupado {used} · livre para o site {free}",
|
||||
"Band {used} · sayt uchun bo‘sh {free}",
|
||||
"Бос емес {used} · сайт үшін бос {free}",
|
||||
],
|
||||
[
|
||||
"Persistent storage: on",
|
||||
"Постоянное хранение: включено",
|
||||
"Stockage persistant : activé",
|
||||
"Dauerhafte Speicherung: an",
|
||||
"Almacenamiento persistente: activado",
|
||||
"Archiviazione persistente: attiva",
|
||||
"Armazenamento persistente: ativado",
|
||||
"Doimiy saqlash: yoqilgan",
|
||||
"Тұрақты сақтау: қосулы",
|
||||
],
|
||||
[
|
||||
"Persistent storage: not allowed by the browser",
|
||||
"Постоянное хранение: не разрешено браузером",
|
||||
"Stockage persistant : refusé par le navigateur",
|
||||
"Dauerhafte Speicherung: vom Browser nicht erlaubt",
|
||||
"Almacenamiento persistente: no permitido por el navegador",
|
||||
"Archiviazione persistente: non consentita dal browser",
|
||||
"Armazenamento persistente: não permitido pelo navegador",
|
||||
"Doimiy saqlash: brauzer ruxsat bermagan",
|
||||
"Тұрақты сақтау: браузер рұқсат етпеген",
|
||||
],
|
||||
[
|
||||
"Ask the browser",
|
||||
"Спросить браузер",
|
||||
"Demander au navigateur",
|
||||
"Browser fragen",
|
||||
"Pedírselo al navegador",
|
||||
"Chiedi al browser",
|
||||
"Pedir ao navegador",
|
||||
"Brauzerdan so‘rash",
|
||||
"Браузерден сұрау",
|
||||
],
|
||||
[
|
||||
"My games · {n}",
|
||||
"Мои партии · {n}",
|
||||
"Mes parties · {n}",
|
||||
"Meine Partien · {n}",
|
||||
"Mis partidas · {n}",
|
||||
"Le mie partite · {n}",
|
||||
"Minhas partidas · {n}",
|
||||
"Mening partiyalarim · {n}",
|
||||
"Менің партияларым · {n}",
|
||||
],
|
||||
[
|
||||
"Download all as PGN",
|
||||
"Скачать всё в PGN",
|
||||
"Tout télécharger en PGN",
|
||||
"Alles als PGN herunterladen",
|
||||
"Descargar todo en PGN",
|
||||
"Scarica tutto in PGN",
|
||||
"Baixar tudo em PGN",
|
||||
"Hammasini PGN qilib yuklab olish",
|
||||
"Барлығын PGN етіп жүктеп алу",
|
||||
],
|
||||
[
|
||||
"Stockfish 19 engine",
|
||||
"Движок Stockfish 19",
|
||||
"Moteur Stockfish 19",
|
||||
"Engine Stockfish 19",
|
||||
"Motor Stockfish 19",
|
||||
"Motore Stockfish 19",
|
||||
"Motor Stockfish 19",
|
||||
"Stockfish 19 dvijogi",
|
||||
"Stockfish 19 қозғалтқышы",
|
||||
],
|
||||
[
|
||||
"If you clear the site's data in the browser, all of this is lost. Download your games as PGN to keep them.",
|
||||
"Если очистить данные сайта в браузере, всё это пропадёт. Скачайте свои партии в PGN, чтобы не потерять их.",
|
||||
"Si vous effacez les données du site dans le navigateur, tout cela est perdu. Téléchargez vos parties en PGN pour les garder.",
|
||||
"Wenn Sie die Daten der Website im Browser löschen, geht all das verloren. Laden Sie Ihre Partien als PGN herunter, um sie zu behalten.",
|
||||
"Si borras los datos del sitio en el navegador, todo esto se pierde. Descarga tus partidas en PGN para conservarlas.",
|
||||
"Se cancelli i dati del sito nel browser, tutto questo va perso. Scarica le tue partite in PGN per conservarle.",
|
||||
"Se você limpar os dados do site no navegador, tudo isso se perde. Baixe suas partidas em PGN para não perdê-las.",
|
||||
"Agar brauzerda sayt ma’lumotlarini tozalasangiz, bularning barchasi yo‘qoladi. Partiyalaringizni saqlab qolish uchun ularni PGN qilib yuklab oling.",
|
||||
"Браузерде сайт деректерін тазаласаңыз, мұның бәрі жоғалады. Партияларыңызды сақтау үшін оларды PGN етіп жүктеп алыңыз.",
|
||||
],
|
||||
[
|
||||
"It evaluates the position, shows the best moves and reviews the game. It is downloaded once and kept in this browser.",
|
||||
"Оценивает позицию, показывает лучшие ходы и разбирает партию. Скачивается один раз и хранится в этом браузере.",
|
||||
"Il évalue la position, montre les meilleurs coups et analyse la partie. Il est téléchargé une fois et gardé dans ce navigateur.",
|
||||
"Sie bewertet die Stellung, zeigt die besten Züge und analysiert die Partie. Sie wird einmal heruntergeladen und in diesem Browser gespeichert.",
|
||||
"Evalúa la posición, muestra las mejores jugadas y analiza la partida. Se descarga una vez y se guarda en este navegador.",
|
||||
"Valuta la posizione, mostra le mosse migliori e analizza la partita. Si scarica una volta e resta in questo browser.",
|
||||
"Avalia a posição, mostra os melhores lances e analisa a partida. É baixado uma vez e fica guardado neste navegador.",
|
||||
"U pozitsiyani baholaydi, eng yaxshi yurishlarni ko‘rsatadi va partiyani tahlil qiladi. Bir marta yuklab olinadi va shu brauzerda saqlanadi.",
|
||||
"Ол позицияны бағалайды, ең жақсы жүрістерді көрсетеді және партияны талдайды. Бір рет жүктеліп, осы браузерде сақталады.",
|
||||
],
|
||||
[
|
||||
"Size: {size}",
|
||||
"Размер: {size}",
|
||||
"Taille : {size}",
|
||||
"Größe: {size}",
|
||||
"Tamaño: {size}",
|
||||
"Dimensione: {size}",
|
||||
"Tamanho: {size}",
|
||||
"Hajmi: {size}",
|
||||
"Көлемі: {size}",
|
||||
],
|
||||
[
|
||||
"free for the site: {free}",
|
||||
"свободно для сайта: {free}",
|
||||
"libre pour le site : {free}",
|
||||
"frei für die Website: {free}",
|
||||
"libre para el sitio: {free}",
|
||||
"libero per il sito: {free}",
|
||||
"livre para o site: {free}",
|
||||
"sayt uchun bo‘sh: {free}",
|
||||
"сайт үшін бос: {free}",
|
||||
],
|
||||
[
|
||||
"Release to open",
|
||||
"Отпустите, чтобы открыть",
|
||||
|
|
|
|||
|
|
@ -193,6 +193,8 @@ pub struct Header {
|
|||
pub format_hint: String,
|
||||
/// A database downloaded from Lichess and Chess.com: its "⟳ New games".
|
||||
pub online: Option<OnlineButton>,
|
||||
/// A file the browser holds only for this visit: "Keep a copy in the browser".
|
||||
pub keep_copy: bool,
|
||||
}
|
||||
|
||||
pub struct OnlineButton {
|
||||
|
|
@ -969,6 +971,10 @@ impl LargeView {
|
|||
filters_shown,
|
||||
),
|
||||
] {
|
||||
// The search by position is not in every version.
|
||||
if pane == Pane::Board && !crate::platform::CAPS.reference {
|
||||
continue;
|
||||
}
|
||||
let hint = if on { tr("Hide the panel") } else { hint };
|
||||
if ui.selectable_label(on, label).on_hover_text(hint).clicked() {
|
||||
match (pane, on) {
|
||||
|
|
@ -1835,6 +1841,14 @@ impl LargeView {
|
|||
if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() {
|
||||
open_notes = true;
|
||||
}
|
||||
if header.keep_copy
|
||||
&& ui
|
||||
.add(egui::Button::new(tr("📋 Keep a copy in the browser")).small())
|
||||
.on_hover_text(tr("The copy opens right away, without choosing the file. It is stored in this browser on this device and is lost if you clear the site's data. The file on disk is not changed."))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::KeepCopy(path.to_path_buf()));
|
||||
}
|
||||
// A database from Lichess and Chess.com: its new games.
|
||||
if let Some(online) = &header.online {
|
||||
if online.busy {
|
||||
|
|
@ -1913,7 +1927,9 @@ impl LargeView {
|
|||
self.focus_search = true;
|
||||
}
|
||||
}
|
||||
if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B)) {
|
||||
if crate::platform::CAPS.reference
|
||||
&& ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B))
|
||||
{
|
||||
self.pane = Pane::Board;
|
||||
}
|
||||
// Ctrl+Shift+Backspace: all conditions, the quick search and the position included.
|
||||
|
|
|
|||
|
|
@ -31,6 +31,8 @@ mod i18n;
|
|||
mod large_db;
|
||||
mod library;
|
||||
mod maia_download;
|
||||
#[cfg(web)]
|
||||
mod my_games;
|
||||
mod notation;
|
||||
mod online;
|
||||
#[cfg(not(web))]
|
||||
|
|
@ -69,6 +71,8 @@ pub async fn start_web(
|
|||
lang: Option<String>,
|
||||
) -> Result<(), wasm_bindgen::JsValue> {
|
||||
platform::web::vfs::load().await;
|
||||
platform::web::engine::probe().await;
|
||||
platform::web::storage::refresh(|| {});
|
||||
let mut settings = settings::Settings::load();
|
||||
if let Some(chosen) = lang.as_deref().and_then(i18n::Lang::from_locale)
|
||||
&& chosen != settings.language
|
||||
|
|
|
|||
|
|
@ -57,6 +57,11 @@ pub enum LibraryAction {
|
|||
#[cfg(not(web))]
|
||||
OpenUpdate,
|
||||
RemoveDatabase(PathBuf),
|
||||
/// A file the browser held for the last visit only: choose it again, the new one
|
||||
/// taking its place on the shelf.
|
||||
ChooseAgain(PathBuf),
|
||||
/// Keep a copy of a file in the browser (it opens then without choosing it).
|
||||
KeepCopy(PathBuf),
|
||||
OpenSettings,
|
||||
/// A new, empty PGN database (own-databases.md §2).
|
||||
NewDatabase,
|
||||
|
|
@ -341,6 +346,10 @@ impl Library {
|
|||
if crate::examples::is_example(path) {
|
||||
return Some(Block::Example);
|
||||
}
|
||||
// In a browser the user's files are only read.
|
||||
if cfg!(web) && crate::platform::fs::meta(path).is_ok_and(|m| m.readonly) {
|
||||
return Some(Block::ReadOnly);
|
||||
}
|
||||
if !self.files.exists(path) {
|
||||
return Some(Block::Missing);
|
||||
}
|
||||
|
|
@ -1091,6 +1100,11 @@ impl Library {
|
|||
});
|
||||
trf("loading… {n}", &[("n", &p.games)])
|
||||
}
|
||||
Some(Slot::Failed(_)) | None
|
||||
if crate::platform::files::session_only(path) && !self.files.exists(path) =>
|
||||
{
|
||||
tr("↻ Choose the file again").into()
|
||||
}
|
||||
Some(Slot::Failed(_)) => tr("error").into(),
|
||||
None if !self.files.exists(path) => tr("file not found").into(),
|
||||
// Not opened: its games once counted, nothing till then.
|
||||
|
|
@ -1261,6 +1275,25 @@ impl Library {
|
|||
});
|
||||
return;
|
||||
}
|
||||
Some(Slot::Failed(_))
|
||||
if crate::platform::files::session_only(&path) && !self.files.exists(&path) =>
|
||||
{
|
||||
// A browser keeps no way back to a file the user chose (Firefox, Safari).
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(40.0);
|
||||
ui.label(tr("This browser doesn't remember files: after a reload, choose the file again or keep a copy in the browser."));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(tr("↻ Choose the file again")).clicked() {
|
||||
actions.push(LibraryAction::ChooseAgain(path.clone()));
|
||||
}
|
||||
if ui.button(tr("Remove from list")).clicked() {
|
||||
actions.push(LibraryAction::RemoveDatabase(path.clone()));
|
||||
}
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
Some(Slot::Failed(e)) => {
|
||||
let e = e.clone();
|
||||
ui.vertical_centered(|ui| {
|
||||
|
|
@ -1349,6 +1382,7 @@ impl Library {
|
|||
format,
|
||||
format_hint,
|
||||
online,
|
||||
keep_copy: crate::platform::files::session_only(path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
67
apps/desktop/src/my_games.rs
Normal file
67
apps/desktop/src/my_games.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
//! «My games» of the web version (docs/design/web-version.md §2.3): one PGN database
|
||||
//! kept in the browser (the page's `/data`, in IndexedDB), always on the shelf. Saving
|
||||
//! a game (Ctrl+S, 💾) puts it there — into its own record, or as a new one; the user's
|
||||
//! files are only read. «Download all as PGN» gives it back as a file.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::i18n::tr;
|
||||
use crate::settings::Settings;
|
||||
|
||||
const DIR: &str = "my-games";
|
||||
|
||||
/// The database: `/data/my-games/<name>.pgn`, named in the language of the first start.
|
||||
pub fn path() -> PathBuf {
|
||||
let dir = crate::platform::data_dir().unwrap_or_default().join(DIR);
|
||||
crate::platform::web::vfs::list(&dir)
|
||||
.into_iter()
|
||||
.find(|p| p.extension().is_some_and(|e| e == "pgn"))
|
||||
.unwrap_or_else(|| dir.join(format!("{}.pgn", tr("My games"))))
|
||||
}
|
||||
|
||||
/// Makes the database at the first start and keeps it on the shelf; `true` when the
|
||||
/// settings changed.
|
||||
pub fn setup(settings: &mut Settings) -> bool {
|
||||
let path = path();
|
||||
if !crate::platform::fs::exists(&path) {
|
||||
let _ = crate::platform::fs::write_atomic(&path, b"");
|
||||
}
|
||||
if settings.databases.contains(&path) {
|
||||
return false;
|
||||
}
|
||||
settings.databases.push(path);
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether `path` is «My games».
|
||||
pub fn is(path: &std::path::Path) -> bool {
|
||||
path == self::path()
|
||||
}
|
||||
|
||||
/// Gives all of «My games» as a downloaded PGN file (`ChessPenguin-my-games-<date>.pgn`).
|
||||
pub fn download_all() -> Result<(), String> {
|
||||
let text = crate::platform::fs::read_to_string(&path()).map_err(|e| e.to_string())?;
|
||||
let date = chrono::Local::now().format("%Y-%m-%d");
|
||||
crate::platform::files::download_pgn(&format!("ChessPenguin-my-games-{date}.pgn"), &text)
|
||||
}
|
||||
|
||||
/// Games in «My games» (records of its text; 0 when empty).
|
||||
pub fn count() -> usize {
|
||||
crate::platform::fs::read(&path())
|
||||
.ok()
|
||||
.and_then(|b| {
|
||||
chess_core::PgnDatabase::from_bytes(
|
||||
b,
|
||||
Some(chess_core::TextEncoding::Utf8),
|
||||
&mut |_| {},
|
||||
&std::sync::atomic::AtomicBool::new(false),
|
||||
)
|
||||
.ok()
|
||||
})
|
||||
.map_or(0, |db| db.len())
|
||||
}
|
||||
|
||||
/// Its size in bytes.
|
||||
pub fn size() -> u64 {
|
||||
crate::platform::fs::meta(&path()).map_or(0, |m| m.len)
|
||||
}
|
||||
|
|
@ -11,9 +11,72 @@ const DATABASES: [&str; 10] = [
|
|||
"pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z",
|
||||
];
|
||||
|
||||
/// Asks the user for databases to open; `then` gets their paths (nothing when the
|
||||
/// 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;
|
||||
|
||||
/// 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).
|
||||
#[derive(Default)]
|
||||
pub struct Picked {
|
||||
pub paths: Vec<PathBuf>,
|
||||
pub too_big: Vec<(String, u64)>,
|
||||
}
|
||||
|
||||
/// A file the browser holds for this visit only (one the user chose or dropped): after
|
||||
/// a reload it is gone, the user chooses it again or keeps a copy. Never on a computer.
|
||||
pub fn session_only(path: &std::path::Path) -> bool {
|
||||
#[cfg(web)]
|
||||
return path.starts_with(super::web::vfs::OPENED);
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// 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).
|
||||
#[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;
|
||||
if let Some(free) = super::storage_free()
|
||||
&& need + need / 10 > free
|
||||
{
|
||||
return 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)
|
||||
}
|
||||
|
||||
/// Why no copy was kept.
|
||||
#[cfg(web)]
|
||||
pub enum KeepCopy {
|
||||
NoRoom { need: u64, free: u64 },
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Asks the user for databases to open; `then` gets what was chosen (nothing when the
|
||||
/// user cancelled). The dialog does not hold the screen: `then` comes later.
|
||||
pub fn pick_databases(then: impl FnOnce(Vec<PathBuf>) + Send + 'static) {
|
||||
pub fn pick_databases(then: impl FnOnce(Picked) + Send + 'static) {
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
use crate::i18n::tr;
|
||||
|
|
@ -26,7 +89,10 @@ pub fn pick_databases(then: impl FnOnce(Vec<PathBuf>) + Send + 'static) {
|
|||
.add_filter("PGN", &["pgn", "PGN"])
|
||||
.add_filter(tr("All files"), &["*"])
|
||||
.pick_files();
|
||||
then(picked.unwrap_or_default());
|
||||
then(Picked {
|
||||
paths: picked.unwrap_or_default(),
|
||||
too_big: Vec::new(),
|
||||
});
|
||||
});
|
||||
}
|
||||
#[cfg(web)]
|
||||
|
|
@ -37,21 +103,14 @@ pub fn pick_databases(then: impl FnOnce(Vec<PathBuf>) + Send + 'static) {
|
|||
.map(|e| format!(".{e}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
super::web::page::pick_files(&accept, move |files| {
|
||||
then(
|
||||
files
|
||||
.into_iter()
|
||||
.map(|(name, bytes)| super::web::vfs::add_opened(&name, bytes))
|
||||
.collect(),
|
||||
);
|
||||
});
|
||||
super::web::page::pick_files(&accept, move |files| then(opened(files)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The files dropped on the window in this frame, as databases to open: `then` gets
|
||||
/// their paths once read (in a browser they are kept for the session like chosen
|
||||
/// ones). The desktop program does not take dropped files: nothing comes there.
|
||||
pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Vec<PathBuf>) + Send + 'static) {
|
||||
pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Picked) + Send + 'static) {
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let _ = (ctx, then);
|
||||
|
|
@ -69,13 +128,21 @@ pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Vec<PathBuf>) + Send
|
|||
return;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let read = super::web::page::read_files(files).await;
|
||||
then(
|
||||
read.into_iter()
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ use web as imp;
|
|||
pub mod clipboard;
|
||||
pub mod files;
|
||||
pub mod fs;
|
||||
pub mod pgn_store;
|
||||
|
||||
/// What the platform offers the interface: a feature it lacks is not shown.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
|
|
@ -46,6 +47,9 @@ pub struct Caps {
|
|||
pub training: bool,
|
||||
/// Saving a game is a download of its PGN (the browser's files are not written).
|
||||
pub download_pgn: bool,
|
||||
/// The reference tab (what was played here in the databases) and the search of a
|
||||
/// position in a database (not in the light web version).
|
||||
pub reference: bool,
|
||||
}
|
||||
|
||||
/// The features of this platform.
|
||||
|
|
@ -60,6 +64,7 @@ pub const CAPS: Caps = Caps {
|
|||
engine_programs: true,
|
||||
training: true,
|
||||
download_pgn: false,
|
||||
reference: true,
|
||||
};
|
||||
|
||||
/// The features of this platform: the light web version (`docs/decisions.md`, «Веб-версия»).
|
||||
|
|
@ -74,6 +79,7 @@ pub const CAPS: Caps = Caps {
|
|||
engine_programs: false,
|
||||
training: false,
|
||||
download_pgn: true,
|
||||
reference: false,
|
||||
};
|
||||
|
||||
/// The program's settings (`~/.config/chesspenguin`; in a browser, its storage).
|
||||
|
|
@ -105,6 +111,27 @@ pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result
|
|||
imp::spawn(name, job)
|
||||
}
|
||||
|
||||
/// Bytes the browser still gives the site to keep (its quota less what is used); `None`
|
||||
/// on a computer and until the browser answered.
|
||||
pub fn storage_free() -> Option<u64> {
|
||||
#[cfg(web)]
|
||||
return web::storage::usage().map(|(used, quota)| quota.saturating_sub(used));
|
||||
#[cfg(not(web))]
|
||||
None
|
||||
}
|
||||
|
||||
/// A size for people: "340 KB", "96 MB", "9.6 GB".
|
||||
pub fn size_text(bytes: u64) -> String {
|
||||
let b = bytes as f64;
|
||||
if b >= 1e9 {
|
||||
format!("{:.1} GB", b / 1e9)
|
||||
} else if b >= 1e6 {
|
||||
format!("{:.0} MB", b / 1e6)
|
||||
} else {
|
||||
format!("{:.0} KB", (b / 1e3).max(1.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// A line for the program's log (`chesspenguin.log`; in a browser its console).
|
||||
pub fn log(line: &str) {
|
||||
#[cfg(not(web))]
|
||||
|
|
|
|||
86
apps/desktop/src/platform/pgn_store.rs
Normal file
86
apps/desktop/src/platform/pgn_store.rs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
//! Writing games into a PGN database the library has open: its file on a computer
|
||||
//! (`chess_core::pgn::store`, as before); in a browser the page's file of that path
|
||||
//! (only the program's own: «My games»; the user's files are only read). The text
|
||||
//! written is the same byte for byte.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use chess_core::PgnDatabase;
|
||||
use chess_core::pgn::store::{self, Appended, Removed, WriteError};
|
||||
|
||||
#[cfg(web)]
|
||||
fn write(path: &Path, bytes: Vec<u8>) -> Result<(), WriteError> {
|
||||
super::web::vfs::write(path, bytes).map_err(WriteError::Io)
|
||||
}
|
||||
|
||||
#[cfg(web)]
|
||||
fn utf8(db: &PgnDatabase) -> Result<(), WriteError> {
|
||||
if db.encoding() != chess_core::TextEncoding::Utf8 && !db.detected_encoding().ascii_only {
|
||||
return Err(WriteError::Encoding);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds `record` at the end of `db` (the file `path`).
|
||||
pub fn append(db: &PgnDatabase, path: &Path, record: &str) -> Result<Appended, WriteError> {
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let _ = path;
|
||||
store::append(db, record)
|
||||
}
|
||||
#[cfg(web)]
|
||||
{
|
||||
utf8(db)?;
|
||||
let (bytes, offset) = store::appended(db, record);
|
||||
write(path, bytes)?;
|
||||
Ok(Appended { offset })
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces record `index` of `db` with `record`.
|
||||
pub fn replace(
|
||||
db: &PgnDatabase,
|
||||
path: &Path,
|
||||
index: usize,
|
||||
record: &str,
|
||||
) -> Result<(), WriteError> {
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let _ = path;
|
||||
store::replace(db, index, record)
|
||||
}
|
||||
#[cfg(web)]
|
||||
{
|
||||
utf8(db)?;
|
||||
write(path, store::replaced(db, index, record)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes record `index` of `db`; [`restore`] puts it back.
|
||||
pub fn remove(db: &PgnDatabase, path: &Path, index: usize) -> Result<Removed, WriteError> {
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let _ = path;
|
||||
store::remove(db, index)
|
||||
}
|
||||
#[cfg(web)]
|
||||
{
|
||||
utf8(db)?;
|
||||
let (bytes, gone) = store::removed(db, index)?;
|
||||
write(path, bytes)?;
|
||||
Ok(gone)
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a removed record back at its place.
|
||||
pub fn restore(db: &PgnDatabase, path: &Path, removed: &Removed) -> Result<(), WriteError> {
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let _ = path;
|
||||
store::restore(db, removed)
|
||||
}
|
||||
#[cfg(web)]
|
||||
{
|
||||
write(path, store::restored(db, removed)?)
|
||||
}
|
||||
}
|
||||
199
apps/desktop/src/platform/web/engine.rs
Normal file
199
apps/desktop/src/platform/web/engine.rs
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
//! Stockfish 19 for the web version (npm `stockfish@19.0.1`, nmrugg/stockfish.js,
|
||||
//! GPL-3.0): the single-threaded build, served by our site beside the program
|
||||
//! (`/app/engine/`, apps/web/build.sh). Its `.wasm` (99 MB, 78 MB in Brotli) is
|
||||
//! downloaded only when the user agrees (decisions «Веб-версия»), checked against its
|
||||
//! SHA-256 and kept in the browser's Cache Storage. A worker of the engine gets it as a
|
||||
//! `blob:` address after `#` (the script takes the wasm's address from there): no worker
|
||||
//! downloads it again.
|
||||
//!
|
||||
//! Its search is that of the official Stockfish 19 (the same evaluations, node for node:
|
||||
//! docs/research/web-version-tech.md §2.2), so a game review gives the same marks.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
/// The engine's worker script and its WebAssembly, relative to the page.
|
||||
pub const SCRIPT: &str = "engine/stockfish-19-single.js";
|
||||
const WASM: &str = "engine/stockfish-19-single.wasm";
|
||||
/// The wasm as published (`stockfish@19.0.1`, `bin/stockfish-19-single.wasm`).
|
||||
pub const WASM_BYTES: u64 = 99_169_054;
|
||||
const WASM_SHA256: &str = "991bede2f253ebb08ff01fcc48270f4b9c8e66b12d5bd5f8d6f52eb3e3b3a740";
|
||||
/// What travels over the network (the site sends it in Brotli).
|
||||
pub const DOWNLOAD_MB: u64 = 78;
|
||||
/// The cache of the engine; another version of it gets another name.
|
||||
const CACHE: &str = "chesspenguin-engine-sf19.0.1";
|
||||
|
||||
thread_local! {
|
||||
/// The cached wasm as a `blob:` address, once it is there.
|
||||
static BLOB: RefCell<Option<String>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Why the engine could not be downloaded.
|
||||
#[derive(Debug)]
|
||||
pub enum Fetch {
|
||||
Network(String),
|
||||
Server(u16),
|
||||
/// Not the published file.
|
||||
Checksum,
|
||||
/// The browser would not keep it (space, a private window).
|
||||
Storage(String),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
fn js(e: JsValue) -> String {
|
||||
e.as_string()
|
||||
.or_else(|| {
|
||||
e.dyn_ref::<js_sys::Error>()
|
||||
.map(|e| String::from(e.message()))
|
||||
})
|
||||
.unwrap_or_else(|| format!("{e:?}"))
|
||||
}
|
||||
|
||||
fn caches() -> Result<web_sys::CacheStorage, String> {
|
||||
web_sys::window().ok_or("no window")?.caches().map_err(js)
|
||||
}
|
||||
|
||||
async fn open() -> Result<web_sys::Cache, String> {
|
||||
JsFuture::from(caches()?.open(CACHE))
|
||||
.await
|
||||
.map_err(js)?
|
||||
.dyn_into()
|
||||
.map_err(js)
|
||||
}
|
||||
|
||||
/// Makes the cached engine usable (a `blob:` address); called at the start.
|
||||
pub async fn probe() {
|
||||
let found = async {
|
||||
let cache = open().await?;
|
||||
let hit = JsFuture::from(cache.match_with_str(WASM))
|
||||
.await
|
||||
.map_err(js)?;
|
||||
let Ok(response) = hit.dyn_into::<web_sys::Response>() else {
|
||||
return Ok::<_, String>(None);
|
||||
};
|
||||
let blob: web_sys::Blob = JsFuture::from(response.blob().map_err(js)?)
|
||||
.await
|
||||
.map_err(js)?
|
||||
.dyn_into()
|
||||
.map_err(js)?;
|
||||
if blob.size() as u64 != WASM_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
web_sys::Url::create_object_url_with_blob(&blob)
|
||||
.map(Some)
|
||||
.map_err(js)
|
||||
};
|
||||
match found.await {
|
||||
Ok(url) => BLOB.with_borrow_mut(|b| *b = url),
|
||||
Err(e) => log::warn!("the engine's cache: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The address of a worker of the engine, once it is downloaded.
|
||||
pub fn worker_script() -> Option<String> {
|
||||
BLOB.with_borrow(|b| b.as_ref().map(|url| format!("{SCRIPT}#{url}")))
|
||||
}
|
||||
|
||||
/// Downloads the engine into the cache; `progress(done, total)` on the way.
|
||||
pub async fn download(progress: impl Fn(u64, u64), cancel: Arc<AtomicBool>) -> Result<(), Fetch> {
|
||||
let window = web_sys::window().ok_or_else(|| Fetch::Network("no window".into()))?;
|
||||
let response: web_sys::Response = JsFuture::from(window.fetch_with_str(WASM))
|
||||
.await
|
||||
.map_err(|e| Fetch::Network(js(e)))?
|
||||
.dyn_into()
|
||||
.map_err(|e| Fetch::Network(js(e)))?;
|
||||
if !response.ok() {
|
||||
return Err(Fetch::Server(response.status()));
|
||||
}
|
||||
let body = response
|
||||
.body()
|
||||
.ok_or_else(|| Fetch::Network("no body".into()))?;
|
||||
let reader: web_sys::ReadableStreamDefaultReader = body
|
||||
.get_reader()
|
||||
.dyn_into()
|
||||
.map_err(|e| Fetch::Network(js(e.into())))?;
|
||||
let mut bytes: Vec<u8> = Vec::with_capacity(WASM_BYTES as usize);
|
||||
let mut hasher = Sha256::new();
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
let _ = reader.cancel();
|
||||
return Err(Fetch::Cancelled);
|
||||
}
|
||||
let chunk = JsFuture::from(reader.read())
|
||||
.await
|
||||
.map_err(|e| Fetch::Network(js(e)))?;
|
||||
let done = js_sys::Reflect::get(&chunk, &"done".into())
|
||||
.map(|d| d.is_truthy())
|
||||
.unwrap_or(true);
|
||||
if done {
|
||||
break;
|
||||
}
|
||||
let value: js_sys::Uint8Array = js_sys::Reflect::get(&chunk, &"value".into())
|
||||
.map_err(|e| Fetch::Network(js(e)))?
|
||||
.dyn_into()
|
||||
.map_err(|e| Fetch::Network(js(e)))?;
|
||||
let start = bytes.len();
|
||||
bytes.resize(start + value.length() as usize, 0);
|
||||
value.copy_to(&mut bytes[start..]);
|
||||
hasher.update(&bytes[start..]);
|
||||
if bytes.len() as u64 > WASM_BYTES {
|
||||
return Err(Fetch::Checksum);
|
||||
}
|
||||
progress(bytes.len() as u64, WASM_BYTES);
|
||||
}
|
||||
let digest: String = hasher
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect();
|
||||
if bytes.len() as u64 != WASM_BYTES || digest != WASM_SHA256 {
|
||||
return Err(Fetch::Checksum);
|
||||
}
|
||||
let storage = |e: JsValue| Fetch::Storage(js(e));
|
||||
let init = web_sys::ResponseInit::new();
|
||||
let headers = web_sys::Headers::new().map_err(storage)?;
|
||||
headers
|
||||
.set("Content-Type", "application/wasm")
|
||||
.map_err(storage)?;
|
||||
init.set_headers(&headers);
|
||||
let stored = web_sys::Response::new_with_opt_u8_array_and_init(Some(&mut bytes), &init)
|
||||
.map_err(storage)?;
|
||||
let cache = open().await.map_err(Fetch::Storage)?;
|
||||
JsFuture::from(cache.put_with_str(WASM, &stored))
|
||||
.await
|
||||
.map_err(storage)?;
|
||||
drop(bytes);
|
||||
probe().await;
|
||||
if worker_script().is_none() {
|
||||
return Err(Fetch::Storage("the browser did not keep the engine".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the downloaded engine from the browser.
|
||||
pub fn remove() {
|
||||
if let Some(url) = BLOB.with_borrow_mut(Option::take) {
|
||||
let _ = web_sys::Url::revoke_object_url(&url);
|
||||
}
|
||||
if let Ok(c) = caches() {
|
||||
let _ = c.delete(CACHE);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the engine is downloaded and ready.
|
||||
pub fn ready() -> bool {
|
||||
BLOB.with_borrow(Option::is_some)
|
||||
}
|
||||
|
||||
/// Engines working at once for a game review: one per logical processor, as on a
|
||||
/// computer, at most `limit` (each worker holds its own copy of the engine, ≈ 130 MB).
|
||||
pub fn workers(limit: usize) -> usize {
|
||||
let cpus = web_sys::window().map_or(1.0, |w| w.navigator().hardware_concurrency()) as usize;
|
||||
cpus.clamp(1, limit)
|
||||
}
|
||||
|
|
@ -6,8 +6,10 @@
|
|||
//! `/opened` (the files the user gave the page, only read: decisions «Веб-версия») live
|
||||
//! for the session. Background work runs on the page's thread after the frame.
|
||||
|
||||
pub mod engine;
|
||||
pub mod idb;
|
||||
pub mod page;
|
||||
pub mod storage;
|
||||
pub mod vfs;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
|
|
|||
|
|
@ -22,7 +22,13 @@ pub async fn next_task() {
|
|||
let _ = wasm_bindgen_futures::JsFuture::from(promise).await;
|
||||
}
|
||||
|
||||
type Picked = Box<dyn FnOnce(Vec<(String, Vec<u8>)>)>;
|
||||
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)>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// What to do with the files chosen next.
|
||||
|
|
@ -70,12 +76,23 @@ 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).
|
||||
pub async fn read_files(files: Vec<web_sys::File>) -> Vec<(String, Vec<u8>)> {
|
||||
let mut out = Vec::with_capacity(files.len());
|
||||
/// 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.push((f.name(), js_sys::Uint8Array::new(&buf).to_vec())),
|
||||
Ok(buf) => out
|
||||
.read
|
||||
.push((f.name(), js_sys::Uint8Array::new(&buf).to_vec())),
|
||||
Err(e) => log::warn!("cannot read {}: {e:?}", f.name()),
|
||||
}
|
||||
}
|
||||
|
|
@ -85,7 +102,7 @@ pub async fn read_files(files: Vec<web_sys::File>) -> Vec<(String, Vec<u8>)> {
|
|||
/// 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(Vec<(String, Vec<u8>)>) + 'static) {
|
||||
pub fn pick_files(accept: &str, then: impl FnOnce(Read) + 'static) {
|
||||
match open_input(accept) {
|
||||
Ok(input) => {
|
||||
ON_PICKED.with_borrow_mut(|p| *p = Some(Box::new(then)));
|
||||
|
|
|
|||
72
apps/desktop/src/platform/web/storage.rs
Normal file
72
apps/desktop/src/platform/web/storage.rs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
//! What the browser gives the site to keep: the space used and left
|
||||
//! (`navigator.storage.estimate()`: the site's quota, not the disk's free space) and
|
||||
//! whether its data is kept for good (`persist()`: not cleared when space runs low).
|
||||
//! Both are asked for in the background; the screen shows what came last.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
thread_local! {
|
||||
static USAGE: Cell<Option<(u64, u64)>> = const { Cell::new(None) };
|
||||
static PERSISTED: Cell<Option<bool>> = const { Cell::new(None) };
|
||||
}
|
||||
|
||||
fn manager() -> Option<web_sys::StorageManager> {
|
||||
Some(web_sys::window()?.navigator().storage())
|
||||
}
|
||||
|
||||
fn number(o: &wasm_bindgen::JsValue, key: &str) -> Option<u64> {
|
||||
js_sys::Reflect::get(o, &key.into())
|
||||
.ok()?
|
||||
.as_f64()
|
||||
.map(|n| n as u64)
|
||||
}
|
||||
|
||||
/// Asks the browser again how much is used and left; `then` once it answered.
|
||||
pub fn refresh(then: impl FnOnce() + 'static) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
if let Some(m) = manager() {
|
||||
if let Ok(p) = m.estimate()
|
||||
&& let Ok(e) = JsFuture::from(p).await
|
||||
&& let (Some(usage), Some(quota)) = (number(&e, "usage"), number(&e, "quota"))
|
||||
{
|
||||
USAGE.set(Some((usage, quota)));
|
||||
}
|
||||
if let Ok(p) = m.persisted()
|
||||
&& let Ok(v) = JsFuture::from(p).await
|
||||
{
|
||||
PERSISTED.set(v.as_bool());
|
||||
}
|
||||
}
|
||||
then();
|
||||
});
|
||||
}
|
||||
|
||||
/// (used, quota) in bytes, as the browser last said.
|
||||
pub fn usage() -> Option<(u64, u64)> {
|
||||
USAGE.get()
|
||||
}
|
||||
|
||||
/// Whether the site's data is kept for good (`None`: not known yet).
|
||||
pub fn persisted() -> Option<bool> {
|
||||
PERSISTED.get()
|
||||
}
|
||||
|
||||
/// Asks the browser to keep the site's data for good (Firefox asks the user; Chromium
|
||||
/// and Safari decide themselves); `then` with the answer.
|
||||
pub fn persist(then: impl FnOnce(bool) + 'static) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let granted = match manager().and_then(|m| m.persist().ok()) {
|
||||
Some(p) => JsFuture::from(p)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|v| v.dyn_into::<js_sys::Boolean>().ok())
|
||||
.is_some_and(|b| b.value_of()),
|
||||
None => false,
|
||||
};
|
||||
PERSISTED.set(Some(granted));
|
||||
then(granted);
|
||||
});
|
||||
}
|
||||
|
|
@ -118,6 +118,17 @@ pub fn remove(path: &Path) -> io::Result<()> {
|
|||
})
|
||||
}
|
||||
|
||||
/// The files right in the folder `dir`.
|
||||
pub fn list(dir: &Path) -> Vec<PathBuf> {
|
||||
FILES.with_borrow(|files| {
|
||||
files
|
||||
.keys()
|
||||
.filter(|p| p.parent() == Some(dir))
|
||||
.cloned()
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
|
|
|||
|
|
@ -949,6 +949,7 @@ struct ListRow {
|
|||
use crate::review::JobMsg;
|
||||
|
||||
struct EngineJob {
|
||||
runner: crate::review::JobRunner,
|
||||
rx: Receiver<JobMsg>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
total: usize,
|
||||
|
|
@ -1977,11 +1978,15 @@ impl PrepScreen {
|
|||
tx,
|
||||
ctx.clone(),
|
||||
);
|
||||
if let Err(e) = spawned {
|
||||
let runner = match spawned {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
self.error = Some(e.to_string());
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.job = Some(EngineJob {
|
||||
runner,
|
||||
rx,
|
||||
cancel,
|
||||
total,
|
||||
|
|
@ -2000,6 +2005,7 @@ impl PrepScreen {
|
|||
};
|
||||
let mut ended = false;
|
||||
let mut got = false;
|
||||
job.runner.pump();
|
||||
while let Ok(msg) = job.rx.try_recv() {
|
||||
match msg {
|
||||
JobMsg::Event(e) => {
|
||||
|
|
|
|||
|
|
@ -40,9 +40,59 @@ pub enum JobMsg {
|
|||
Failed(String),
|
||||
}
|
||||
|
||||
/// Runs the engine job over `targets` with ChessPenguin's Stockfish at `path` on a
|
||||
/// thread named `name`: its events and its end come through `tx`, each waking `ctx`.
|
||||
/// A browser starts no engine processes: there the job cannot run (the error).
|
||||
/// An engine job under way. On a computer its thread sends everything through the
|
||||
/// channel; in a browser its engines are Web Workers driven from the frames:
|
||||
/// [`JobRunner::pump`] passes on what they gave.
|
||||
pub struct JobRunner {
|
||||
#[cfg(web)]
|
||||
dispatcher: game_review::Dispatcher,
|
||||
#[cfg(web)]
|
||||
tx: std::sync::mpsc::Sender<JobMsg>,
|
||||
#[cfg(web)]
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl JobRunner {
|
||||
/// Call every frame (nothing to do on a computer).
|
||||
pub fn pump(&mut self) {
|
||||
#[cfg(web)]
|
||||
{
|
||||
if self.cancel.load(Ordering::Relaxed) {
|
||||
self.dispatcher.cancel();
|
||||
}
|
||||
let (events, end) = self.dispatcher.poll();
|
||||
for e in events {
|
||||
let _ = self.tx.send(JobMsg::Event(e));
|
||||
}
|
||||
if let Some(end) = end {
|
||||
let _ = self.tx.send(job_end(end));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The last message of a job.
|
||||
fn job_end(result: Result<(), JobFailure>) -> JobMsg {
|
||||
match result {
|
||||
Ok(()) => JobMsg::Done,
|
||||
Err(JobFailure::Start(e) | JobFailure::Engine(e)) => JobMsg::Failed(e),
|
||||
Err(JobFailure::Terminated(reason)) => {
|
||||
JobMsg::Failed(crate::analysis::termination_message(&reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Engines working at once for a job: one per logical CPU, as many as fit.
|
||||
pub fn processes() -> usize {
|
||||
#[cfg(web)]
|
||||
return crate::platform::web::engine::workers(game_review::MAX_PROCESSES);
|
||||
#[cfg(not(web))]
|
||||
game_review::processes(game_review::MAX_PROCESSES)
|
||||
}
|
||||
|
||||
/// Runs the engine job over `targets` with ChessPenguin's Stockfish at `path` (in a
|
||||
/// browser: the address of its worker) named `name`: its events and its end come
|
||||
/// through `tx`, each waking `ctx`.
|
||||
pub fn spawn_job(
|
||||
name: &str,
|
||||
path: PathBuf,
|
||||
|
|
@ -51,7 +101,7 @@ pub fn spawn_job(
|
|||
cancel: Arc<AtomicBool>,
|
||||
tx: std::sync::mpsc::Sender<JobMsg>,
|
||||
ctx: egui::Context,
|
||||
) -> std::io::Result<()> {
|
||||
) -> std::io::Result<JobRunner> {
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
std::thread::Builder::new()
|
||||
|
|
@ -67,26 +117,32 @@ pub fn spawn_job(
|
|||
ctx.request_repaint();
|
||||
},
|
||||
);
|
||||
let msg = match result {
|
||||
Ok(()) => JobMsg::Done,
|
||||
Err(JobFailure::Start(e) | JobFailure::Engine(e)) => JobMsg::Failed(e),
|
||||
Err(JobFailure::Terminated(reason)) => {
|
||||
JobMsg::Failed(crate::analysis::termination_message(&reason))
|
||||
}
|
||||
};
|
||||
let _ = tx.send(msg);
|
||||
let _ = tx.send(job_end(result));
|
||||
ctx.request_repaint();
|
||||
})
|
||||
.map(drop)
|
||||
.map(|_| JobRunner {})
|
||||
}
|
||||
#[cfg(web)]
|
||||
{
|
||||
let _ = (name, path, settings, targets, cancel, tx, ctx);
|
||||
Err(std::io::ErrorKind::Unsupported.into())
|
||||
let _ = name;
|
||||
let wake: Arc<dyn Fn() + Send + Sync> = Arc::new(move || ctx.request_repaint());
|
||||
game_review::Dispatcher::start(&path.to_string_lossy(), &settings, targets, wake)
|
||||
.map(|dispatcher| JobRunner {
|
||||
dispatcher,
|
||||
tx,
|
||||
cancel,
|
||||
})
|
||||
.map_err(|e| match e {
|
||||
JobFailure::Start(e) | JobFailure::Engine(e) => std::io::Error::other(e),
|
||||
JobFailure::Terminated(r) => {
|
||||
std::io::Error::other(crate::analysis::termination_message(&r))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Job {
|
||||
runner: JobRunner,
|
||||
rx: Receiver<JobMsg>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
total: usize,
|
||||
|
|
@ -117,9 +173,27 @@ fn cache_dir() -> Option<PathBuf> {
|
|||
Settings::cache_dir().map(|d| d.join("analysis"))
|
||||
}
|
||||
|
||||
/// The cached analyses in the program's files (the platform's: a folder of the disk, or
|
||||
/// the browser's storage).
|
||||
struct Cache(PathBuf);
|
||||
|
||||
impl game_review::CacheStore for Cache {
|
||||
fn read(&self, name: &str) -> Option<Vec<u8>> {
|
||||
crate::platform::fs::read(&self.0.join(name)).ok()
|
||||
}
|
||||
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> {
|
||||
crate::platform::fs::write_atomic(&self.0.join(name), bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl Review {
|
||||
pub fn new(game: &Game) -> Self {
|
||||
let analysis = GameAnalysis::new(game, cache_dir().as_deref());
|
||||
let cache = cache_dir().map(Cache);
|
||||
let analysis = GameAnalysis::with_store(
|
||||
game,
|
||||
cache.as_ref().map(|c| c as &dyn game_review::CacheStore),
|
||||
);
|
||||
Review {
|
||||
visible: analysis.has_data(),
|
||||
analysis,
|
||||
|
|
@ -175,11 +249,15 @@ impl Review {
|
|||
tx,
|
||||
ctx.clone(),
|
||||
);
|
||||
if let Err(e) = spawned {
|
||||
let runner = match spawned {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
self.error = Some(e.to_string());
|
||||
return false;
|
||||
}
|
||||
};
|
||||
self.job = Some(Job {
|
||||
runner,
|
||||
rx,
|
||||
cancel,
|
||||
total,
|
||||
|
|
@ -201,6 +279,7 @@ impl Review {
|
|||
return false;
|
||||
};
|
||||
let mut ended = false;
|
||||
job.runner.pump();
|
||||
while let Ok(msg) = job.rx.try_recv() {
|
||||
match msg {
|
||||
JobMsg::Event(e) => {
|
||||
|
|
@ -258,7 +337,7 @@ impl Review {
|
|||
|
||||
fn save_cache(&self) {
|
||||
if let Some(dir) = cache_dir()
|
||||
&& let Err(e) = self.analysis.save_cache(&dir)
|
||||
&& let Err(e) = self.analysis.save_to(&Cache(dir.clone()))
|
||||
{
|
||||
eprintln!("review cache: {}: {e}", dir.display());
|
||||
}
|
||||
|
|
@ -757,12 +836,6 @@ impl Drop for Review {
|
|||
/// Nodes per second of one engine thread assumed until an engine was measured.
|
||||
pub const DEFAULT_NPS: f64 = 700_000.0;
|
||||
|
||||
/// Engine processes of a game analysis on this computer: one per logical CPU, at most
|
||||
/// `game_review::MAX_PROCESSES` and what the free memory holds.
|
||||
pub fn processes() -> usize {
|
||||
game_review::processes(game_review::MAX_PROCESSES)
|
||||
}
|
||||
|
||||
/// ChessPenguin's Stockfish at `path` for an analysis job: below the program (nice 10),
|
||||
/// so that the program stays smooth while every CPU works.
|
||||
#[cfg(not(web))]
|
||||
|
|
|
|||
|
|
@ -60,6 +60,16 @@ impl EngineConfig {
|
|||
Some(self.path.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the engine can be started: ChessPenguin's Stockfish is there (in a
|
||||
/// browser: downloaded into it), or the file of another engine.
|
||||
pub fn present(&self) -> bool {
|
||||
if self.builtin {
|
||||
crate::engines::own_stockfish().is_some()
|
||||
} else {
|
||||
self.path.is_file()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Piece animation, with Lichess's durations.
|
||||
|
|
|
|||
|
|
@ -15,10 +15,19 @@ pub enum Tab {
|
|||
Sound,
|
||||
Interface,
|
||||
Translation,
|
||||
/// What the web version keeps in the browser.
|
||||
#[cfg(web)]
|
||||
BrowserData,
|
||||
About,
|
||||
}
|
||||
|
||||
pub enum SettingsAction {
|
||||
/// All of «My games» as a downloaded PGN.
|
||||
#[cfg(web)]
|
||||
DownloadMyGames,
|
||||
/// Ask the browser to keep the site's data for good.
|
||||
#[cfg(web)]
|
||||
KeepData,
|
||||
#[cfg(not(web))]
|
||||
AddEngine,
|
||||
/// Download the official Stockfish (decision 14).
|
||||
|
|
@ -93,6 +102,8 @@ impl SettingsWindow {
|
|||
if crate::platform::CAPS.translation {
|
||||
ui.selectable_value(&mut self.tab, Tab::Translation, tr("Translation"));
|
||||
}
|
||||
#[cfg(web)]
|
||||
ui.selectable_value(&mut self.tab, Tab::BrowserData, tr("Browser data"));
|
||||
ui.selectable_value(&mut self.tab, Tab::About, tr("About"));
|
||||
});
|
||||
ui.separator();
|
||||
|
|
@ -100,6 +111,8 @@ impl SettingsWindow {
|
|||
Tab::Engines => self.engines(ui, s, &mut actions, &mut changed),
|
||||
Tab::Board => board_tab(ui, s, &mut changed),
|
||||
Tab::Translation => changed |= translation.settings_tab(ui, s),
|
||||
#[cfg(web)]
|
||||
Tab::BrowserData => browser_data(ui, &mut actions),
|
||||
Tab::Sound => sound_tab(ui, s, &mut actions, &mut changed),
|
||||
Tab::About => {
|
||||
let (status, available) =
|
||||
|
|
@ -791,3 +804,67 @@ fn updates(
|
|||
))
|
||||
.changed();
|
||||
}
|
||||
|
||||
/// Settings → Browser data (docs/design/web-version.md §2.3): what is kept only in this
|
||||
/// browser, how much room it takes and is left, and the way to take «My games» along.
|
||||
#[cfg(web)]
|
||||
fn browser_data(ui: &mut Ui, actions: &mut Vec<SettingsAction>) {
|
||||
use crate::platform::{size_text, web};
|
||||
ui.label(tr(
|
||||
"Everything below is stored only here, on this device. Files on disk are not changed.",
|
||||
));
|
||||
ui.add_space(6.0);
|
||||
if let Some((used, quota)) = web::storage::usage() {
|
||||
ui.label(trf(
|
||||
"Used {used} · free for the site {free}",
|
||||
&[
|
||||
("used", &size_text(used)),
|
||||
("free", &size_text(quota.saturating_sub(used))),
|
||||
],
|
||||
));
|
||||
}
|
||||
ui.horizontal(|ui| match web::storage::persisted() {
|
||||
Some(true) => {
|
||||
ui.label(tr("Persistent storage: on"));
|
||||
}
|
||||
_ => {
|
||||
ui.label(
|
||||
RichText::new(tr("Persistent storage: not allowed by the browser"))
|
||||
.color(ui.visuals().warn_fg_color),
|
||||
);
|
||||
if ui.button(tr("Ask the browser")).clicked() {
|
||||
actions.push(SettingsAction::KeepData);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
egui::Grid::new("browser data")
|
||||
.num_columns(3)
|
||||
.spacing([16.0, 6.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label(trf(
|
||||
"My games · {n}",
|
||||
&[("n", &crate::i18n::games(crate::my_games::count()))],
|
||||
));
|
||||
ui.label(size_text(crate::my_games::size()));
|
||||
if ui.button(tr("Download all as PGN")).clicked() {
|
||||
actions.push(SettingsAction::DownloadMyGames);
|
||||
}
|
||||
ui.end_row();
|
||||
if web::engine::ready() {
|
||||
ui.label(tr("Stockfish 19 engine"));
|
||||
ui.label(size_text(web::engine::WASM_BYTES));
|
||||
if ui.button(tr("Delete")).clicked() {
|
||||
actions.push(SettingsAction::RemoveDownloaded);
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"If you clear the site's data in the browser, all of this is lost. Download your games as PGN to keep them.",
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,6 +37,27 @@ if command -v wasm-opt >/dev/null 2>&1; then
|
|||
fi
|
||||
|
||||
cp "$here/page/device.js" "$here/page/page.js" "$out/"
|
||||
|
||||
# The engine: Stockfish.js 19.0.1 (npm `stockfish`, GPL-3.0), its single-threaded build,
|
||||
# checked against the registry's integrity (THIRD_PARTY_NOTICES.md). STOCKFISH_TGZ= points
|
||||
# at a copy of the package; otherwise it is downloaded once into target/web/.
|
||||
sf_url=https://registry.npmjs.org/stockfish/-/stockfish-19.0.1.tgz
|
||||
sf_sha512=bTwsO4e9HAwPBKls1+szcfibmaWRNzTF20rQE/XPdB3LOSoT6XTZDr1zYwriwSRRFT5MkvqrglPmJrKEVXGnyQ==
|
||||
tgz=${STOCKFISH_TGZ:-$root/target/web/stockfish-19.0.1.tgz}
|
||||
if [ ! -f "$tgz" ]; then
|
||||
mkdir -p "$(dirname "$tgz")"
|
||||
curl -fsSL --retry 3 -o "$tgz.part" "$sf_url"
|
||||
mv "$tgz.part" "$tgz"
|
||||
fi
|
||||
have_sha=$(openssl dgst -sha512 -binary "$tgz" | base64 -w0)
|
||||
if [ "$have_sha" != "$sf_sha512" ]; then
|
||||
echo "$tgz is not stockfish@19.0.1 (sha512 $have_sha)" >&2
|
||||
exit 1
|
||||
fi
|
||||
mkdir -p "$out/engine"
|
||||
tar -xzf "$tgz" -C "$out/engine" --strip-components=2 \
|
||||
package/bin/stockfish-19-single.js package/bin/stockfish-19-single.wasm
|
||||
tar -xzf "$tgz" -C "$out/engine" --strip-components=1 package/Copying.txt
|
||||
for size in 32 64 180; do
|
||||
cp "$root/website/static/img/icon-$size.png" "$out/"
|
||||
done
|
||||
|
|
|
|||
99
apps/web/check/review.mjs
Normal file
99
apps/web/check/review.mjs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
// The game review of the web version against the desktop program's, on games of the
|
||||
// chess.com check set (crates/game-review/chesscom/): the browser reviews them (Stockfish
|
||||
// 19 wasm in workers), its evaluations are read out of its storage and compared with the
|
||||
// ones `chesscom_check` keeps (target/chesscom-check/v1): the same search must give the
|
||||
// same evaluations, so the same !!/!.
|
||||
//
|
||||
// node apps/web/check/review.mjs <app-dir> <out-dir> <native-cache-dir> <game.pgn>...
|
||||
import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { session } from './steps.mjs';
|
||||
import { sleep } from './bidi.mjs';
|
||||
|
||||
const [appDir, outDir, nativeDir, ...games] = process.argv.slice(2);
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
const all = join(outDir, 'chesscom-games.pgn');
|
||||
writeFileSync(all, games.map((g) => readFileSync(g, 'utf8').trim()).join('\n\n') + '\n');
|
||||
|
||||
const s = await session(appDir);
|
||||
const { t } = s;
|
||||
const stored = `new Promise((ok, no) => {
|
||||
const q = indexedDB.open('chesspenguin');
|
||||
q.onerror = () => no('no db');
|
||||
q.onsuccess = () => {
|
||||
const st = q.result.transaction('files').objectStore('files');
|
||||
const keys = st.getAllKeys(), values = st.getAll();
|
||||
values.onsuccess = () => ok(keys.result.map((k, i) => [k, new TextDecoder().decode(values.result[i])])
|
||||
.filter(([k]) => k.startsWith('/cache/analysis/')));
|
||||
};
|
||||
})`;
|
||||
let failed = 0;
|
||||
try {
|
||||
await s.run({ url: '?lang=en' }, outDir);
|
||||
await sleep(2000);
|
||||
// The games in one file, reviewed one by one.
|
||||
await s.run({ key: 'o', mods: ['ctrl'] }, outDir);
|
||||
await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000);
|
||||
const input = await s.ff.browser.send('script.evaluate', {
|
||||
expression: `document.getElementById('cp-open-files')`, target: { context: t.context }, awaitPromise: false,
|
||||
});
|
||||
await s.ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: input.result.sharedId }, files: [all] });
|
||||
await sleep(3000);
|
||||
await s.run({ shot: 'review-0-opened.png' }, outDir);
|
||||
for (let i = 0; i < games.length; i++) {
|
||||
const before = (await t.evaluate(stored)).length;
|
||||
await s.run({ click: [300, 214 + 27 * i], double: true }, outDir);
|
||||
await sleep(1500);
|
||||
await s.run({ key: 'a', mods: ['shift'] }, outDir);
|
||||
// The first time the engine is offered: downloaded, the review starts by itself.
|
||||
if (i === 0) {
|
||||
await sleep(1000);
|
||||
await s.run({ shot: 'review-0-offer.png' }, outDir);
|
||||
await s.run({ key: 'enter' }, outDir);
|
||||
await sleep(5000);
|
||||
await s.run({ shot: 'review-0-downloading.png' }, outDir);
|
||||
}
|
||||
const t0 = Date.now();
|
||||
for (;;) {
|
||||
await sleep(2000);
|
||||
if ((await t.evaluate(stored)).length > before) break;
|
||||
if (Date.now() - t0 > 600000) throw new Error(`no review of ${games[i]}`);
|
||||
}
|
||||
console.log(`${basename(games[i])}: reviewed in ${((Date.now() - t0) / 1000).toFixed(0)} s`);
|
||||
await s.run({ shot: `review-${i + 1}.png` }, outDir);
|
||||
await s.run({ click: [55, 15] }, outDir);
|
||||
await sleep(1000);
|
||||
}
|
||||
// The comparison.
|
||||
const fromBrowser = await t.evaluate(stored);
|
||||
for (const [key, text] of fromBrowser) {
|
||||
const name = basename(key);
|
||||
writeFileSync(join(outDir, name), text);
|
||||
const web = JSON.parse(text);
|
||||
const nativePath = join(nativeDir, name);
|
||||
if (!existsSync(nativePath)) {
|
||||
console.log(`FAIL ${name}: no native evaluations to compare with`);
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
const native = new Map(JSON.parse(readFileSync(nativePath, 'utf8')).evals);
|
||||
let same = 0, differ = 0, missing = 0;
|
||||
for (const [k, e] of web.evals) {
|
||||
const n = native.get(k);
|
||||
if (!n) { missing++; continue; }
|
||||
if (JSON.stringify(n) === JSON.stringify(e)) same++;
|
||||
else {
|
||||
differ++;
|
||||
if (differ <= 3) console.log(' differs', k.slice(-40), JSON.stringify(n).slice(0, 160), '|', JSON.stringify(e).slice(0, 160));
|
||||
}
|
||||
}
|
||||
const ok = differ === 0 && missing === 0 && same > 0;
|
||||
if (!ok) failed++;
|
||||
console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${same} positions the same${differ ? `, ${differ} differ` : ''}${missing ? `, ${missing} not in the native set` : ''} (engine ${web.meta.engine}, ${web.meta.nodes} nodes)`);
|
||||
}
|
||||
} finally {
|
||||
await s.stop();
|
||||
}
|
||||
for (const e of s.errors) console.log('console:', e);
|
||||
console.log(failed ? `${failed} failed` : 'all the same');
|
||||
process.exit(failed ? 1 : 0);
|
||||
69
apps/web/check/steps.mjs
Normal file
69
apps/web/check/steps.mjs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// Runs a list of steps in the web version in headless Firefox and keeps screenshots —
|
||||
// for finding the places of buttons, and for the scenario checks built on it.
|
||||
//
|
||||
// node apps/web/check/steps.mjs <app-dir> <out-dir> <steps.json>
|
||||
//
|
||||
// A step: {"url": "?lang=en"} | {"wait": ms} | {"click": [x, y], "double": true}
|
||||
// | {"key": "l", "mods": ["ctrl"]} | {"shot": "name.png"} | {"eval": "js expression"}
|
||||
// | {"until": "js expression", "ms": 60000}
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { launch } from './firefox.mjs';
|
||||
import { sleep, tab } from './bidi.mjs';
|
||||
|
||||
export const KEYS = { ctrl: '', shift: '', alt: '', esc: '', right: '', left: '', enter: '' };
|
||||
|
||||
export async function session(appDir, port = 18767) {
|
||||
const root = fileURLToPath(new URL('../../..', import.meta.url));
|
||||
const server = spawn('python3', ['-I', join(root, 'apps/web/check/serve.py'), resolve(appDir), join(root, 'website/static'), String(port)], { stdio: 'ignore' });
|
||||
const ff = await launch(19224);
|
||||
const errors = [];
|
||||
const t = await tab(ff.browser, 1400, 860, (line) => {
|
||||
if (/panicked|RuntimeError|\[error\]/.test(line)) errors.push(line);
|
||||
if (process.env.CONSOLE) console.log(line);
|
||||
});
|
||||
const base = `http://127.0.0.1:${port}/app/`;
|
||||
const run = async (step, outDir) => {
|
||||
if (step.url !== undefined) {
|
||||
await t.navigate(base + step.url);
|
||||
await t.waitFor(`document.getElementById('cp-status').hidden || !document.getElementById('cp-device').hidden`, 30000);
|
||||
}
|
||||
if (step.wait) await sleep(step.wait);
|
||||
if (step.click) {
|
||||
const [x, y] = step.click;
|
||||
const acts = [{ type: 'pointerMove', x, y }];
|
||||
for (let i = 0; i < (step.double ? 2 : 1); i++) acts.push({ type: 'pointerDown', button: step.right ? 2 : 0 }, { type: 'pointerUp', button: step.right ? 2 : 0 });
|
||||
await t.actions([{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]);
|
||||
await sleep(300);
|
||||
}
|
||||
if (step.key) {
|
||||
const mods = (step.mods || []).map((m) => KEYS[m]);
|
||||
const v = KEYS[step.key] || step.key;
|
||||
const acts = [...mods.map((m) => ({ type: 'keyDown', value: m })), { type: 'keyDown', value: v }, { type: 'keyUp', value: v }, ...mods.reverse().map((m) => ({ type: 'keyUp', value: m }))];
|
||||
for (let i = 0; i < (step.times || 1); i++) await t.actions([{ type: 'key', id: 'kb', actions: acts }]);
|
||||
await sleep(300);
|
||||
}
|
||||
if (step.eval) console.log('eval:', JSON.stringify(await t.evaluate(step.eval)).slice(0, 2000));
|
||||
if (step.until) await t.waitFor(step.until, step.ms || 60000);
|
||||
if (step.shot) writeFileSync(join(outDir, step.shot), await t.screenshot());
|
||||
};
|
||||
return {
|
||||
t, ff, errors, run,
|
||||
stop: async () => { await ff.stop(); server.kill(); },
|
||||
};
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const [appDir, outDir, stepsFile] = process.argv.slice(2);
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
const steps = JSON.parse(readFileSync(stepsFile, 'utf8'));
|
||||
const s = await session(appDir);
|
||||
try {
|
||||
for (const step of steps) await s.run(step, outDir);
|
||||
} finally {
|
||||
await s.stop();
|
||||
}
|
||||
for (const e of s.errors) console.log('console:', e);
|
||||
}
|
||||
|
|
@ -97,21 +97,38 @@ fn check_writable(db: &PgnDatabase) -> Result<&Path, WriteError> {
|
|||
/// before the new record stay as they were.
|
||||
pub fn append(db: &PgnDatabase, record: &str) -> Result<Appended, WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
let bytes = db.bytes();
|
||||
let eol = line_ending(bytes);
|
||||
let sep = separator(bytes, eol);
|
||||
let mut data = sep.as_bytes().to_vec();
|
||||
data.extend(record_bytes(record, eol));
|
||||
let (data, sep) = tail_for(db.bytes(), record);
|
||||
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
|
||||
let offset = file.metadata()?.len() + sep.len() as u64;
|
||||
let offset = file.metadata()?.len() + sep as u64;
|
||||
file.write_all(&data)?;
|
||||
file.sync_all()?;
|
||||
Ok(Appended { offset })
|
||||
}
|
||||
|
||||
/// Replaces record `index` with `record`; every other byte of the file stays.
|
||||
pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
/// What goes at the end of `bytes` to add `record` after a blank line, and how many of
|
||||
/// its bytes come before the record.
|
||||
fn tail_for(bytes: &[u8], record: &str) -> (Vec<u8>, usize) {
|
||||
let eol = line_ending(bytes);
|
||||
let sep = separator(bytes, eol);
|
||||
let mut data = sep.as_bytes().to_vec();
|
||||
data.extend(record_bytes(record, eol));
|
||||
(data, sep.len())
|
||||
}
|
||||
|
||||
/// The text of `db` with `record` added at the end, and where the record starts: the
|
||||
/// same bytes [`append`] writes, for a database kept elsewhere than in a file (the web
|
||||
/// version's games in the browser).
|
||||
pub fn appended(db: &PgnDatabase, record: &str) -> (Vec<u8>, u64) {
|
||||
let bytes = db.bytes();
|
||||
let (tail, sep) = tail_for(bytes, record);
|
||||
let mut out = Vec::with_capacity(bytes.len() + tail.len());
|
||||
out.extend_from_slice(bytes);
|
||||
out.extend(tail);
|
||||
(out, (bytes.len() + sep) as u64)
|
||||
}
|
||||
|
||||
/// The text of `db` with record `index` replaced by `record` (what [`replace`] writes).
|
||||
pub fn replaced(db: &PgnDatabase, index: usize, record: &str) -> Result<Vec<u8>, WriteError> {
|
||||
let bytes = db.bytes();
|
||||
let range = db
|
||||
.entries()
|
||||
|
|
@ -124,14 +141,11 @@ pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), Write
|
|||
out.extend_from_slice(&bytes[..range.start]);
|
||||
out.extend(record_bytes(record, eol));
|
||||
out.extend_from_slice(&bytes[range.end..]);
|
||||
write_atomic(path, &out)?;
|
||||
Ok(())
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Removes record `index`; the bytes before and after it stay. What was removed comes
|
||||
/// back with [`restore`].
|
||||
pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
/// The text of `db` without record `index` (what [`remove`] writes) and the record.
|
||||
pub fn removed(db: &PgnDatabase, index: usize) -> Result<(Vec<u8>, Removed), WriteError> {
|
||||
let bytes = db.bytes();
|
||||
let range = db
|
||||
.entries()
|
||||
|
|
@ -142,11 +156,29 @@ pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
|||
let mut out = Vec::with_capacity(bytes.len());
|
||||
out.extend_from_slice(&bytes[..range.start]);
|
||||
out.extend_from_slice(&bytes[range.end..]);
|
||||
write_atomic(path, &out)?;
|
||||
Ok(Removed {
|
||||
Ok((
|
||||
out,
|
||||
Removed {
|
||||
index,
|
||||
bytes: bytes[range].to_vec(),
|
||||
})
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Replaces record `index` with `record`; every other byte of the file stays.
|
||||
pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
write_atomic(path, &replaced(db, index, record)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes record `index`; the bytes before and after it stay. What was removed comes
|
||||
/// back with [`restore`].
|
||||
pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
let (out, gone) = removed(db, index)?;
|
||||
write_atomic(path, &out)?;
|
||||
Ok(gone)
|
||||
}
|
||||
|
||||
/// Puts a removed record back at its place: the file is byte for byte what it was
|
||||
|
|
@ -154,6 +186,12 @@ pub fn remove(db: &PgnDatabase, index: usize) -> Result<Removed, WriteError> {
|
|||
/// database as read after the removal.
|
||||
pub fn restore(db: &PgnDatabase, removed: &Removed) -> Result<(), WriteError> {
|
||||
let path = check_writable(db)?;
|
||||
write_atomic(path, &restored(db, removed)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The text of `db` with a removed record back at its place (what [`restore`] writes).
|
||||
pub fn restored(db: &PgnDatabase, removed: &Removed) -> Result<Vec<u8>, WriteError> {
|
||||
let bytes = db.bytes();
|
||||
let at = match db.entries().get(removed.index) {
|
||||
Some(e) => e.byte_range.start,
|
||||
|
|
@ -164,8 +202,7 @@ pub fn restore(db: &PgnDatabase, removed: &Removed) -> Result<(), WriteError> {
|
|||
out.extend_from_slice(&bytes[..at]);
|
||||
out.extend_from_slice(&removed.bytes);
|
||||
out.extend_from_slice(&bytes[at..]);
|
||||
write_atomic(path, &out)?;
|
||||
Ok(())
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes every record of `db` into `dest` as UTF-8 (LF, one blank line between
|
||||
|
|
|
|||
|
|
@ -15,3 +15,4 @@ uci.workspace = true
|
|||
chess-openings.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
web-time.workspace = true
|
||||
|
|
|
|||
|
|
@ -14,12 +14,19 @@ use uci::{EnginePosition, Side};
|
|||
|
||||
use crate::PosEval;
|
||||
|
||||
// What the job does for one target, whatever drives it.
|
||||
mod work;
|
||||
// The job in engine processes, each on a thread of its own: a computer's and a
|
||||
// phone's.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
mod engines;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub use engines::run;
|
||||
// The job in Web Workers: a browser's.
|
||||
#[cfg(target_family = "wasm")]
|
||||
mod workers;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use workers::Dispatcher;
|
||||
|
||||
/// Nodes of every search of a game analysis (0.85 s on one thread of an i7-13700KF,
|
||||
/// depth about 24).
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|||
use std::sync::mpsc::channel;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side};
|
||||
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits};
|
||||
|
||||
use super::work::{Answer, Next, Work};
|
||||
use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target};
|
||||
use crate::{Eval, PosEval, Second, Shallow};
|
||||
|
||||
/// A node-limited search should never take this long; stop it if it does.
|
||||
const SEARCH_GUARD: Duration = Duration::from_secs(300);
|
||||
|
|
@ -107,133 +107,33 @@ fn worker(
|
|||
let _ = handle.new_game();
|
||||
search_once(&handle, pos, SearchId(next_id), among, nodes, halted)
|
||||
};
|
||||
while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
'targets: while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
if halted() {
|
||||
break;
|
||||
}
|
||||
let (mut eval, nps) = match &t.known {
|
||||
Some(e) => (e.clone(), 0),
|
||||
None => {
|
||||
let Some((info, best)) = search(&t.pos, Vec::new(), settings.nodes)? else {
|
||||
continue;
|
||||
};
|
||||
let Some(score) = info.score else { continue };
|
||||
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
|
||||
if let Some(b) = best
|
||||
&& pv.first() != Some(&b)
|
||||
{
|
||||
pv = vec![b];
|
||||
let mut work = Work::new(t.clone(), settings.nodes);
|
||||
loop {
|
||||
match work.next() {
|
||||
Next::Search { pos, among, nodes } => {
|
||||
let answer = search(&pos, among, nodes)?;
|
||||
if answer.is_none() && halted() {
|
||||
break 'targets;
|
||||
}
|
||||
let eval = PosEval {
|
||||
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
|
||||
pv,
|
||||
depth: info.depth.unwrap_or(0),
|
||||
second: None,
|
||||
shallow: None,
|
||||
};
|
||||
(eval, info.nps.unwrap_or(0))
|
||||
work.answer(answer);
|
||||
}
|
||||
};
|
||||
// The move played is the engine's best: what the best of the others gives says
|
||||
// whether it was the only good move, or a sacrifice when nothing else won.
|
||||
let mover = match t.turn {
|
||||
Side::White => chess_core::shakmaty::Color::White,
|
||||
Side::Black => chess_core::shakmaty::Color::Black,
|
||||
};
|
||||
let played = t.played.as_ref().filter(|p| {
|
||||
eval.pv.first() == Some(*p)
|
||||
&& !t.others.is_empty()
|
||||
&& crate::report::worth_second(eval.eval, mover)
|
||||
});
|
||||
if let Some(played) = played
|
||||
&& eval.second.as_ref().map(|s| &s.without) != Some(played)
|
||||
{
|
||||
match search(&t.pos, t.others.clone(), settings.nodes)? {
|
||||
// An engine that ignores `searchmoves` answers with the move played:
|
||||
// no second move then.
|
||||
Some((info, best))
|
||||
if best.as_ref() != Some(played) && info.pv.first() != Some(played) =>
|
||||
{
|
||||
if let Some(score) = info.score {
|
||||
eval.second = Some(Second {
|
||||
without: played.clone(),
|
||||
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
|
||||
});
|
||||
Next::Done(event) => {
|
||||
if let Some(e) = event {
|
||||
on_event(e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
None if halted() => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// How hard it was to find: what a shallow search makes of it.
|
||||
if let (Some(played), Some(nodes)) = (played, t.shallow)
|
||||
&& !eval
|
||||
.shallow
|
||||
.as_ref()
|
||||
.is_some_and(|s| &s.played == played && s.nodes == nodes)
|
||||
{
|
||||
match shallow(&mut search, t, played, nodes)? {
|
||||
Some(s) => eval.shallow = Some(s),
|
||||
None if halted() => break,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
on_event(JobEvent::Eval {
|
||||
key: t.key.clone(),
|
||||
eval,
|
||||
nps,
|
||||
});
|
||||
}
|
||||
handle.quit();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What a search gave: its last full line and the best move, `None` when there is none
|
||||
/// (see [`search_once`]).
|
||||
type SearchResult = Result<Option<(uci::SearchInfo, Option<String>)>, JobFailure>;
|
||||
|
||||
/// The shallow search of `played` at `t`: the best move at `nodes` and, when it is
|
||||
/// another, the move played alone. `None` when the engine gave no answer (or ignored
|
||||
/// `searchmoves`) or the job was halted.
|
||||
fn shallow(
|
||||
search: &mut dyn FnMut(&EnginePosition, Vec<String>, u64) -> SearchResult,
|
||||
t: &Target,
|
||||
played: &str,
|
||||
nodes: u64,
|
||||
) -> Result<Option<Shallow>, JobFailure> {
|
||||
let eval_of = |info: &uci::SearchInfo| {
|
||||
info.score
|
||||
.map(|s| Eval::from_white_eval(s.to_white(t.turn).eval))
|
||||
};
|
||||
let Some((info, best)) = search(&t.pos, Vec::new(), nodes)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (Some(best), Some(best_eval)) = (best.or_else(|| info.pv.first().cloned()), eval_of(&info))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let played_eval = if best == played {
|
||||
best_eval
|
||||
} else {
|
||||
match search(&t.pos, vec![played.to_owned()], nodes)? {
|
||||
Some((info, b)) if b.as_deref().is_none_or(|b| b == played) => {
|
||||
let Some(e) = eval_of(&info) else {
|
||||
return Ok(None);
|
||||
};
|
||||
e
|
||||
}
|
||||
_ => return Ok(None),
|
||||
}
|
||||
};
|
||||
Ok(Some(Shallow {
|
||||
nodes,
|
||||
played: played.to_owned(),
|
||||
best,
|
||||
best_eval,
|
||||
played_eval,
|
||||
}))
|
||||
}
|
||||
|
||||
/// One node-limited search: its last full line and the best move. `None` when it gave
|
||||
/// no line or the job was halted.
|
||||
fn search_once(
|
||||
|
|
@ -243,7 +143,7 @@ fn search_once(
|
|||
among: Vec<String>,
|
||||
nodes: u64,
|
||||
halted: &dyn Fn() -> bool,
|
||||
) -> SearchResult {
|
||||
) -> Result<Answer, JobFailure> {
|
||||
handle
|
||||
.search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among)
|
||||
.map_err(|e| JobFailure::Engine(e.to_string()))?;
|
||||
|
|
|
|||
223
crates/game-review/src/job/work.rs
Normal file
223
crates/game-review/src/job/work.rs
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
//! What the job does for one target, as a machine without I/O: it names the next
|
||||
//! search (the full one, the second best without the move played, the shallow ones)
|
||||
//! and takes its answer; at the end it gives the target's [`JobEvent::Eval`]. Engine
|
||||
//! processes on a computer and Web Workers in a browser drive the same machine, so the
|
||||
//! evaluations — and the marks — are the same everywhere.
|
||||
|
||||
use uci::{EnginePosition, SearchInfo, Side};
|
||||
|
||||
use super::{JobEvent, Target};
|
||||
use crate::{Eval, PosEval, Second, Shallow};
|
||||
|
||||
/// A search's answer: its last full line and the best move; `None` when it gave none.
|
||||
pub(crate) type Answer = Option<(SearchInfo, Option<String>)>;
|
||||
|
||||
/// What the machine wants now.
|
||||
pub(crate) enum Next {
|
||||
/// A node-limited search of `pos` (among these moves only; empty: all), from a
|
||||
/// clear hash.
|
||||
Search {
|
||||
pos: EnginePosition,
|
||||
among: Vec<String>,
|
||||
nodes: u64,
|
||||
},
|
||||
/// The target is done: its evaluation (`None`: the engine gave nothing to use).
|
||||
Done(Option<JobEvent>),
|
||||
}
|
||||
|
||||
enum Stage {
|
||||
Full,
|
||||
Second,
|
||||
ShallowBest,
|
||||
ShallowPlayed { best: String, best_eval: Eval },
|
||||
Finish,
|
||||
}
|
||||
|
||||
pub(crate) struct Work {
|
||||
t: Target,
|
||||
nodes: u64,
|
||||
stage: Stage,
|
||||
eval: Option<PosEval>,
|
||||
nps: u64,
|
||||
/// The move played, when it is the engine's best and worth a second search.
|
||||
played: Option<String>,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
pub(crate) fn new(t: Target, nodes: u64) -> Self {
|
||||
let mut w = Work {
|
||||
t,
|
||||
nodes,
|
||||
stage: Stage::Full,
|
||||
eval: None,
|
||||
nps: 0,
|
||||
played: None,
|
||||
};
|
||||
if let Some(e) = w.t.known.clone() {
|
||||
w.got_eval(e, 0);
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
fn eval_of(&self, info: &SearchInfo) -> Option<Eval> {
|
||||
info.score
|
||||
.map(|s| Eval::from_white_eval(s.to_white(self.t.turn).eval))
|
||||
}
|
||||
|
||||
/// The full evaluation is there: the second search, if it is worth one.
|
||||
fn got_eval(&mut self, eval: PosEval, nps: u64) {
|
||||
let t = &self.t;
|
||||
// The move played is the engine's best: what the best of the others gives says
|
||||
// whether it was the only good move, or a sacrifice when nothing else won.
|
||||
let mover = match t.turn {
|
||||
Side::White => chess_core::shakmaty::Color::White,
|
||||
Side::Black => chess_core::shakmaty::Color::Black,
|
||||
};
|
||||
self.played = t
|
||||
.played
|
||||
.as_ref()
|
||||
.filter(|p| {
|
||||
eval.pv.first() == Some(*p)
|
||||
&& !t.others.is_empty()
|
||||
&& crate::report::worth_second(eval.eval, mover)
|
||||
})
|
||||
.cloned();
|
||||
let second_known = eval.second.as_ref().map(|s| &s.without) == self.played.as_ref();
|
||||
self.eval = Some(eval);
|
||||
self.nps = nps;
|
||||
self.stage = if self.played.is_some() && !second_known {
|
||||
Stage::Second
|
||||
} else {
|
||||
Stage::ShallowBest
|
||||
};
|
||||
if matches!(self.stage, Stage::ShallowBest) {
|
||||
self.after_second();
|
||||
}
|
||||
}
|
||||
|
||||
/// The shallow search, when the rules want one and it is not there yet.
|
||||
fn after_second(&mut self) {
|
||||
let wanted = match (&self.played, self.t.shallow, &self.eval) {
|
||||
(Some(played), Some(nodes), Some(eval)) => !eval
|
||||
.shallow
|
||||
.as_ref()
|
||||
.is_some_and(|s| &s.played == played && s.nodes == nodes),
|
||||
_ => false,
|
||||
};
|
||||
self.stage = if wanted {
|
||||
Stage::ShallowBest
|
||||
} else {
|
||||
Stage::Finish
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn next(&self) -> Next {
|
||||
let t = &self.t;
|
||||
match &self.stage {
|
||||
Stage::Full => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: Vec::new(),
|
||||
nodes: self.nodes,
|
||||
},
|
||||
Stage::Second => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: t.others.clone(),
|
||||
nodes: self.nodes,
|
||||
},
|
||||
Stage::ShallowBest => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: Vec::new(),
|
||||
nodes: t.shallow.unwrap_or_default(),
|
||||
},
|
||||
Stage::ShallowPlayed { .. } => Next::Search {
|
||||
pos: t.pos.clone(),
|
||||
among: self.played.iter().cloned().collect(),
|
||||
nodes: t.shallow.unwrap_or_default(),
|
||||
},
|
||||
Stage::Finish => Next::Done(self.eval.clone().map(|eval| JobEvent::Eval {
|
||||
key: t.key.clone(),
|
||||
eval,
|
||||
nps: self.nps,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer to the search [`Self::next`] asked for.
|
||||
pub(crate) fn answer(&mut self, answer: Answer) {
|
||||
match std::mem::replace(&mut self.stage, Stage::Finish) {
|
||||
Stage::Full => {
|
||||
let Some((info, best)) = answer else { return };
|
||||
let Some(score) = info.score else { return };
|
||||
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
|
||||
if let Some(b) = best
|
||||
&& pv.first() != Some(&b)
|
||||
{
|
||||
pv = vec![b];
|
||||
}
|
||||
let eval = PosEval {
|
||||
eval: Eval::from_white_eval(score.to_white(self.t.turn).eval),
|
||||
pv,
|
||||
depth: info.depth.unwrap_or(0),
|
||||
second: None,
|
||||
shallow: None,
|
||||
};
|
||||
self.got_eval(eval, info.nps.unwrap_or(0));
|
||||
}
|
||||
Stage::Second => {
|
||||
let played = self.played.clone();
|
||||
// An engine that ignores `searchmoves` answers with the move played: no
|
||||
// second move then.
|
||||
if let Some((info, best)) = answer
|
||||
&& best.as_ref() != played.as_ref()
|
||||
&& info.pv.first() != played.as_ref()
|
||||
&& let (Some(score), Some(played), Some(eval)) =
|
||||
(info.score, played, self.eval.as_mut())
|
||||
{
|
||||
eval.second = Some(Second {
|
||||
without: played,
|
||||
eval: Eval::from_white_eval(score.to_white(self.t.turn).eval),
|
||||
});
|
||||
}
|
||||
self.after_second();
|
||||
}
|
||||
Stage::ShallowBest => {
|
||||
let Some((info, best)) = answer else { return };
|
||||
let (Some(best), Some(best_eval)) = (
|
||||
best.or_else(|| info.pv.first().cloned()),
|
||||
self.eval_of(&info),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
if self.played.as_ref() == Some(&best) {
|
||||
self.shallow(best, best_eval, best_eval);
|
||||
} else {
|
||||
self.stage = Stage::ShallowPlayed { best, best_eval };
|
||||
}
|
||||
}
|
||||
Stage::ShallowPlayed { best, best_eval } => {
|
||||
if let Some((info, b)) = answer
|
||||
&& b.as_deref()
|
||||
.is_none_or(|b| Some(b) == self.played.as_deref())
|
||||
&& let Some(played_eval) = self.eval_of(&info)
|
||||
{
|
||||
self.shallow(best, best_eval, played_eval);
|
||||
}
|
||||
}
|
||||
Stage::Finish => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn shallow(&mut self, best: String, best_eval: Eval, played_eval: Eval) {
|
||||
if let (Some(eval), Some(played), Some(nodes)) =
|
||||
(self.eval.as_mut(), self.played.clone(), self.t.shallow)
|
||||
{
|
||||
eval.shallow = Some(Shallow {
|
||||
nodes,
|
||||
played,
|
||||
best,
|
||||
best_eval,
|
||||
played_eval,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
220
crates/game-review/src/job/workers.rs
Normal file
220
crates/game-review/src/job/workers.rs
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
//! The engine job in a browser: engines in Web Workers, each taking the next target,
|
||||
//! driven from the page's frames by their messages — nothing here blocks. The search
|
||||
//! of every target is the same machine as on a computer ([`super::work`]).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use uci::{
|
||||
EngineEvent, EngineHandle, ScoreBound, SearchId, SearchInfo, SearchLimits, Starting,
|
||||
WorkerConfig,
|
||||
};
|
||||
use web_time::Instant;
|
||||
|
||||
use super::work::{Next, Work};
|
||||
use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target};
|
||||
|
||||
/// A node-limited search should never take this long; stop it if it does.
|
||||
const SEARCH_GUARD: Duration = Duration::from_secs(300);
|
||||
|
||||
/// How long an engine may take to start: a worker compiles the whole engine (≈ 100 MB
|
||||
/// of WebAssembly), several at once.
|
||||
const START_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
enum Engine {
|
||||
Starting(Starting),
|
||||
Ready(EngineHandle),
|
||||
Done,
|
||||
}
|
||||
|
||||
struct Running {
|
||||
id: SearchId,
|
||||
last: Option<SearchInfo>,
|
||||
started: Instant,
|
||||
stopping: bool,
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
engine: Engine,
|
||||
work: Option<Work>,
|
||||
search: Option<Running>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
/// The job: started by [`Dispatcher::start`], driven by [`Dispatcher::poll`].
|
||||
pub struct Dispatcher {
|
||||
slots: Vec<Slot>,
|
||||
targets: std::vec::IntoIter<Target>,
|
||||
nodes: u64,
|
||||
names: HashSet<String>,
|
||||
events: Vec<JobEvent>,
|
||||
failure: Option<JobFailure>,
|
||||
halted: bool,
|
||||
}
|
||||
|
||||
impl Dispatcher {
|
||||
/// Starts `settings.processes` engines of the worker script `script`; `wake` is
|
||||
/// called whenever one of them has something new.
|
||||
pub fn start(
|
||||
script: &str,
|
||||
settings: &JobSettings,
|
||||
targets: Vec<Target>,
|
||||
wake: Arc<dyn Fn() + Send + Sync>,
|
||||
) -> Result<Dispatcher, JobFailure> {
|
||||
let workers = settings
|
||||
.processes
|
||||
.clamp(1, MAX_PROCESSES)
|
||||
.min(targets.len().max(1));
|
||||
let mut slots = Vec::with_capacity(workers);
|
||||
if !targets.is_empty() {
|
||||
for _ in 0..workers {
|
||||
let mut config = WorkerConfig::new(script);
|
||||
config.timeouts.uciok = START_TIMEOUT;
|
||||
config.timeouts.readyok = START_TIMEOUT;
|
||||
let wake = wake.clone();
|
||||
let starting = uci::Engine::start_worker(config, Box::new(move || wake()))
|
||||
.map_err(|e| JobFailure::Start(e.to_string()))?;
|
||||
slots.push(Slot {
|
||||
engine: Engine::Starting(starting),
|
||||
work: None,
|
||||
search: None,
|
||||
next_id: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Dispatcher {
|
||||
slots,
|
||||
targets: targets.into_iter(),
|
||||
nodes: settings.nodes,
|
||||
names: HashSet::new(),
|
||||
events: Vec::new(),
|
||||
failure: None,
|
||||
halted: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stops the job: the engines are stopped, what came stays.
|
||||
pub fn cancel(&mut self) {
|
||||
self.halted = true;
|
||||
for s in &mut self.slots {
|
||||
s.engine = Engine::Done;
|
||||
}
|
||||
}
|
||||
|
||||
/// What came since the last call, and the end once the job is over (`Ok` also when
|
||||
/// cancelled). Call it every frame and when woken.
|
||||
pub fn poll(&mut self) -> (Vec<JobEvent>, Option<Result<(), JobFailure>>) {
|
||||
for i in 0..self.slots.len() {
|
||||
if let Err(e) = self.step(i) {
|
||||
self.failure.get_or_insert(e);
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
let events = std::mem::take(&mut self.events);
|
||||
let over = self.slots.iter().all(|s| matches!(s.engine, Engine::Done));
|
||||
let end = over.then(|| match self.failure.take() {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
});
|
||||
(events, end)
|
||||
}
|
||||
|
||||
fn step(&mut self, i: usize) -> Result<(), JobFailure> {
|
||||
let slot = &mut self.slots[i];
|
||||
if let Engine::Starting(s) = &mut slot.engine {
|
||||
match s.poll() {
|
||||
None => return Ok(()),
|
||||
Some(Err(e)) => return Err(JobFailure::Start(e.to_string())),
|
||||
Some(Ok(h)) => {
|
||||
// Unknown options are not fatal: some engines lack Threads/Hash/MultiPV.
|
||||
let _ = h.set_threads(1);
|
||||
let _ = h.set_hash_mb(SEARCH_HASH_MB);
|
||||
let _ = h.set_multipv(1);
|
||||
if let Some(name) = &h.info().name
|
||||
&& self.names.insert(name.clone())
|
||||
{
|
||||
self.events.push(JobEvent::Engine(name.clone()));
|
||||
}
|
||||
slot.engine = Engine::Ready(h);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Engine::Ready(h) = &slot.engine else {
|
||||
return Ok(());
|
||||
};
|
||||
// The answer of the running search, once it is there.
|
||||
let mut answer = None;
|
||||
for ev in h.drain_events() {
|
||||
let Some(run) = slot.search.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
match ev {
|
||||
EngineEvent::Info { search_id, info } if search_id == run.id => {
|
||||
if info.multipv_index() == 1 && info.score.is_some() {
|
||||
let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact);
|
||||
if exact || run.last.is_none() {
|
||||
run.last = Some(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
EngineEvent::BestMove {
|
||||
search_id, best, ..
|
||||
} if search_id == run.id => {
|
||||
let last = run.last.take();
|
||||
answer = Some(last.map(|info| (info, best)));
|
||||
slot.search = None;
|
||||
}
|
||||
EngineEvent::Terminated(reason) => return Err(JobFailure::Terminated(reason)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(run) = slot.search.as_mut() {
|
||||
if !run.stopping && run.started.elapsed() > SEARCH_GUARD {
|
||||
let _ = h.stop();
|
||||
run.stopping = true;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let (Some(answer), Some(work)) = (answer, slot.work.as_mut()) {
|
||||
work.answer(answer);
|
||||
}
|
||||
// The next search: of this target, or of the next one.
|
||||
loop {
|
||||
if slot.work.is_none() {
|
||||
match self.targets.next().filter(|_| !self.halted) {
|
||||
Some(t) => slot.work = Some(Work::new(t, self.nodes)),
|
||||
None => {
|
||||
slot.engine = Engine::Done;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(work) = slot.work.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
match work.next() {
|
||||
Next::Search { pos, among, nodes } => {
|
||||
slot.next_id += 1;
|
||||
let id = SearchId(slot.next_id);
|
||||
// Every search starts from a clear hash, so that it depends on its
|
||||
// position alone.
|
||||
let _ = h.new_game();
|
||||
h.search_among(pos, id, SearchLimits::Nodes(nodes), among)
|
||||
.map_err(|e| JobFailure::Engine(e.to_string()))?;
|
||||
slot.search = Some(Running {
|
||||
id,
|
||||
last: None,
|
||||
started: Instant::now(),
|
||||
stopping: false,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
Next::Done(event) => {
|
||||
self.events.extend(event);
|
||||
slot.work = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@
|
|||
//! are used without an engine.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
use chess_core::shakmaty::san::SanPlus;
|
||||
use chess_core::shakmaty::uci::UciMove;
|
||||
|
|
@ -22,6 +22,8 @@ mod job;
|
|||
pub mod report;
|
||||
|
||||
pub use features::{MoveFeatures, Rules};
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use job::Dispatcher;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub use job::run;
|
||||
pub use job::{
|
||||
|
|
@ -157,11 +159,37 @@ pub struct GameAnalysis {
|
|||
shallow_nodes: u64,
|
||||
}
|
||||
|
||||
/// Where cached analyses are kept, one file per main line by name: a folder (`Path`),
|
||||
/// or whatever else a program keeps files in (the web version's browser storage).
|
||||
pub trait CacheStore {
|
||||
fn read(&self, name: &str) -> Option<Vec<u8>>;
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()>;
|
||||
}
|
||||
|
||||
/// The cache in a folder of the disk.
|
||||
pub struct CacheDir<'a>(pub &'a Path);
|
||||
|
||||
impl CacheStore for CacheDir<'_> {
|
||||
fn read(&self, name: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(self.0.join(name)).ok()
|
||||
}
|
||||
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> {
|
||||
write_atomic(&self.0.join(name), bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl GameAnalysis {
|
||||
/// The analysis of `game`: from the cache in `cache_dir` (the folder of the cached
|
||||
/// analyses) when this main line was analysed before, else from `[%eval]` comments
|
||||
/// when every move has one, else empty.
|
||||
pub fn new(game: &Game, cache_dir: Option<&Path>) -> Self {
|
||||
let dir = cache_dir.map(CacheDir);
|
||||
Self::with_store(game, dir.as_ref().map(|d| d as &dyn CacheStore))
|
||||
}
|
||||
|
||||
/// [`Self::new`] with the cache in `store`.
|
||||
pub fn with_store(game: &Game, store: Option<&dyn CacheStore>) -> Self {
|
||||
let mut a = GameAnalysis {
|
||||
evals: HashMap::new(),
|
||||
meta: None,
|
||||
|
|
@ -181,7 +209,7 @@ impl GameAnalysis {
|
|||
shallow_nodes: SHALLOW_NODES,
|
||||
};
|
||||
a.rebuild(game);
|
||||
if cache_dir.is_some_and(|d| a.load_cache(d)) || a.load_pgn_evals(game) {
|
||||
if store.is_some_and(|s| a.load_cache(s)) || a.load_pgn_evals(game) {
|
||||
a.rebuild(game);
|
||||
}
|
||||
a
|
||||
|
|
@ -556,8 +584,8 @@ impl GameAnalysis {
|
|||
|
||||
// ----- cache -----------------------------------------------------------------
|
||||
|
||||
/// The cache file of this main line in `dir`.
|
||||
fn cache_path(&self, dir: &Path) -> PathBuf {
|
||||
/// The name of the cache file of this main line.
|
||||
fn cache_name(&self) -> String {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for k in &self.keys {
|
||||
for b in k.bytes().chain(std::iter::once(b'\n')) {
|
||||
|
|
@ -565,11 +593,16 @@ impl GameAnalysis {
|
|||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
dir.join(format!("{h:016x}.json"))
|
||||
format!("{h:016x}.json")
|
||||
}
|
||||
|
||||
/// Keeps engine results in `dir` (nothing for evaluations read from the PGN).
|
||||
pub fn save_cache(&self, dir: &Path) -> std::io::Result<()> {
|
||||
self.save_to(&CacheDir(dir))
|
||||
}
|
||||
|
||||
/// Keeps engine results in `store` (nothing for evaluations read from the PGN).
|
||||
pub fn save_to(&self, store: &dyn CacheStore) -> std::io::Result<()> {
|
||||
let Some(meta) = self.meta.clone().filter(|m| m.nodes > 0) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
|
@ -588,11 +621,11 @@ impl GameAnalysis {
|
|||
.collect(),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?;
|
||||
write_atomic(&self.cache_path(dir), &bytes)
|
||||
store.write(&self.cache_name(), &bytes)
|
||||
}
|
||||
|
||||
fn load_cache(&mut self, dir: &Path) -> bool {
|
||||
let Ok(bytes) = std::fs::read(self.cache_path(dir)) else {
|
||||
fn load_cache(&mut self, store: &dyn CacheStore) -> bool {
|
||||
let Some(bytes) = store.read(&self.cache_name()) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(file) = serde_json::from_slice::<CacheFile>(&bytes) else {
|
||||
|
|
@ -837,7 +870,7 @@ mod tests {
|
|||
let targets = a.begin(&g, false);
|
||||
fake_results(&mut a, targets);
|
||||
a.refresh(&g);
|
||||
let path = a.cache_path(&dir);
|
||||
let path = dir.join(a.cache_name());
|
||||
a.save_cache(&dir).expect("saved");
|
||||
// The file as 1.x wrote it: no `search` in the meta, 3M nodes.
|
||||
let mut json: serde_json::Value =
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue