diff --git a/.cargo/config.toml b/.cargo/config.toml index 52be801..d92eacf 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -2,3 +2,8 @@ # without the Visual C++ Redistributable (VCRUNTIME140.dll). [target.x86_64-pc-windows-msvc] rustflags = ["-C", "target-feature=+crt-static"] + +# WebAssembly in a browser: random numbers from crypto.getRandomValues (getrandom 0.3 +# needs this as well as its `wasm_js` feature, enabled by apps/web). +[target.wasm32-unknown-unknown] +rustflags = ["--cfg", "getrandom_backend=\"wasm_js\""] diff --git a/.gitignore b/.gitignore index d878c7d..07b902c 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,6 @@ # A local run of the website from the repository root (website/README.md runs it from server/). /data-dev/ + +# The web version built for the site (apps/web/build.sh website/static/app) +website/static/app/ diff --git a/Cargo.lock b/Cargo.lock index 6fdca1b..0075acd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -716,6 +716,12 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "cc" version = "1.8.0" @@ -772,6 +778,7 @@ version = "2.1.1" dependencies = [ "encoding_rs", "pgn-reader", + "serde", "shakmaty", "thiserror 2.0.21", ] @@ -816,6 +823,7 @@ dependencies = [ "game-review", "getrandom 0.3.4", "image", + "js-sys", "log", "maia", "online-games", @@ -834,11 +842,27 @@ dependencies = [ "trainer", "uci", "ureq", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", "whatlang", "winresource", "zip", ] +[[package]] +name = "chesspenguin-web" +version = "2.1.1" +dependencies = [ + "chesspenguin", + "eframe", + "log", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "chrono" version = "0.4.45" @@ -846,7 +870,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", + "wasm-bindgen", "windows-link", ] @@ -1686,6 +1712,7 @@ dependencies = [ "serde_json", "shakmaty", "uci", + "web-time", ] [[package]] @@ -1716,9 +1743,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -2445,6 +2474,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "minicov" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d" +dependencies = [ + "cc", + "walkdir", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2619,6 +2658,15 @@ dependencies = [ "winapi", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -3080,6 +3128,12 @@ dependencies = [ "ureq", ] +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + [[package]] name = "option-ext" version = "0.2.0" @@ -4390,7 +4444,10 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" dependencies = [ + "js-sys", "libc", + "wasm-bindgen", + "web-sys", ] [[package]] @@ -4640,6 +4697,7 @@ dependencies = [ "chrono", "serde", "serde_json", + "web-time", ] [[package]] @@ -4678,8 +4736,14 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" name = "uci" version = "2.1.1" dependencies = [ + "js-sys", "libc", "thiserror 2.0.21", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test", + "web-sys", + "web-time", ] [[package]] @@ -5050,6 +5114,45 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-bindgen-test" +version = "0.3.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42" +dependencies = [ + "async-trait", + "cast", + "js-sys", + "libm", + "minicov", + "nu-ansi-term", + "num-traits", + "oorandom", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test-macro", + "wasm-bindgen-test-shared", +] + +[[package]] +name = "wasm-bindgen-test-macro" +version = "0.3.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "wasm-bindgen-test-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe" + [[package]] name = "wayland-backend" version = "0.3.17" diff --git a/Cargo.toml b/Cargo.toml index fdba624..a18757a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ members = [ "crates/play", "crates/prep", "apps/desktop", + "apps/web", ] [workspace.package] @@ -30,6 +31,8 @@ shakmaty = "0.30.2" pgn-reader = "0.29.1" encoding_rs = "0.8" thiserror = "2" +# `Instant`/`SystemTime` that also work in a browser (std's panic there). +web-time = "1.1" serde = { version = "1", features = ["derive"] } serde_json = "1" egui = "=0.36.2" @@ -54,3 +57,11 @@ prep = { path = "crates/prep" } [profile.dev.package."*"] opt-level = 2 + +# The web version (apps/web/build.sh): small to download, the release otherwise. +[profile.web] +inherits = "release" +opt-level = "s" +lto = "fat" +codegen-units = 1 +panic = "abort" diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 6bc3033..c0403f8 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -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 diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index e3f2cd0..ae025c9 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -9,6 +9,16 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +# The interface, shared with the web version (apps/web); src/main.rs starts it in a +# window. +[lib] +name = "chesspenguin_app" +path = "src/lib.rs" + +[[bin]] +name = "chesspenguin" +path = "src/main.rs" + [dependencies] chess-core.workspace = true maia.workspace = true @@ -21,23 +31,15 @@ egui.workspace = true eframe.workspace = true egui_extras.workspace = true image.workspace = true -rfd.workspace = true -arboard.workspace = true -rodio.workspace = true directories.workspace = true trainer.workspace = true play.workspace = true serde.workspace = true serde_json.workspace = true online-games.workspace = true -releases.workspace = true -# Downloading the official Stockfish on request (decision 14). -ureq = "3.4" -flate2 = "1.1" -tar = "0.4" +web-time.workspace = true sha2 = "0.11" zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs"] } - # The system language for the first start. sys-locale = "0.3" whatlang = "0.18.0" @@ -49,6 +51,42 @@ log = "0.4" base64 = "0.22" form_urlencoded = "1" +# The desktop program: native dialogs, the clipboard, sound, the network (updates, +# engines and Maia on request, online games, translation). +[target.'cfg(not(target_family = "wasm"))'.dependencies] +rfd.workspace = true +arboard.workspace = true +rodio.workspace = true +releases.workspace = true +# Downloading the official Stockfish on request (decision 14). +ureq = "3.4" +flate2 = "1.1" +tar = "0.4" + +# The web version: the page, its files and storage (apps/web starts it). +[target.'cfg(target_family = "wasm")'.dependencies] +# The reader worker gives the page a database's index (platform::web::import). +chess-core = { workspace = true, features = ["serde"] } +getrandom = { version = "0.3", features = ["wasm_js"] } +# The browser's languages for the first start. +sys-locale = { version = "0.3", features = ["js"] } +# Today's date from the browser's clock. +chrono = { version = "0.4", default-features = false, features = ["clock", "std", "wasmbind"] } +wasm-bindgen = "0.2.129" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" +web-sys = { version = "0.3", features = [ + "Window", "Document", "Element", "HtmlElement", "HtmlInputElement", "HtmlAnchorElement", + "File", "FileList", "Blob", "BlobPropertyBag", "Url", "Event", "Location", "Navigator", + "Storage", "UrlSearchParams", "EventTarget", "CssStyleDeclaration", "Clipboard", + "IdbFactory", "IdbDatabase", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", + "IdbTransactionMode", "IdbObjectStore", "DomStringList", "HtmlAudioElement", + "HtmlMediaElement", "HtmlCanvasElement", "console", "CacheStorage", "Cache", + "Request", "Response", "ResponseInit", "Headers", "ReadableStream", + "ReadableStreamDefaultReader", "StorageManager", "StorageEstimate", "History", + "BeforeUnloadEvent", "WorkerOptions", "WorkerType", +] } + [build-dependencies] winresource = "0.1" diff --git a/apps/desktop/build.rs b/apps/desktop/build.rs index 5219d5b..3c834bf 100644 --- a/apps/desktop/build.rs +++ b/apps/desktop/build.rs @@ -1,5 +1,12 @@ -// Embeds the application icon into the Windows executable. fn main() { + // `cfg(web)`: WebAssembly in a browser (the web version, apps/web). + println!("cargo::rustc-check-cfg=cfg(web)"); + if std::env::var("CARGO_CFG_TARGET_FAMILY").as_deref() == Ok("wasm") + && std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("unknown") + { + println!("cargo::rustc-cfg=web"); + } + // Embeds the application icon into the Windows executable. if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { let mut res = winresource::WindowsResource::new(); res.set_icon("../../packaging/windows/chesspenguin.ico"); diff --git a/apps/desktop/src/analysis.rs b/apps/desktop/src/analysis.rs index d0be947..339ed8f 100644 --- a/apps/desktop/src/analysis.rs +++ b/apps/desktop/src/analysis.rs @@ -1,7 +1,7 @@ -//! Engine analysis controller: owns the UCI process, binds results to the analysed position. +//! Engine analysis controller: owns the engine (a UCI process; in a browser a Web +//! Worker), binds results to the analysed position. use crate::i18n::{tr, trf}; -use std::sync::mpsc::{Receiver, channel}; use shakmaty::san::SanPlus; use shakmaty::uci::UciMove; @@ -38,9 +38,39 @@ struct Target { engine_pos: EnginePosition, } +/// An engine on its way: its process started on a thread of its own (the handshake +/// blocks for up to ~20 s); in a browser its worker, the handshake by its messages. +enum Launch { + #[cfg(not(web))] + Thread(std::sync::mpsc::Receiver>), + /// The worker and the options to set once it answered. + #[cfg(web)] + Worker(uci::Starting, EngineConfig), +} + +impl Launch { + /// The engine once it answered, its options set (or why it did not answer). + fn poll(&mut self) -> Option> { + match self { + #[cfg(not(web))] + Launch::Thread(rx) => rx.try_recv().ok(), + #[cfg(web)] + Launch::Worker(s, cfg) => s.poll().map(|r| r.inspect(|h| set_options(h, cfg))), + } + } +} + +/// Threads, hash and lines of `cfg` (unknown options are not fatal: some engines lack +/// Threads/Hash/MultiPV). +fn set_options(h: &EngineHandle, cfg: &EngineConfig) { + let _ = h.set_threads(cfg.threads); + let _ = h.set_hash_mb(cfg.hash_mb); + let _ = h.set_multipv(cfg.multipv.max(1)); +} + pub struct Analysis { engine: Option, - spawning: Option>>, + spawning: Option, pub status: Status, pub engine_name: String, next_id: u64, @@ -56,7 +86,7 @@ pub struct Analysis { /// The current search ended (time limit reached); lines stay as the final result. pub finished: bool, /// Executable of the running engine (to detect a switch of the active engine). - pub engine_path: Option, + pub engine_path: Option, } impl Analysis { @@ -90,7 +120,7 @@ impl Analysis { matches!(self.status, Status::Starting | Status::Running) } - /// Starts the engine in a background thread (handshake blocks for up to ~20 s). + /// Starts the engine in the background: its options are set once it answered. pub fn start(&mut self, cfg: &EngineConfig, ctx: &egui::Context) { self.stop(); let Some(path) = cfg.executable() else { @@ -98,48 +128,32 @@ impl Analysis { Status::Failed(tr("The built-in engine is not part of this build").into()); return; }; - let (tx, rx) = channel(); - let ctx_w = ctx.clone(); - let ctx_done = ctx.clone(); - let cfg = cfg.clone(); self.engine_name = cfg.name.clone(); self.multipv = cfg.multipv.max(1); self.limit = cfg.search_secs; self.engine_path = Some(path.clone()); - let spawned = std::thread::Builder::new() - .name("engine-spawn".into()) - .spawn(move || { - let res = uci::Engine::spawn_with( - uci::EngineConfig::new(&path), - Box::new(move || ctx_w.request_repaint()), - ) - .inspect(|h| { - // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. - let _ = h.set_threads(cfg.threads); - let _ = h.set_hash_mb(cfg.hash_mb); - let _ = h.set_multipv(cfg.multipv.max(1)); - }); - let _ = tx.send(res); - ctx_done.request_repaint(); - }); - match spawned { - Ok(_) => { - self.spawning = Some(rx); + match launch(path, cfg.clone(), ctx) { + Ok(l) => { + self.spawning = Some(l); self.status = Status::Starting; } - Err(e) => self.status = Status::Failed(e.to_string()), + Err(e) => self.status = Status::Failed(e), } } - /// Stops analysis and terminates the engine process. + /// Stops analysis and terminates the engine. pub fn stop(&mut self) { if let Some(e) = self.engine.take() { - // quit() may wait up to the quit timeout; do it off the UI thread. + // quit() may wait up to the quit timeout; do it off the UI thread. A worker + // stops at once. + #[cfg(not(web))] let _ = std::thread::Builder::new() .name("engine-quit".into()) .spawn(move || { e.quit(); }); + #[cfg(web)] + e.quit(); } self.spawning = None; self.current = None; @@ -212,9 +226,7 @@ impl Analysis { /// Drains engine events; call once per frame. pub fn poll(&mut self) { - if let Some(rx) = &self.spawning - && let Ok(res) = rx.try_recv() - { + if let Some(res) = self.spawning.as_mut().and_then(Launch::poll) { self.spawning = None; match res { Ok(h) => { @@ -281,6 +293,49 @@ impl Analysis { } } +/// Starts the engine of `cfg` at `path` with its options. +#[cfg(not(web))] +fn launch( + location: crate::engines::EngineLocation, + cfg: EngineConfig, + ctx: &egui::Context, +) -> Result { + let crate::engines::EngineLocation::Program(path) = location; + let (tx, rx) = std::sync::mpsc::channel(); + let ctx_w = ctx.clone(); + let ctx_done = ctx.clone(); + std::thread::Builder::new() + .name("engine-spawn".into()) + .spawn(move || { + let res = uci::Engine::spawn_with( + uci::EngineConfig::new(&path), + Box::new(move || ctx_w.request_repaint()), + ) + .inspect(|h| set_options(h, &cfg)); + let _ = tx.send(res); + ctx_done.request_repaint(); + }) + .map(|_| Launch::Thread(rx)) + .map_err(|e| e.to_string()) +} + +/// Starts the engine of `cfg` in its Web Worker. +#[cfg(web)] +fn launch( + location: crate::engines::EngineLocation, + cfg: EngineConfig, + ctx: &egui::Context, +) -> Result { + let crate::engines::EngineLocation::Worker(script) = location; + let ctx = ctx.clone(); + uci::Engine::start_worker( + uci::WorkerConfig::new(script), + Box::new(move || ctx.request_repaint()), + ) + .map(|s| Launch::Worker(s, cfg)) + .map_err(|e| e.to_string()) +} + impl Drop for Analysis { fn drop(&mut self) { self.stop(); diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 71976bc..cdd038b 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -25,11 +25,35 @@ use crate::sound::SoundPlayer; /// Results of work done off the UI thread (file dialogs, engine checks). enum Async { DatabasesPicked(Vec), + /// Files not opened: too big for a browser (name, bytes). + #[cfg(web)] + TooBig(Vec<(String, u64)>), SavePicked(PathBuf), SaveCancelled, EngineChecked(Result<(PathBuf, String), String>), /// The folder for new databases (`None`: the dialog was cancelled). FolderPicked(Option), + /// A remembered file the browser let the page read again. + #[cfg(web)] + ReadAllowed(PathBuf), + /// ChessBase databases not all files of which were chosen (their `.cbh` names). + #[cfg(web)] + Incomplete(Vec), + /// A folder was chosen with no database in it. + #[cfg(web)] + EmptyFolder, + /// A copy of the visit's database `.0` kept in the browser, or why not. + #[cfg(web)] + CopyKept(PathBuf, Result), +} + +/// What the web version tells in a window of its own about the files chosen. +#[cfg(web)] +enum WebNotice { + /// Databases too big for a browser (name, bytes). + TooBig(Vec<(String, u64)>), + /// A ChessBase database's `.cbh` chosen without its other files (its name). + Incomplete(String), } /// A passing message at the bottom; `undo`: with the button that puts a deleted game back. @@ -215,19 +239,27 @@ pub struct App { play_next: Option, tx: Sender, rx: Receiver, + /// «Paste PGN»: the clipboard being read. + pasting: Option, + /// A file of the last visit being chosen again (a browser's). + choosing_again: Option, + /// The web version's draft of an unsaved game: the one left at the last visit + /// (offered), and when this visit's was last written (egui time; `None`: none). + #[cfg(web)] + draft_offer: Option, + #[cfg(web)] + draft_at: Option, + #[cfg(web)] + web_notice: Option, confirm_close: Option, /// Close the game once the pending "save as" succeeds. close_after_save: Option, /// The offer to download Stockfish when an action needs an engine. engine_offer: crate::engine_offer::EngineOffer, offer_hook_done: bool, - /// Lichess / Chess.com: which answered at start, and the download window. - online_probe: crate::online::Probe, - /// When the online databases were last updated on their own (egui time, s), and - /// whether the window had the focus in the last frame. - online_updated_at: f64, - was_focused: bool, - online: crate::online_ui::OnlineDialog, + /// What only the desktop program has: online games, updates. + #[cfg(not(web))] + desktop: Desktop, /// Translating comments: the setup and consent windows, the ChatGPT sign-in. translation: crate::translate_ui::Hub, /// A position to find in a database once the game is closed. @@ -237,11 +269,7 @@ pub struct App { previous_games: Vec, /// The last game showed the reference tab: the next one opens with it too. reference_tab: bool, - /// Updates: the release check, how this copy is installed, the window, and the - /// executable to start after quitting (a restart into the new version). - update_check: crate::update::Check, - update_kind: crate::update::Install, - update_ui: crate::update_ui::UpdateDialog, + /// The executable to start after quitting (a restart into the new version). restart_to: Option, /// The reference tab of games (kept across games: its results stay cached). reference: crate::reference::Reference, @@ -257,6 +285,52 @@ pub struct App { debug: DebugStartup, } +/// What only the desktop program has. +#[cfg(not(web))] +struct Desktop { + /// Lichess / Chess.com: which answered at start, and the download window. + online_probe: crate::online::Probe, + /// When the online databases were last updated on their own (egui time, s), and + /// whether the window had the focus in the last frame. + online_updated_at: f64, + was_focused: bool, + online: crate::online_ui::OnlineDialog, + /// Updates: the release check, how this copy is installed, the window. + update_check: crate::update::Check, + update_kind: crate::update::Install, + update_ui: crate::update_ui::UpdateDialog, +} + +#[cfg(not(web))] +impl Desktop { + fn new(ctx: &egui::Context, settings: &Settings) -> Desktop { + let online_dbs: Vec = settings + .databases + .iter() + .filter(|p| crate::online::is_online(p)) + .cloned() + .collect(); + Desktop { + online_probe: crate::online::Probe::start(ctx), + online_updated_at: 0.0, + was_focused: true, + online: { + // Every downloaded database gets the games played since, at each start. + let mut d = crate::online_ui::OnlineDialog::from_env(); + d.update_quietly(online_dbs); + d + }, + update_check: if settings.check_updates { + crate::update::Check::start(ctx) + } else { + crate::update::Check::idle() + }, + update_kind: crate::update::detect(), + update_ui: crate::update_ui::UpdateDialog::from_env(), + } + } +} + /// Dev-only startup automation for screenshots/manual QA (see docs/dev/desktop.md): /// `CP_OPEN=` opens a game from the first database, `CP_PLY=` steps /// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings (`=board`, `=about`: that tab), @@ -343,18 +417,20 @@ impl App { // Before the samples, which are named in this language. crate::i18n::set_lang(settings.language); crate::engine_download::clean_leftovers(); - crate::update::clean_leftovers(); - let settings_check_updates = settings.check_updates; - // "Updated to …" once, when this version runs for the first time after another. let current = env!("CARGO_PKG_VERSION"); - let updated_from = settings - .last_version - .clone() - .filter(|v| crate::update::parse_version(v) < crate::update::parse_version(current)); - if settings.install_id.is_empty() { - settings.install_id = crate::update::new_install_id(); - } - crate::update::set_install_id(&settings.install_id); + #[cfg(not(web))] + let updated_from = { + crate::update::clean_leftovers(); + // "Updated to …" once, when this version runs for the first time after another. + let from = settings.last_version.clone().filter(|v| { + crate::update::parse_version(v) < crate::update::parse_version(current) + }); + if settings.install_id.is_empty() { + settings.install_id = crate::update::new_install_id(); + } + crate::update::set_install_id(&settings.install_id); + from + }; if settings.last_version.as_deref() != Some(current) { settings.last_version = Some(current.to_owned()); let _ = settings.save(); @@ -363,6 +439,11 @@ impl App { if crate::examples::setup(&mut settings) || engines_found { let _ = settings.save(); } + // After the samples: a new library opens on the classics. + #[cfg(web)] + if crate::my_games::setup(&mut settings) { + let _ = settings.save(); + } // PGN files passed on the command line (e.g. "Open with…") join the library, first one selected. let args: Vec = std::env::args_os() .skip(1) @@ -376,12 +457,8 @@ impl App { if !args.is_empty() { let _ = settings.save(); } - let online_dbs: Vec = settings - .databases - .iter() - .filter(|p| crate::online::is_online(p)) - .cloned() - .collect(); + #[cfg(not(web))] + let desktop = Desktop::new(ctx, &settings); let (tx, rx) = channel(); let mut library = Library::new(ctx); // Read in the background: a missing file says so there (a lost network drive @@ -408,18 +485,19 @@ impl App { play_next: None, tx, rx, + pasting: None, + choosing_again: None, + #[cfg(web)] + draft_offer: crate::my_games::read_draft(), + #[cfg(web)] + draft_at: None, + #[cfg(web)] + web_notice: None, confirm_close: None, close_after_save: None, find_after_close: None, previous_games: Vec::new(), reference_tab: false, - update_check: if settings_check_updates { - crate::update::Check::start(ctx) - } else { - crate::update::Check::idle() - }, - update_kind: crate::update::detect(), - update_ui: crate::update_ui::UpdateDialog::from_env(), restart_to: None, reference: Default::default(), prep_dialog: None, @@ -428,21 +506,15 @@ impl App { prep_quit_ok: false, engine_offer: crate::engine_offer::EngineOffer::new(), offer_hook_done: false, - online_probe: crate::online::Probe::start(ctx), - online_updated_at: 0.0, - was_focused: true, - online: { - // Every downloaded database gets the games played since, at each start. - let mut d = crate::online_ui::OnlineDialog::from_env(); - d.update_quietly(online_dbs); - d - }, + #[cfg(not(web))] + desktop, translation: Default::default(), allow_quit: false, applied_dark: None, debug: DebugStartup::from_env(), } .with_debug_settings(); + #[cfg(not(web))] if let Some(from) = updated_from { let msg = trf( "ChessPenguin is updated: {from} → {to}", @@ -957,6 +1029,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() { @@ -1004,7 +1086,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() { @@ -1145,7 +1227,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); @@ -1184,7 +1266,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() { @@ -1279,7 +1361,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); @@ -1325,7 +1407,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()); @@ -1480,7 +1562,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; @@ -1537,7 +1619,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()) { @@ -1740,7 +1822,7 @@ impl App { self.settings .active_engine() .and_then(|e| e.executable()) - .filter(|p| p.is_file()) + .filter(|l| l.present()) }); let Some(aside) = self.put_aside.take() else { return; @@ -1978,7 +2060,7 @@ impl App { self.settings .active_engine() .and_then(|e| e.executable()) - .filter(|p| p.is_file()) + .filter(|l| l.present()) }); match &start.from { Some(from) => self.game_from(from), @@ -2052,6 +2134,7 @@ impl App { self.own.editor = Some((editor, EditorThen::Done)); } + #[cfg(not(web))] fn pick_folder(&self, ctx: &egui::Context, start: PathBuf) { self.spawn_dialog(ctx, move || { let picked = rfd::FileDialog::new() @@ -2119,7 +2202,13 @@ impl App { self.settings.last_target = Some(dest.clone()); self.settings_dirty = true; self.library.select_db(&dest, ctx); - self.toast(ctx, trf("Copy made: {path}", &[("path", &dest.display())])); + self.toast( + ctx, + trf( + "Copy made: {path}", + &[("path", &crate::platform::files::shown(&dest))], + ), + ); } Err(e) => { self.toast(ctx, trf("Could not make the copy: {e}", &[("e", &e)])) @@ -2217,7 +2306,11 @@ impl App { } ChooserOutcome::SaveAsFile => { self.close_after_save = self.own.then_close.take(); + #[cfg(not(web))] self.pick_save(ctx); + // A file of its own in a browser: a download. + #[cfg(web)] + self.download_pgn(ctx); } ChooserOutcome::Cancel => { if let Some(intent) = self.own.then_close.take() { @@ -2231,9 +2324,13 @@ impl App { && let Some(outcome) = dialog.show(ctx) { match outcome { + // A browser has no folders: there are no new databases there. NewBaseOutcome::PickFolder => { - let start = dialog.dir.clone(); - self.pick_folder(ctx, start); + #[cfg(not(web))] + { + let start = dialog.dir.clone(); + self.pick_folder(ctx, start); + } } NewBaseOutcome::Cancel => { self.own.new_base = None; @@ -2294,6 +2391,7 @@ impl App { } } + #[cfg(not(web))] fn spawn_dialog( &self, ctx: &egui::Context, @@ -2312,22 +2410,14 @@ impl App { } fn pick_databases(&self, ctx: &egui::Context) { - self.spawn_dialog(ctx, || { - rfd::FileDialog::new() - .set_title(tr("Open database")) - .add_filter( - tr("Chess databases"), - &[ - "pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z", - ], - ) - .add_filter("PGN", &["pgn", "PGN"]) - .add_filter(tr("All files"), &["*"]) - .pick_files() - .map(Async::DatabasesPicked) + let (tx, ctx) = (self.tx.clone(), ctx.clone()); + crate::platform::files::pick_databases(move |picked| { + send_picked(&tx, picked); + ctx.request_repaint(); }); } + #[cfg(not(web))] fn pick_save(&self, ctx: &egui::Context) { let Some(g) = &self.game else { return }; let name = sanitize(&g.title()) + ".pgn"; @@ -2341,6 +2431,7 @@ impl App { }); } + #[cfg(not(web))] fn pick_engine(&mut self, ctx: &egui::Context) { self.settings_ui.checking_engine = true; let tx = self.tx.clone(); @@ -2373,9 +2464,33 @@ impl App { } fn handle_async(&mut self, ctx: &egui::Context) { + self.pasted(ctx); while let Ok(msg) = self.rx.try_recv() { match msg { + #[cfg(web)] + Async::TooBig(files) => self.web_notice = Some(WebNotice::TooBig(files)), + #[cfg(web)] + Async::Incomplete(names) => { + if let Some(name) = names.into_iter().next() { + self.web_notice = Some(WebNotice::Incomplete(name)); + } + } + #[cfg(web)] + Async::EmptyFolder => { + self.toast( + ctx, + tr("There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z)."), + ); + } + #[cfg(web)] + Async::CopyKept(path, kept) => self.copy_kept(ctx, path, kept), Async::DatabasesPicked(paths) => { + // The file chosen again takes the place of the one gone. + if let Some(old) = self.choosing_again.take() { + self.settings.databases.retain(|d| *d != old); + self.library.forget(&old); + crate::platform::files::forget(&old); + } for p in paths.iter().rev() { self.settings.touch_database(p); } @@ -2385,6 +2500,8 @@ impl App { self.settings_dirty = true; } Async::SavePicked(path) => self.save_game(ctx, path), + #[cfg(web)] + Async::ReadAllowed(path) => self.library.reload(&path, ctx), Async::SaveCancelled => { self.close_after_save = None; self.restart_to = None; @@ -2446,7 +2563,13 @@ impl App { match chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) { Ok(()) => { g.game.mark_saved(); - self.toast(ctx, trf("Saved: {path}", &[("path", &path.display())])); + self.toast( + ctx, + trf( + "Saved: {path}", + &[("path", &crate::platform::files::shown(&path))], + ), + ); if let Some(intent) = self.close_after_save.take() { self.finish_close(ctx, intent); } @@ -2691,16 +2814,275 @@ impl App { let cfg = crate::settings::EngineConfig::new("Stockfish".into(), path); self.engine_arrived(ctx, cfg, pending) } + #[cfg(not(web))] crate::engine_offer::OfferEvent::ChooseFile => self.pick_engine(ctx), crate::engine_offer::OfferEvent::Toast(m) => self.toast(ctx, m), } } } + /// The page's side of the frame: the game on the screen as an entry of the browser's + /// history, the browser's question on leaving with unsaved work, the draft of an + /// unsaved game. Nothing of it on a computer. + fn page_frame(&mut self, ctx: &egui::Context) { + crate::platform::page::game_shown(ctx, self.game.is_some()); + let modified = self.game.as_ref().is_some_and(|g| g.game.is_modified()); + let reviewing = self.game.as_ref().is_some_and(|g| g.review_running()); + crate::platform::page::warn_on_leave(modified || reviewing); + #[cfg(web)] + { + const EVERY: f64 = 5.0; + let now = ctx.input(|i| i.time); + match self.game.as_ref().filter(|g| g.game.is_modified()) { + Some(g) if self.draft_at.is_none_or(|t| now - t >= EVERY) => { + crate::my_games::write_draft(&crate::my_games::Draft { + title: g.title(), + moves: g.game.mainline().len().div_ceil(2), + pgn: g.game.to_pgn(), + }); + self.draft_at = Some(now); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(EVERY)); + } + Some(_) => {} + // Saved, or left without saving: no draft of this visit is kept. + None if self.draft_at.take().is_some() => crate::my_games::delete_draft(), + None => {} + } + } + } + + /// «There is an unsaved game» over the library, with Open and Delete. + #[cfg(web)] + fn draft_strip(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + let Some(d) = self.draft_offer.clone() else { + return; + }; + let mut open = false; + let mut delete = false; + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(8, 6)) + .fill(ui.visuals().faint_bg_color) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(trf( + "There is an unsaved game: {title}, moves: {n}.", + &[("title", &d.title), ("n", &d.moves)], + )) + .color(ui.visuals().warn_fg_color), + ); + open = ui.button(tr("Open")).clicked(); + delete = ui.button(tr("Delete")).clicked(); + }); + }); + if open { + self.draft_offer = None; + self.open_pgn_text(ctx, d.pgn, false); + crate::my_games::delete_draft(); + } else if delete { + self.draft_offer = None; + crate::my_games::delete_draft(); + } + } + + /// Files dropped on the window open as databases, like chosen ones; while files are + /// 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 |picked| { + send_picked(&tx, picked); + waker.request_repaint(); + }); + if crate::platform::files::dragging(ctx) { + let rect = ctx.content_rect(); + let painter = ctx.layer_painter(egui::LayerId::new( + egui::Order::Foreground, + egui::Id::new("dropping files"), + )); + let visuals = ctx.global_style().visuals.clone(); + let accent = visuals.selection.bg_fill; + painter.rect_filled(rect, 0.0, accent.gamma_multiply(0.12)); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("Release to open"), + egui::FontId::proportional(22.0), + visuals.strong_text_color(), + ); + } + } + + /// 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)] + { + let (tx, wake) = (self.tx.clone(), ctx.clone()); + crate::platform::files::keep_copy(&path.clone(), move |kept| { + let _ = tx.send(Async::CopyKept(path, kept)); + wake.request_repaint(); + }); + } + #[cfg(not(web))] + let _ = (ctx, path); + } + + /// The copy of `path` is kept (or not): it takes the file's place on the shelf. + #[cfg(web)] + fn copy_kept( + &mut self, + ctx: &egui::Context, + path: PathBuf, + kept: Result, + ) { + { + use crate::platform::files::KeepCopy; + use crate::platform::size_text; + match kept { + Ok(copy) => { + for d in self.settings.databases.iter_mut().filter(|d| **d == path) { + *d = copy.clone(); + } + self.library.forget(&path); + crate::platform::files::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), + } + } + } + + /// The window of [`WebNotice`]: a database too big for a browser (with the way to + /// the program for the computer), or a ChessBase database's other files to choose. + #[cfg(web)] + fn web_notice(&mut self, ctx: &egui::Context) { + let Some(notice) = &self.web_notice else { + return; + }; + let mut close = false; + let mut folder = false; + let mut files = false; + let modal = egui::Modal::new(egui::Id::new("web_notice")).show(ctx, |ui| { + ui.set_width(460.0); + match notice { + WebNotice::TooBig(dbs) => { + for (name, size) in dbs { + ui.label(RichText::new(name.as_str()).strong()); + ui.label(trf( + "This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.", + &[ + ("size", &crate::platform::size_text(*size)), + ("limit", &crate::platform::size_text(crate::platform::files::TOO_BIG)), + ], + )); + } + ui.add_space(6.0); + let lang = match crate::i18n::current() { + crate::i18n::Lang::En => "", + crate::i18n::Lang::Ru => "ru/", + crate::i18n::Lang::Fr => "fr/", + crate::i18n::Lang::De => "de/", + crate::i18n::Lang::Es => "es/", + crate::i18n::Lang::It => "it/", + crate::i18n::Lang::Pt => "pt/", + crate::i18n::Lang::Uz => "uz/", + crate::i18n::Lang::Kk => "kk/", + }; + ui.hyperlink_to( + tr("Download ChessPenguin for the computer"), + format!("/{lang}#download"), + ); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + close = ui.button(tr("Close")).clicked(); + }); + } + WebNotice::Incomplete(name) => { + ui.label(RichText::new(name.as_str()).strong()); + ui.label(tr( + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + )); + ui.add_space(4.0); + ui.label( + RichText::new(if crate::platform::files::remembers_chosen() { + tr("Allow access to the database's folder — its other files will be found by themselves.") + } else { + tr("Choose the database's folder — its other files will be found by themselves.") + }) + .weak(), + ); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + folder = ui.button(tr("📁 Choose the database's folder")).clicked(); + files = ui.button(tr("Choose the database's files")).clicked(); + close = ui.button(tr("Cancel")).clicked(); + }); + } + } + }); + if close || modal.should_close() { + self.web_notice = None; + } + if folder { + self.web_notice = None; + self.pick_database_folder(ctx); + } + if files { + self.web_notice = None; + self.pick_databases(ctx); + } + } + + #[cfg(web)] + fn pick_database_folder(&self, ctx: &egui::Context) { + let (tx, ctx) = (self.tx.clone(), ctx.clone()); + crate::platform::files::pick_database_folder(move |picked| { + send_picked(&tx, picked); + ctx.request_repaint(); + }); + } + + /// The open game's PGN, downloaded as a file named after the game. + #[cfg(web)] + fn download_pgn(&mut self, ctx: &egui::Context) { + let Some(g) = &self.game else { return }; + let name = sanitize(&g.title()) + ".pgn"; + if let Err(e) = crate::platform::files::download_pgn(&name, &g.game.to_pgn()) { + self.toast( + ctx, + trf("The PGN could not be downloaded: {e}", &[("e", &e)]), + ); + } + } + fn paste_pgn(&mut self, ctx: &egui::Context) { - let text = arboard::Clipboard::new().and_then(|mut c| c.get_text()); + self.pasting = Some(crate::platform::clipboard::read_text(ctx)); + } + + /// The clipboard read for «Paste PGN», once it is there. + fn pasted(&mut self, ctx: &egui::Context) { + let Some(text) = self.pasting.as_ref().and_then(|r| r.poll()) else { + return; + }; + self.pasting = None; match text { - Ok(t) if !t.trim().is_empty() => self.open_pgn_text(ctx, t, false), + Some(t) if !t.trim().is_empty() => self.open_pgn_text(ctx, t, false), _ => self.toast(ctx, tr("The clipboard is empty or unavailable")), } } @@ -2840,12 +3222,108 @@ impl App { _ => {} } } + + /// Online games and updates, each frame (the desktop program's). + #[cfg(not(web))] + fn desktop_frame(&mut self, ctx: &egui::Context) { + // Back to the window after a while: the downloaded databases get the games + // played since (at the start they did already). + let now = ctx.input(|i| i.time); + let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); + if focused + && !self.desktop.was_focused + && now - self.desktop.online_updated_at > ONLINE_EVERY + { + self.desktop.online_updated_at = now; + self.desktop.online.update_quietly( + self.settings + .databases + .iter() + .filter(|p| crate::online::is_online(p)) + .cloned(), + ); + } + self.desktop.was_focused = focused; + let events = self.desktop.online.show(ctx, &self.desktop.online_probe); + for e in events { + match e { + crate::online_ui::OnlineEvent::Added(p) => { + let known = self.settings.databases.contains(&p); + self.settings.touch_database(&p); + if known { + self.library.reload(&p, ctx); + } + self.library.select_db(&p, ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Updated(p) => self.library.reload(&p, ctx), + crate::online_ui::OnlineEvent::Open(p) => { + self.settings.touch_database(&p); + self.library.select_db(&p, ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Message(t) => self.toast(ctx, t), + } + } + // Updates: the badge next to Settings, the window, the status in Settings → About. + self.desktop.update_check.poll(); + let skipped = self.settings.skipped_version.clone(); + let badge = self + .desktop + .update_check + .newer() + .filter(|r| { + self.desktop.update_ui.active() || skipped.as_deref() != Some(r.version.as_str()) + }) + .map(|r| self.desktop.update_ui.badge(r)); + self.library.update = badge.clone(); + if let Some(g) = &mut self.game { + g.update = badge; + } + for e in self.desktop.update_ui.show( + ctx, + self.desktop.update_check.newer(), + &self.desktop.update_kind, + ) { + match e { + crate::update_ui::UpdateEvent::Restart(exe) => { + self.restart_to = Some(exe); + self.request_close(ctx, CloseIntent::QuitApp); + } + crate::update_ui::UpdateEvent::CopyText(t) => { + ctx.copy_text(t); + self.toast(ctx, tr("Copied")); + } + crate::update_ui::UpdateEvent::Quit => { + self.request_close(ctx, CloseIntent::QuitApp); + } + crate::update_ui::UpdateEvent::Skip(v) => { + self.settings.skipped_version = Some(v); + self.settings_dirty = true; + } + } + } + self.settings_ui.update_available = + self.desktop.update_check.newer().map(|r| r.version.clone()); + self.settings_ui.update_status = if self.desktop.update_check.running() { + Some(tr("Checking…").to_owned()) + } else if let Some(r) = self.desktop.update_check.newer() { + Some(trf("Version {v} is out", &[("v", &r.version)])) + } else if self.desktop.update_check.release.is_some() { + Some(tr("This is the latest version").to_owned()) + } else if self.desktop.update_check.error.is_some() { + Some(tr("Could not check for updates").to_owned()) + } else { + None + }; + } } impl eframe::App for App { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { crate::san::set(self.settings.move_notation); // The window has shown its first frame: this graphics mode works. + #[cfg(not(web))] if ui.ctx().cumulative_frame_nr() >= 1 { crate::graphics::started(); } @@ -2915,7 +3393,12 @@ impl eframe::App for App { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); self.confirm_close = Some(CloseIntent::QuitApp); } + self.dropped_files(&ctx); self.handle_async(&ctx); + // The browser's «Back» in a game: «← Library». + if crate::platform::page::take_back() && self.game.is_some() { + self.request_close(&ctx, CloseIntent::BackToLibrary); + } // Dev hook (screenshots): the engine offer as on pressing L without an engine. if std::env::var("CP_ENGINE_OFFER").is_ok() && !self.offer_hook_done { self.offer_hook_done = true; @@ -2926,6 +3409,9 @@ impl eframe::App for App { } } self.offer_events(&ctx); + self.page_frame(&ctx); + #[cfg(web)] + self.web_notice(&ctx); self.debug_step(&ctx); self.debug_keys(&ctx); self.debug_screenshot(&ctx); @@ -2941,16 +3427,27 @@ impl eframe::App for App { Key::N, )) }) && self.game.is_none() + && crate::platform::CAPS.own_databases { self.own.then_close = None; self.new_base_dialog(own_db::AfterCreate::Shelf); } // In the library a game from the start; on a game's screen the game plays on // from its position (the game view takes Ctrl+G there). - if self.game.is_none() && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) { + if self.game.is_none() + && crate::platform::CAPS.play + && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) + { 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))) { @@ -3028,7 +3525,10 @@ impl eframe::App for App { } } } - GameAction::OpenUpdate => self.update_ui.open = true, + #[cfg(not(web))] + GameAction::OpenUpdate => self.desktop.update_ui.open = true, + #[cfg(web)] + GameAction::DownloadPgn => self.download_pgn(&ctx), GameAction::ReturnToPrevious => { if !self.previous_games.is_empty() || self.prep.as_ref().is_some_and(|p| p.shown) @@ -3188,10 +3688,16 @@ impl eframe::App for App { { self.prep_dialog = Some(PrepDialog::new(path, entry.unwrap_or_default())); } - self.online_probe.poll(); - self.library.online = self.online_probe.any(); - self.library.online_busy = self.online.busy(); - self.library.online_running = self.online.running(); + #[cfg(not(web))] + { + let d = &mut self.desktop; + d.online_probe.poll(); + self.library.online = d.online_probe.any(); + self.library.online_busy = d.online.busy(); + self.library.online_running = d.online.running(); + } + #[cfg(web)] + self.draft_strip(ui, &ctx); for a in self.library.show(ui, &dbs, &self.settings) { match a { LibraryAction::OpenGame { path, index, at } => { @@ -3221,23 +3727,47 @@ impl eframe::App for App { } LibraryAction::PastePgn => self.paste_pgn(&ctx), LibraryAction::AddDatabases => self.pick_databases(&ctx), - LibraryAction::OnlineGames => self.online.open(), - LibraryAction::UpdateOnline(p) => self.online.update(&p, &ctx), - LibraryAction::OpenUpdate => self.update_ui.open = true, + #[cfg(not(web))] + LibraryAction::OnlineGames => self.desktop.online.open(), + #[cfg(not(web))] + LibraryAction::UpdateOnline(p) => self.desktop.online.update(&p, &ctx), + #[cfg(not(web))] + LibraryAction::OpenUpdate => self.desktop.update_ui.open = true, LibraryAction::RemoveDatabase(p) => { self.settings.databases.retain(|d| *d != p); self.library.forget(&p); + crate::platform::files::forget(&p); self.settings_dirty = true; // The file stays where it is; said so, with the place. self.toast = Some(Toast { text: trf( "Removed from the shelf; the file stays: {path}", - &[("path", &p.display())], + &[("path", &crate::platform::files::shown(&p))], ), until: ctx.input(|i| i.time) + 6.0, undo: false, }); } + #[cfg(web)] + LibraryAction::AllowReading(p) => { + let (tx, wake) = (self.tx.clone(), ctx.clone()); + crate::platform::files::allow_reading(&p.clone(), move |back| { + if back { + let _ = tx.send(Async::ReadAllowed(p)); + } + wake.request_repaint(); + }); + } + LibraryAction::ChooseAgain(p) => { + self.choosing_again = Some(p); + self.pick_databases(&ctx); + } + #[cfg(web)] + LibraryAction::ChooseFolderAgain(p) => { + self.choosing_again = Some(p); + self.pick_database_folder(&ctx); + } + LibraryAction::KeepCopy(p) => self.keep_copy(&ctx, p), LibraryAction::OpenSettings => self.settings_ui.open = true, LibraryAction::NewDatabase => { self.own.then_close = None; @@ -3262,88 +3792,8 @@ impl eframe::App for App { } } - // Back to the window after a while: the downloaded databases get the games - // played since (at the start they did already). - let now = ctx.input(|i| i.time); - let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); - if focused && !self.was_focused && now - self.online_updated_at > ONLINE_EVERY { - self.online_updated_at = now; - self.online.update_quietly( - self.settings - .databases - .iter() - .filter(|p| crate::online::is_online(p)) - .cloned(), - ); - } - self.was_focused = focused; - let events = self.online.show(&ctx, &self.online_probe); - for e in events { - match e { - crate::online_ui::OnlineEvent::Added(p) => { - let known = self.settings.databases.contains(&p); - self.settings.touch_database(&p); - if known { - self.library.reload(&p, &ctx); - } - self.library.select_db(&p, &ctx); - self.settings_dirty = true; - } - crate::online_ui::OnlineEvent::Updated(p) => self.library.reload(&p, &ctx), - crate::online_ui::OnlineEvent::Open(p) => { - self.settings.touch_database(&p); - self.library.select_db(&p, &ctx); - self.settings_dirty = true; - } - crate::online_ui::OnlineEvent::Message(t) => self.toast(&ctx, t), - } - } - // Updates: the badge next to Settings, the window, the status in Settings → About. - self.update_check.poll(); - let skipped = self.settings.skipped_version.clone(); - let badge = self - .update_check - .newer() - .filter(|r| self.update_ui.active() || skipped.as_deref() != Some(r.version.as_str())) - .map(|r| self.update_ui.badge(r)); - self.library.update = badge.clone(); - if let Some(g) = &mut self.game { - g.update = badge; - } - for e in self - .update_ui - .show(&ctx, self.update_check.newer(), &self.update_kind) - { - match e { - crate::update_ui::UpdateEvent::Restart(exe) => { - self.restart_to = Some(exe); - self.request_close(&ctx, CloseIntent::QuitApp); - } - crate::update_ui::UpdateEvent::CopyText(t) => { - ctx.copy_text(t); - self.toast(&ctx, tr("Copied")); - } - crate::update_ui::UpdateEvent::Quit => { - self.request_close(&ctx, CloseIntent::QuitApp); - } - crate::update_ui::UpdateEvent::Skip(v) => { - self.settings.skipped_version = Some(v); - self.settings_dirty = true; - } - } - } - self.settings_ui.update_available = self.update_check.newer().map(|r| r.version.clone()); - self.settings_ui.update_status = if self.update_check.running() { - Some(tr("Checking…").to_owned()) - } else if let Some(r) = self.update_check.newer() { - Some(trf("Version {v} is out", &[("v", &r.version)])) - } else if self.update_check.release.is_some() { - Some(tr("This is the latest version").to_owned()) - } else if self.update_check.error.is_some() { - Some(tr("Could not check for updates").to_owned()) - } else { - None - }; + #[cfg(not(web))] + self.desktop_frame(&ctx); self.settings_ui.download = self.engine_offer.stage(); self.settings_dirty |= self.translation.poll(&ctx, &mut self.settings); @@ -3358,15 +3808,33 @@ impl eframe::App for App { self.settings_dirty |= changed; for a in actions { match a { + #[cfg(not(web))] SettingsAction::AddEngine => self.pick_engine(&ctx), + #[cfg(not(web))] SettingsAction::CheckUpdates => { - self.update_check = self.update_check.again(&ctx); + self.desktop.update_check = self.desktop.update_check.again(&ctx); } + #[cfg(not(web))] SettingsAction::PickBaseFolder => { let start = own_db::default_base_dir(self.settings.new_database_dir.as_deref()); self.pick_folder(&ctx, start); } - SettingsAction::OpenUpdate => self.update_ui.open = true, + #[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 => { @@ -3500,7 +3968,8 @@ impl eframe::App for App { } // Downloads of online games stop and save what they got; a new database goes on // the shelf with it (the next download continues it). - for p in self.online.stop_all() { + #[cfg(not(web))] + for p in self.desktop.online.stop_all() { if crate::online::State::load(&p).is_some_and(|s| s.games > 0) { self.settings.touch_database(&p); } @@ -3509,6 +3978,25 @@ impl eframe::App for App { } } +/// What the user chose or dropped, to the screen. +fn send_picked(tx: &Sender, picked: crate::platform::files::Picked) { + if !picked.paths.is_empty() { + let _ = tx.send(Async::DatabasesPicked(picked.paths)); + } + #[cfg(web)] + { + if !picked.too_big.is_empty() { + let _ = tx.send(Async::TooBig(picked.too_big)); + } + if !picked.incomplete.is_empty() { + let _ = tx.send(Async::Incomplete(picked.incomplete)); + } + if picked.empty_folder { + let _ = tx.send(Async::EmptyFolder); + } + } +} + fn sanitize(s: &str) -> String { s.chars() .map(|c| match c { diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index 76445fc..eeeb618 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -883,7 +883,7 @@ pub fn ply_label(ply: u32) -> String { } } -/// A position search running in a background thread. +/// A position search (or other work with progress and cancelling) in the background. pub struct Background { cancel: Arc, progress: Arc, @@ -902,14 +902,12 @@ impl Background { let progress = Arc::new(AtomicUsize::new(0)); let (tx, rx) = channel(); let (c, p, ctx) = (cancel.clone(), progress.clone(), ctx.clone()); - std::thread::Builder::new() - .name("position-search".into()) - .spawn(move || { - let r = work(&p, &c); - let _ = tx.send(r); - ctx.request_repaint(); - }) - .ok()?; + crate::platform::spawn("position-search", move || { + let r = work(&p, &c); + let _ = tx.send(r); + ctx.request_repaint(); + }) + .ok()?; Some(Background { cancel, progress, diff --git a/apps/desktop/src/chatgpt.rs b/apps/desktop/src/chatgpt.rs index 0f69b51..57d79e3 100644 --- a/apps/desktop/src/chatgpt.rs +++ b/apps/desktop/src/chatgpt.rs @@ -12,7 +12,8 @@ use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, channel}; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use std::time::Duration; +use web_time::{Instant, SystemTime, UNIX_EPOCH}; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD; @@ -20,7 +21,9 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use crate::translate::{Failure, agent, update_credentials, with_waits}; +use crate::translate::{Failure, update_credentials}; +#[cfg(not(web))] +use crate::translate::{agent, with_waits}; const AUTHORIZE: &str = "https://auth.openai.com/api/accounts/authorize"; const TOKEN: &str = "https://auth.openai.com/api/accounts/oauth/token"; @@ -148,6 +151,13 @@ pub struct SignIn { } impl SignIn { + /// The web version does not sign in to ChatGPT (it would listen on a port). + #[cfg(web)] + pub fn start(_ctx: &egui::Context, _host_id: &str, _client_id: &str) -> Result { + Err("the web version does not sign in to ChatGPT".into()) + } + + #[cfg(not(web))] /// Starts listening for the callback and returns the address to open in the browser. pub fn start(ctx: &egui::Context, host_id: &str, client_id: &str) -> Result { let listener = PORTS @@ -217,6 +227,7 @@ impl Drop for SignIn { } } +#[cfg(not(web))] /// The page the browser tab shows after the sign-in. fn page(ok: bool) -> String { let (title, text) = if ok { @@ -240,6 +251,7 @@ fn page(ok: bool) -> String { ) } +#[cfg(not(web))] fn reply(stream: &mut TcpStream, status: &str, body: &str) { let _ = write!( stream, @@ -248,6 +260,7 @@ fn reply(stream: &mut TcpStream, status: &str, body: &str) { ); } +#[cfg(not(web))] /// Waits for the browser to come back to the callback: (code, issued client id). fn wait_for_callback( listener: &TcpListener, @@ -310,6 +323,7 @@ fn wait_for_callback( } } +#[cfg(not(web))] fn token_request(body: &str) -> Result { let mut resp = agent(Duration::from_secs(30)) .post(TOKEN) @@ -340,6 +354,7 @@ fn tokens_from(v: &Value, client_id: &str, old_refresh: &str) -> Tokens { } } +#[cfg(not(web))] fn exchange( code: &str, verifier: &str, @@ -380,9 +395,11 @@ fn exchange( }) } +#[cfg(not(web))] /// Refreshes are one at a time: the refresh token rotates. static REFRESH: Mutex<()> = Mutex::new(()); +#[cfg(not(web))] /// A valid access token, refreshed when it is about to expire. fn access_token() -> Result { let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner()); @@ -398,6 +415,7 @@ fn access_token() -> Result { refresh(&t) } +#[cfg(not(web))] fn refresh(t: &Tokens) -> Result { let body = form(&[ ("grant_type", "refresh_token"), @@ -459,11 +477,15 @@ pub fn sign_out() { return; }; update_credentials(|c| c.chatgpt = None); + #[cfg(not(web))] let _ = std::thread::Builder::new() .name("chatgpt-sign-out".into()) .spawn(move || revoke(&t)); + #[cfg(web)] + let _ = t; } +#[cfg(not(web))] fn revoke(t: &Tokens) -> bool { let body = form(&[ ("token", &t.refresh), @@ -489,6 +511,22 @@ fn revoke(t: &Tokens) -> bool { // --- Requests ------------------------------------------------------------------------------ +#[cfg(web)] +pub fn models() -> Result, Failure> { + Err(crate::translate::no_requests()) +} + +#[cfg(web)] +pub fn respond( + _model: &str, + _system: &str, + _user: &str, + _cancel: &AtomicBool, +) -> Result { + Err(crate::translate::no_requests()) +} + +#[cfg(not(web))] /// The models this account may use (`visibility: list`). pub fn models() -> Result, Failure> { let token = access_token()?; @@ -594,6 +632,7 @@ fn failure(status: u16, body: &str) -> Failure { } } +#[cfg(not(web))] /// One answer of the model, read from the event stream. pub fn respond( model: &str, @@ -655,6 +694,7 @@ pub fn respond( }) } +#[cfg(not(web))] /// The text of a Responses event stream: the deltas until `response.completed`. fn read_stream(reader: impl BufRead, cancel: &AtomicBool) -> Result { let mut text = String::new(); diff --git a/apps/desktop/src/db_counts.rs b/apps/desktop/src/db_counts.rs index 3209a42..fe9ee57 100644 --- a/apps/desktop/src/db_counts.rs +++ b/apps/desktop/src/db_counts.rs @@ -1,15 +1,14 @@ //! How many games each database on the shelf holds before it is opened: «not loaded» -//! on a card told the user nothing. A thread of its own counts the databases one after -//! another (reading a large one takes seconds; the screen never waits) and remembers the -//! counts with the file's size and time, so the next start shows them at once. A card -//! whose database is not counted yet says nothing. +//! on a card told the user nothing. The databases are counted one after another away +//! from the screen (reading a large one takes seconds; the screen never waits): on a +//! thread of its own, in a browser by the page's reader (`platform::web::import`). The +//! counts are remembered with the file's size and time, so the next start shows them +//! at once. A card whose database is not counted yet says nothing. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::atomic::AtomicBool; -use std::sync::mpsc::{Sender, channel}; +use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; -use std::time::UNIX_EPOCH; use chess_import::Database; use serde::{Deserialize, Serialize}; @@ -52,13 +51,145 @@ enum Job { Known(PathBuf, Count), } -#[derive(Default)] -struct Shared { - known: HashMap, +/// A file to read and count: its path and its size and time now. +struct ToCount(PathBuf, (u64, u64)); + +/// The counts known and where they are kept. +#[derive(Clone)] +struct Counter { + known: Arc>>, + /// `None`: for this run only. + file: Option, + ctx: egui::Context, +} + +impl Counter { + /// What the job leaves to do: a file to read, or nothing (its count is known now). + fn take(&self, job: Job) -> Option { + let (path, known) = match job { + Job::Count(p) => (p, None), + Job::Known(p, c) => (p, Some(c)), + }; + let stamp = stamp(&path)?; + let fresh = self.known.lock().ok().and_then(|k| { + k.get(&path) + .filter(|e| (e.size, e.modified) == stamp) + .map(|e| e.count) + }); + match known { + Some(c) if fresh == Some(c) => None, + Some(c) => { + self.record(path, stamp, c); + None + } + None if fresh.is_some() => None, + None => Some(ToCount(path, stamp)), + } + } + + fn record(&self, path: PathBuf, (size, modified): (u64, u64), count: Count) { + let json = match self.known.lock() { + Ok(mut k) => { + k.insert( + path, + Entry { + size, + modified, + count, + }, + ); + serde_json::to_vec(&*k).ok() + } + Err(_) => return, + }; + if let (Some(f), Some(json)) = (&self.file, json) { + let _ = crate::platform::fs::write_atomic(f, &json); + } + self.ctx.request_repaint(); + } + + /// Counts the files of the jobs, one after another, on a thread of its own. + #[cfg(not(web))] + fn start(self, jobs: Receiver) -> bool { + let spawned = std::thread::Builder::new() + .name("db-counts".into()) + .spawn(move || { + let never = std::sync::atomic::AtomicBool::new(false); + for job in jobs { + let Some(ToCount(path, stamp)) = self.take(job) else { + continue; + }; + // The card says why it cannot be read when the database is opened. + if let Ok(o) = chess_import::open(&path, &mut |_| {}, &never) { + self.record(path, stamp, Count::of(&o.db)); + } + } + }); + spawned.is_ok() + } + + /// Counts the files of the jobs, one after another, in the page's reader: the next + /// once the last is answered ([`Counts`] calls [`Counter::next`] after each job). + #[cfg(web)] + fn start(self, jobs: Receiver) -> bool { + WEB.with_borrow_mut(|w| { + *w = Some(Web { + counter: self, + jobs, + busy: false, + }) + }); + true + } + + #[cfg(web)] + fn next() { + let read = WEB.with_borrow_mut(|w| { + let w = w.as_mut()?; + if w.busy { + return None; + } + while let Ok(job) = w.jobs.try_recv() { + if let Some(to_count) = w.counter.take(job) { + w.busy = true; + return Some((w.counter.clone(), to_count)); + } + } + None + }); + let Some((counter, ToCount(path, stamp))) = read else { + return; + }; + crate::platform::web::import::count(&path.clone(), move |games| { + if let Some(games) = games { + let locked = false; + counter.record(path, stamp, Count { games, locked }); + } + WEB.with_borrow_mut(|w| { + if let Some(w) = w.as_mut() { + w.busy = false; + } + }); + Counter::next(); + }); + } +} + +/// The counting of the page: the jobs not taken yet, and whether a file is being read. +#[cfg(web)] +struct Web { + counter: Counter, + jobs: Receiver, + busy: bool, +} + +#[cfg(web)] +thread_local! { + static WEB: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } pub struct Counts { - shared: Arc>, + known: Arc>>, asked: HashSet, jobs: Option>, } @@ -73,106 +204,58 @@ impl Counts { fn kept_in(file: Option, ctx: &egui::Context) -> Self { let known: HashMap = file .as_ref() - .and_then(|f| std::fs::read(f).ok()) + .and_then(|f| crate::platform::fs::read(f).ok()) .and_then(|b| serde_json::from_slice(&b).ok()) .unwrap_or_default(); - let shared = Arc::new(Mutex::new(Shared { known })); + let known = Arc::new(Mutex::new(known)); let (tx, rx) = channel::(); - let (worker, ctx) = (shared.clone(), ctx.clone()); - let spawned = std::thread::Builder::new() - .name("db-counts".into()) - .spawn(move || { - let never = AtomicBool::new(false); - for job in rx { - let (path, known) = match job { - Job::Count(p) => (p, None), - Job::Known(p, c) => (p, Some(c)), - }; - let Some((size, modified)) = stamp(&path) else { - continue; - }; - let fresh = worker.lock().ok().and_then(|s| { - s.known - .get(&path) - .filter(|e| e.size == size && e.modified == modified) - .map(|e| e.count) - }); - let count = match known { - Some(c) if fresh == Some(c) => continue, - Some(c) => c, - None if fresh.is_some() => continue, - None => match chess_import::open(&path, &mut |_| {}, &never) { - Ok(o) => Count::of(&o.db), - // The card says why when the database is opened. - Err(_) => continue, - }, - }; - let json = match worker.lock() { - Ok(mut s) => { - s.known.insert( - path, - Entry { - size, - modified, - count, - }, - ); - serde_json::to_vec(&s.known).ok() - } - Err(_) => return, - }; - if let (Some(f), Some(json)) = (&file, json) { - if let Some(dir) = f.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = crate::settings::write_atomic(f, &json); - } - ctx.request_repaint(); - } - }); + let counter = Counter { + known: known.clone(), + file, + ctx: ctx.clone(), + }; Self { - shared, + known, asked: HashSet::new(), - jobs: spawned.ok().map(|_| tx), + jobs: counter.start(rx).then_some(tx), + } + } + + fn send(&self, job: Job) { + if let Some(jobs) = &self.jobs { + let _ = jobs.send(job); + #[cfg(web)] + Counter::next(); } } /// The games of a database not opened yet (`None`: not counted yet); it is counted /// from now on. pub fn get(&mut self, path: &Path) -> Option { - if self.asked.insert(path.to_owned()) - && let Some(jobs) = &self.jobs - { - let _ = jobs.send(Job::Count(path.to_owned())); + if self.asked.insert(path.to_owned()) { + self.send(Job::Count(path.to_owned())); } - self.shared.lock().ok()?.known.get(path).map(|e| e.count) + self.known.lock().ok()?.get(path).map(|e| e.count) } /// A database was opened: its count is remembered for the next start. pub fn opened(&mut self, path: &Path, db: &Database) { self.asked.insert(path.to_owned()); - if let Some(jobs) = &self.jobs { - let _ = jobs.send(Job::Known(path.to_owned(), Count::of(db))); - } + self.send(Job::Known(path.to_owned(), Count::of(db))); } } /// The file's size and time (seconds since the epoch); a changed file is counted again. fn stamp(path: &Path) -> Option<(u64, u64)> { - let m = std::fs::metadata(path).ok()?; - let modified = m - .modified() - .ok()? - .duration_since(UNIX_EPOCH) - .ok()? - .as_secs(); - Some((m.len(), modified)) + let m = crate::platform::fs::meta(path).ok()?; + Some((m.len, m.modified_ms / 1000)) } #[cfg(test)] mod tests { use super::*; - use std::time::{Duration, Instant}; + use std::time::Duration; + use web_time::Instant; fn wait(counts: &mut Counts, path: &Path, want: usize) -> bool { let deadline = Instant::now() + Duration::from_secs(5); @@ -201,9 +284,8 @@ mod tests { assert!(wait(&mut counts, &pgn, 2)); // An opened database tells its count; a changed file is counted anew. std::fs::write(&pgn, "[White \"A\"]\n\n1. e4 *\n").unwrap(); - let db = chess_import::open(&pgn, &mut |_| {}, &AtomicBool::new(false)) - .unwrap() - .db; + let never = std::sync::atomic::AtomicBool::new(false); + let db = chess_import::open(&pgn, &mut |_| {}, &never).unwrap().db; counts.opened(&pgn, &db); assert!(wait(&mut counts, &pgn, 1)); assert!(!counts.get(&pgn).unwrap().locked); diff --git a/apps/desktop/src/engine_download.rs b/apps/desktop/src/engine_download.rs index f0130a2..45dc123 100644 --- a/apps/desktop/src/engine_download.rs +++ b/apps/desktop/src/engine_download.rs @@ -66,11 +66,14 @@ fn asset() -> Option { /// 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)) } @@ -99,13 +102,40 @@ pub fn clean_leftovers() { } /// The downloaded engine, if it is there. -pub fn installed() -> Option { - let p = dir()?.join(EXE); - p.is_file().then_some(p) +pub fn installed() -> Option { + #[cfg(web)] + return crate::platform::web::engine::worker_script() + .map(crate::engines::EngineLocation::Worker); + #[cfg(not(web))] + { + let p = dir()?.join(EXE); + p.is_file() + .then_some(crate::engines::EngineLocation::Program(p)) + } +} + +/// The size of the downloaded engine, in MB (0 when it is not there). +pub fn installed_mb() -> u64 { + #[cfg(web)] + return if crate::platform::web::engine::ready() { + crate::platform::web::engine::WASM_BYTES / 1_000_000 + } else { + 0 + }; + #[cfg(not(web))] + dir() + .and_then(|d| std::fs::metadata(d.join(EXE)).ok()) + .map_or(0, |m| m.len() / 1_000_000) } /// 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(()), @@ -148,11 +178,54 @@ pub struct Download { } impl Download { + #[cfg(not(web))] pub fn start(ctx: &egui::Context) -> Download { let total = asset().map_or(0, |a| a.size); Download::spawn(ctx, total, run) } + /// 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 { + 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 + { + // The engine's file: its worker's script. + Ok(()) => Stage::Done(PathBuf::from(engine::SCRIPT)), + 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 (Rodent and the like in a browser). + #[cfg(web)] + pub fn unsupported() -> Download { + Download { + stage: Arc::new(Mutex::new(Stage::Failed(Failure::Unsupported))), + cancel: Arc::new(AtomicBool::new(false)), + } + } + /// Runs `job` (a download and what follows it) in a thread of its own; `total`: the /// bytes expected, shown until the server says. pub fn spawn(ctx: &egui::Context, total: u64, job: Job) -> Download { @@ -205,6 +278,7 @@ impl Drop for Download { } } +#[cfg(not(web))] fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let asset = asset().ok_or(Failure::Unsupported)?; let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; @@ -228,6 +302,7 @@ fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result result } +#[cfg(not(web))] /// Downloads `url` into `to`, checking the size and the SHA-256 on the way. The file is /// written beside and put in place once checked: a new file, never the old one rewritten /// (macOS on Apple silicon kills an executable rewritten in place after it once ran: it @@ -250,6 +325,7 @@ pub fn fetch( result } +#[cfg(not(web))] fn fetch_into( url: &str, to: &Path, @@ -328,6 +404,7 @@ pub fn already(file: &Path, asset: &Asset) -> bool { } /// Takes the engine executable and its license files out of the archive. +#[cfg(not(web))] fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result { let exe = dir.join(EXE); let wanted = |name: &str| -> Option { @@ -382,6 +459,7 @@ fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result { Ok(exe) } +#[cfg(not(web))] /// Starts the engine once and waits for its name: the binary runs on this computer. fn check_runs(exe: &Path) -> Result<(), Failure> { let mut cmd = std::process::Command::new(exe); @@ -455,7 +533,10 @@ mod tests { .output() .expect("runs"); assert!(String::from_utf8_lossy(&out.stdout).contains("Stockfish")); - assert_eq!(installed(), Some(exe)); + assert_eq!( + installed(), + Some(crate::engines::EngineLocation::Program(exe)) + ); } #[test] diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs index 663fd78..5a8ec25 100644 --- a/apps/desktop/src/engine_offer.rs +++ b/apps/desktop/src/engine_offer.rs @@ -30,6 +30,7 @@ pub enum OfferEvent { /// Use the Stockfish found on this computer, then run `Pending`. UseSystem(PathBuf, Option), /// Open the file dialog to choose an engine. + #[cfg(not(web))] ChooseFile, Toast(String), } @@ -72,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. @@ -246,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( @@ -294,7 +305,9 @@ 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() { @@ -368,6 +381,8 @@ impl EngineOffer { }); } + // In a browser nothing is pushed: there are no engine files to choose. + #[cfg_attr(web, allow(clippy::ptr_arg))] fn failure_body(&mut self, ui: &mut Ui, f: &Failure, events: &mut Vec) { ui.heading(tr("⚠ Stockfish wasn't downloaded")); ui.add_space(6.0); @@ -402,6 +417,7 @@ 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() { diff --git a/apps/desktop/src/engines.rs b/apps/desktop/src/engines.rs index 7f91a19..3e86544 100644 --- a/apps/desktop/src/engines.rs +++ b/apps/desktop/src/engines.rs @@ -27,14 +27,53 @@ pub fn bundled_stockfish() -> Option { candidates.into_iter().flatten().find(|p| is_executable(p)) } +/// Where an engine starts from: its program on a computer; in a browser, which runs no +/// programs, the address of its Web Worker's script. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EngineLocation { + #[cfg(not(web))] + Program(PathBuf), + #[cfg(web)] + Worker(String), +} + +impl EngineLocation { + /// Whether the engine is there to start (its program's file; a worker always). + pub fn present(&self) -> bool { + match self { + #[cfg(not(web))] + EngineLocation::Program(p) => p.is_file(), + #[cfg(web)] + EngineLocation::Worker(_) => true, + } + } +} + +impl std::fmt::Display for EngineLocation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + #[cfg(not(web))] + EngineLocation::Program(p) => write!(f, "{}", p.display()), + #[cfg(web)] + EngineLocation::Worker(script) => write!(f, "{script}"), + } + } +} + /// ChessPenguin's Stockfish: the bundled one, or else the downloaded one. -pub fn own_stockfish() -> Option { - bundled_stockfish().or_else(crate::engine_download::installed) +pub fn own_stockfish() -> Option { + #[cfg(not(web))] + return bundled_stockfish() + .map(EngineLocation::Program) + .or_else(crate::engine_download::installed); + #[cfg(web)] + crate::engine_download::installed() } /// `stockfish` from `PATH` (for example, the distribution package). On macOS an app /// started from the Finder does not get the shell's `PATH`: Homebrew's directories are /// looked at too. +#[cfg(not(web))] pub fn system_stockfish() -> Option { let path = std::env::var_os("PATH").unwrap_or_default(); let extra: &[&str] = if cfg!(target_os = "macos") { @@ -48,6 +87,12 @@ pub fn system_stockfish() -> Option { .find(|p| is_executable(p)) } +/// A browser has no programs of the system to find. +#[cfg(web)] +pub fn system_stockfish() -> Option { + None +} + fn is_executable(p: &Path) -> bool { let Ok(meta) = std::fs::metadata(p) else { return false; diff --git a/apps/desktop/src/examples.rs b/apps/desktop/src/examples.rs index d8bfbfc..9c4fac9 100644 --- a/apps/desktop/src/examples.rs +++ b/apps/desktop/src/examples.rs @@ -24,8 +24,7 @@ const SAMPLES: [(&str, &str); 2] = [ ]; fn dir() -> Option { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") - .map(|d| d.data_local_dir().join("examples")) + crate::platform::examples_dir() } /// A sample database of the program: only read (games added there would end up in a @@ -52,14 +51,14 @@ fn setup_in(dir: &Path, settings: &mut Settings) -> bool { // any language's name is it. for name in all_languages(key) { let path = dir.join(format!("{name}.pgn")); - let kept = path.exists() || settings.databases.contains(&path); + let kept = crate::platform::fs::exists(&path) || settings.databases.contains(&path); if (kept || (first && path == named)) && let Err(e) = bring_up_to_date(&path, text) { eprintln!("examples: cannot write {}: {e}", path.display()); } } - if first && named.exists() && !settings.databases.contains(&named) { + if first && crate::platform::fs::exists(&named) && !settings.databases.contains(&named) { settings.databases.push(named); } } @@ -69,10 +68,10 @@ fn setup_in(dir: &Path, settings: &mut Settings) -> bool { /// Writes `text` to `path` unless the file holds it already. The new file takes the old /// one's place at once (a program started meanwhile reads one or the other whole). fn bring_up_to_date(path: &Path, text: &str) -> std::io::Result<()> { - if std::fs::read(path).is_ok_and(|on_disk| on_disk == text.as_bytes()) { + if crate::platform::fs::read(path).is_ok_and(|on_disk| on_disk == text.as_bytes()) { return Ok(()); } - chess_core::pgn::store::write_atomic(path, text.as_bytes()) + crate::platform::fs::write_atomic(path, text.as_bytes()) } #[cfg(test)] diff --git a/apps/desktop/src/file_state.rs b/apps/desktop/src/file_state.rs index 38dc669..f214d98 100644 --- a/apps/desktop/src/file_state.rs +++ b/apps/desktop/src/file_state.rs @@ -2,7 +2,8 @@ //! read only) without touching the disk in the frame: a network drive that has lost its //! network (an NFS mount waits for it) would hold the whole window. A thread of its own //! looks at the files the screen asks about, again every few seconds; the screen reads -//! what it last found. A file not looked at yet counts as there. +//! what it last found. A file not looked at yet counts as there. In a browser the +//! files are the page's, in memory: they are looked at when asked. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -31,6 +32,7 @@ pub struct FileStates { const EVERY: Duration = Duration::from_secs(3); impl FileStates { + #[cfg(not(web))] pub fn new() -> Self { let shared = Arc::new(Mutex::new(Shared::default())); let looked = shared.clone(); @@ -55,7 +57,21 @@ impl FileStates { Self { shared } } + #[cfg(web)] + pub fn new() -> Self { + Self { + shared: Arc::default(), + } + } + + /// The file as it is (the page's files are in memory: no waiting). + #[cfg(web)] + pub fn get(&self, path: &Path) -> Option { + Some(look(path)) + } + /// The file as last found (`None`: not looked at yet); it is looked at from now on. + #[cfg(not(web))] pub fn get(&self, path: &Path) -> Option { let mut s = self.shared.lock().ok()?; if !s.asked.contains(path) { @@ -71,11 +87,11 @@ impl FileStates { } fn look(path: &Path) -> State { - match std::fs::metadata(path) { + match crate::platform::fs::meta(path) { Ok(m) => State { exists: true, - size: m.len(), - readonly: m.permissions().readonly(), + size: m.len, + readonly: m.readonly, }, Err(_) => State { exists: false, @@ -100,8 +116,8 @@ mod tests { // Not looked at yet: counted as there, nothing waited for. assert!(states.get(&there).is_none()); assert!(states.exists(&gone)); - let deadline = std::time::Instant::now() + Duration::from_secs(5); - while states.get(&gone).is_none() && std::time::Instant::now() < deadline { + let deadline = web_time::Instant::now() + Duration::from_secs(5); + while states.get(&gone).is_none() && web_time::Instant::now() < deadline { std::thread::sleep(Duration::from_millis(20)); } assert!(!states.exists(&gone)); diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index fc68f5e..d9e04c3 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -80,13 +80,15 @@ pub struct GameView { play_start: Option, /// «The game is on» asked (leaving during a game); the clocks wait meanwhile. /// Where leaving goes, and since when the question is open. - play_leave: Option<(crate::app::CloseIntent, std::time::Instant)>, + play_leave: Option<(crate::app::CloseIntent, web_time::Instant)>, /// Learning an opening (this screen is the training). pub train: Option, /// A line from the clipboard that would go elsewhere than the user stands: asked. paste_pending: Option, /// Text to paste on the next frame (dev hook `CP_PASTE_LINE`). paste_request: Option, + /// The menu's «Paste a line»: the clipboard being read. + clipboard: Option, show_diagnostics: bool, engine_settings_open: bool, review: Review, @@ -170,7 +172,11 @@ pub enum GameAction { /// Back to the game this one was opened from. ReturnToPrevious, /// The window offering a newer version. + #[cfg(not(web))] OpenUpdate, + /// The game's PGN as a downloaded file (the web version saves so). + #[cfg(web)] + DownloadPgn, /// Settings → Translation. OpenTranslationSettings, } @@ -200,6 +206,7 @@ impl GameView { paste_pending: None, train: None, paste_request: None, + clipboard: None, show_diagnostics: false, engine_settings_open: false, review, @@ -226,6 +233,11 @@ impl GameView { self.translation.suspend(); } + /// The whole-game analysis is running. + pub fn review_running(&self) -> bool { + self.review.running() + } + /// Copying the PGN always copies the original comments; say so when the translation is shown. fn copy_pgn(&self) -> GameAction { let note = if self.translation.shown().is_some() { @@ -796,6 +808,10 @@ impl GameView { } // A line from the clipboard: pasted, or asked about. + if let Some(text) = self.clipboard.as_ref().and_then(|r| r.poll()) { + self.clipboard = None; + self.paste_request = Some(text.unwrap_or_default()); + } if let Some(text) = self.paste_request.take() { self.paste_text(&text, &mut actions); } @@ -958,15 +974,31 @@ impl GameView { let right = |compact: bool| { button(ui, if compact { "⚙" } else { tr("⚙ Settings") }) + self.update.as_deref().map_or(0.0, |v| button(ui, v)) - + button(ui, "⏷") - + button( - ui, - if compact { - "🔍" - } else { - tr("🔍 Find in database") - }, - ) + + if cfg!(web) { + button( + ui, + if compact { + "⇩" + } else { + tr("⇩ Download PGN") + }, + ) + } else { + 0.0 + } + + if crate::platform::CAPS.reference { + button(ui, "⏷") + + button( + ui, + if compact { + "🔍" + } else { + 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», «∞») @@ -1085,17 +1117,28 @@ impl GameView { { actions.push(GameAction::OpenSettings); } + #[cfg(not(web))] if let Some(v) = &self.update && crate::widgets::update_button(ui, v).clicked() { actions.push(GameAction::OpenUpdate); } + #[cfg(web)] + if ui + .button(if compact { "⇩" } else { tr("⇩ Download PGN") }) + .on_hover_text(tr( + "Download the game as a PGN file: the browser puts it where it puts downloads", + )) + .clicked() + { + actions.push(GameAction::DownloadPgn); + } // Find the position in a database: the last chosen one, or another. let searchable = self.search_line().is_some(); 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 @@ -1411,8 +1454,10 @@ impl GameView { egui::CentralPanel::default().show(ui, |ui| { ui.horizontal(|ui| { ui.selectable_value(&mut self.side_tab, SideTab::Notation, tr("Notation")); - 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 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")); } @@ -1467,7 +1512,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) } @@ -1538,7 +1588,7 @@ impl GameView { }); } if let Some((_, NotationCommand::Paste)) = resp.context { - self.paste_clipboard(actions); + self.paste_clipboard(ui.ctx()); } else if let Some((id, NotationCommand::PlayFrom)) = resp.context { self.play_from(id, actions); } else if let Some((id, NotationCommand::Train)) = resp.context { @@ -1925,7 +1975,9 @@ impl GameView { actions.push(GameAction::Save); ui.close(); } - if ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() { + if crate::platform::CAPS.own_databases + && ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() + { actions.push(GameAction::AddToDatabase); ui.close(); } @@ -1934,6 +1986,11 @@ impl GameView { actions.push(self.copy_pgn()); ui.close(); } + #[cfg(web)] + if ui.button(tr("⇩ Download PGN")).clicked() { + actions.push(GameAction::DownloadPgn); + ui.close(); + } if ui.button(tr("Copy FEN")).clicked() { if let Some(fen) = self.game.fen(self.cursor) { actions.push(GameAction::CopyText(fen, tr("FEN copied"))); @@ -1945,10 +2002,10 @@ impl GameView { .button(tr("Paste a line from the clipboard (Ctrl+V)")) .clicked() { - self.paste_clipboard(actions); + self.paste_clipboard(ui.ctx()); ui.close(); } - if self.play.is_none() { + if self.play.is_none() && crate::platform::CAPS.play { ui.separator(); if ui.button(tr("Play on from here… (Ctrl+G)")).clicked() { let at = self.cursor; @@ -1978,7 +2035,9 @@ impl GameView { ui.close(); } ui.separator(); - if self.translation.can_translate() && ui.button(tr("Translate comments")).clicked() + if crate::platform::CAPS.translation + && self.translation.can_translate() + && ui.button(tr("Translate comments")).clicked() { self.translate_now = true; self.side_tab = SideTab::Notation; @@ -2111,7 +2170,9 @@ impl GameView { } pub fn show_reference_tab(&mut self) { - self.side_tab = SideTab::Reference; + if crate::platform::CAPS.reference { + self.side_tab = SideTab::Reference; + } } pub fn search_line(&self) -> Option<(Chess, Vec, bool)> { @@ -2153,7 +2214,7 @@ impl GameView { &mut self, start: crate::play::Start, (engine, file): (crate::play::Engine, std::path::PathBuf), - judge: Option, + judge: Option, record: Option, ctx: &egui::Context, ) { @@ -2263,7 +2324,7 @@ impl GameView { saved: &crate::play::Saved, to_move_left: Option, engine: (crate::play::Engine, std::path::PathBuf), - judge: Option, + judge: Option, journal: crate::player_games::Journal, ctx: &egui::Context, ) { @@ -2286,7 +2347,7 @@ impl GameView { let left = crate::play::times_left(&self.game, saved.floor, to_move_left); let clock = start .clock - .map(|tc| Clock::resumed(tc, left, to_move, std::time::Instant::now())); + .map(|tc| Clock::resumed(tc, left, to_move, web_time::Instant::now())); self.goto(end); self.begin_play(start, engine, judge, Some(journal), clock, floor, ctx); } @@ -2306,7 +2367,7 @@ impl GameView { &mut self, start: crate::play::Start, (engine, file): (crate::play::Engine, std::path::PathBuf), - judge: Option, + judge: Option, journal: Option, clock: Option, floor: NodeId, @@ -2320,7 +2381,7 @@ impl GameView { // it was heard before. let low_time_heard = clock .as_ref() - .is_some_and(|c| c.left(start.user, std::time::Instant::now()) <= c.low()); + .is_some_and(|c| c.left(start.user, web_time::Instant::now()) <= c.low()); self.play = Some(Session { journal, user: start.user, @@ -2331,20 +2392,18 @@ impl GameView { clock, opponent: match engine { crate::play::Engine::Maia(_) => Opponent::start(file, ctx), + #[cfg(not(web))] crate::play::Engine::Rodent(_) => { Opponent::start_rodent(file, start.style.clone(), Some(start.strength), ctx) } + #[cfg(web)] + crate::play::Engine::Rodent(_) => { + Opponent::not_started(tr("a browser cannot start it").to_owned()) + } }, resign_asked: false, low_time_heard, - judge: judge.map(|p| { - let ctx = ctx.clone(); - crate::play::Judge::start( - uci::EngineConfig::new(p), - Vec::new(), - Box::new(move || ctx.request_repaint()), - ) - }), + judge: judge.and_then(|p| crate::play::start_judge(p, ctx)), hopeless: 0, resign_offer: None, play_on: false, @@ -2514,7 +2573,7 @@ impl GameView { } return; } - let now = std::time::Instant::now(); + let now = web_time::Instant::now(); let clock = s .clock .as_ref() @@ -2551,7 +2610,7 @@ impl GameView { let Ok(id) = self.game.add_move(end, m) else { return; }; - let now = std::time::Instant::now(); + let now = web_time::Instant::now(); if let Some(s) = self.play.as_mut() { s.resign_asked = false; if let Some(c) = s.clock.as_mut() { @@ -2631,7 +2690,7 @@ impl GameView { && s.opponent.thinking { s.opponent.forget(); - s.resign_offer = Some(std::time::Instant::now()); + s.resign_offer = Some(web_time::Instant::now()); self.scroll_to_cursor = true; actions.push(GameAction::Sound(Sound::Defeat)); return; @@ -2671,7 +2730,7 @@ impl GameView { self.play_add(m, None, actions); } } - let now = std::time::Instant::now(); + let now = web_time::Instant::now(); let end_pos = self.game.position(self.play_end_node()).cloned(); let Some(s) = self.play.as_mut() else { return }; if let Some(c) = &s.clock @@ -2703,7 +2762,7 @@ impl GameView { }; s.opponent.forget(); self.board.clear_premove(); - let now = std::time::Instant::now(); + let now = web_time::Instant::now(); let left = s.clock.as_mut().map(|c| { c.stop(now); (c.left(s.user, now), c.left(!s.user, now)) @@ -2805,7 +2864,7 @@ impl GameView { let left = s .clock .as_ref() - .map(|c| c.left(to_move, std::time::Instant::now())); + .map(|c| c.left(to_move, web_time::Instant::now())); let aside = s .journal .take() @@ -3006,7 +3065,7 @@ impl GameView { self.goto(parent); let moved = self.user_moved(user); if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) { - c.take_back(user, moved, std::time::Instant::now()); + c.take_back(user, moved, web_time::Instant::now()); } } self.keep_journal(); @@ -3108,7 +3167,7 @@ impl GameView { pub fn ask_leave(&mut self, intent: crate::app::CloseIntent) { self.board.clear_premove(); if self.play_leave.is_none() { - self.play_leave = Some((intent, std::time::Instant::now())); + self.play_leave = Some((intent, web_time::Instant::now())); } } @@ -3326,7 +3385,7 @@ impl GameView { .into_iter() .chain(s.resign_offer) .min() - .unwrap_or_else(std::time::Instant::now); + .unwrap_or_else(web_time::Instant::now); let turn = self.play_turn(); let active = turn == side; let left = s.clock.as_ref().map(|c| c.left(side, now)); @@ -3821,7 +3880,7 @@ impl GameView { if let Some(t) = self.train.as_mut() && let Some(f) = &t.flash { - let now = std::time::Instant::now(); + let now = web_time::Instant::now(); if now >= f.until { t.flash = None; } else { @@ -3870,7 +3929,7 @@ impl GameView { after, from: m.from().unwrap_or(m.to()), to: crate::board::ui_target(&m), - until: std::time::Instant::now() + crate::train::WRONG_SHOWN, + until: web_time::Instant::now() + crate::train::WRONG_SHOWN, }); actions.push(GameAction::Sound(Sound::Wrong)); } @@ -4404,12 +4463,10 @@ impl GameView { // ----- a line from the clipboard (docs/design/paste-variation.md) ---------------- - /// The menu's «Paste a line from the clipboard»: the clipboard read now. - fn paste_clipboard(&mut self, actions: &mut Vec) { - let text = arboard::Clipboard::new() - .and_then(|mut c| c.get_text()) - .unwrap_or_default(); - self.paste_text(&text, actions); + /// The menu's «Paste a line from the clipboard»: the clipboard is read, the line + /// pasted once it is there (at once on a computer). + fn paste_clipboard(&mut self, ctx: &egui::Context) { + self.clipboard = Some(crate::platform::clipboard::read_text(ctx)); } /// Pastes `text` as a line: at once where the user stands, a question when it @@ -4721,6 +4778,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"); } @@ -4744,7 +4811,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); } } @@ -4797,14 +4866,16 @@ impl GameView { } "copy" => actions.push(self.copy_pgn()), "save" => actions.push(GameAction::Save), - "play_from" => { + "play_from" if crate::platform::CAPS.play => { let at = self.cursor; self.play_from(at, actions); } - "add_to_db" => actions.push(GameAction::AddToDatabase), + "add_to_db" if crate::platform::CAPS.own_databases => { + actions.push(GameAction::AddToDatabase) + } "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(), @@ -4829,7 +4900,7 @@ impl GameView { self.goto(end); } "flip" => self.flipped = !self.flipped, - "translate" => { + "translate" if crate::platform::CAPS.translation => { if self.translation.has_translation() { self.translation.toggle(); } else if self.translation.can_translate() { @@ -5001,13 +5072,20 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec format!("{} / {cores}", idx + 1), _ => format_mb(hash_steps[idx]), }; + // In a browser threads and memory are the platform's: one thread (the + // single-threaded engine), its memory (design §1.5). + let shown = if crate::platform::CAPS.engine_programs { + 4 + } else { + 2 + }; if slider >= 100.0 { ui.spacing_mut().slider_width = slider; egui::Grid::new("engine_settings_grid") .num_columns(3) .spacing(vec2(gap, 8.0)) .show(ui, |ui| { - for (i, (name, idx, len)) in rows.iter_mut().enumerate() { + for (i, (name, idx, len)) in rows.iter_mut().enumerate().take(shown) { ui.label(*name); settled |= index_slider(ui, idx, *len); ui.label(value(i, **idx)); @@ -5016,7 +5094,7 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec WgpuConfiguration { /// and to stderr: a window that stops drawing says why there. One message repeated (a /// dropped frame each frame) is written once a minute with how many times it came. struct LibraryLog { - last: std::sync::Mutex>, + last: std::sync::Mutex>, /// `CP_LOG_FRAMES=1`: also how each frame reaches the screen (egui_wgpu's debug and /// trace messages: a frame skipped as "occluded" is said only there). frames: bool, @@ -194,7 +194,7 @@ impl log::Log for LibraryLog { } eprintln!("{text}"); log(&text); - *last = Some((text, std::time::Instant::now(), 0)); + *last = Some((text, web_time::Instant::now(), 0)); } fn flush(&self) {} @@ -227,8 +227,8 @@ pub fn log(line: &str) { if std::fs::metadata(&f).is_ok_and(|m| m.len() > 1 << 20) { let _ = std::fs::remove_file(&f); } - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) + let now = web_time::SystemTime::now() + .duration_since(web_time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 3d8a66d..cdc4802 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -61,29 +61,31 @@ impl Lang { pub fn from_locales>(locales: impl IntoIterator) -> Lang { locales .into_iter() - .find_map(|l| { - // "ru-RU", "ru_RU.UTF-8", "de-CH", "es-419", "fr". - let code = l - .as_ref() - .split(['-', '_', '.', '@']) - .next()? - .to_ascii_lowercase(); - match code.as_str() { - "en" => Some(Lang::En), - "ru" => Some(Lang::Ru), - "fr" => Some(Lang::Fr), - "de" => Some(Lang::De), - "es" => Some(Lang::Es), - "it" => Some(Lang::It), - "pt" => Some(Lang::Pt), - "uz" => Some(Lang::Uz), - "kk" => Some(Lang::Kk), - _ => None, - } - }) + .find_map(|l| Lang::from_locale(l.as_ref())) .unwrap_or_default() } + /// The language of a locale ("ru-RU", "ru_RU.UTF-8", "de-CH", "es-419", "fr"), if + /// it is one of ours. + pub fn from_locale(locale: &str) -> Option { + let code = locale + .split(['-', '_', '.', '@']) + .next()? + .to_ascii_lowercase(); + match code.as_str() { + "en" => Some(Lang::En), + "ru" => Some(Lang::Ru), + "fr" => Some(Lang::Fr), + "de" => Some(Lang::De), + "es" => Some(Lang::Es), + "it" => Some(Lang::It), + "pt" => Some(Lang::Pt), + "uz" => Some(Lang::Uz), + "kk" => Some(Lang::Kk), + _ => None, + } + } + /// The language of this system (see [`Lang::from_locales`]). pub fn system() -> Lang { Lang::from_locales(sys_locale::get_locales()) @@ -214,6 +216,425 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String { // [English, Русский, Français, Deutsch, Español, Italiano, Português (BR), O‘zbekcha, Қазақша] // Uzbek o‘ and g‘ are written with ‘ (U+2018): the interface font has no U+02BB. const ROWS: &[[&str; 9]] = &[ + // --- the web version --- + [ + "This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.", + "База слишком большая для браузера ({size}, предел {limit}). Извините — откройте её в программе для компьютера.", + "Cette base est trop grande pour le navigateur ({size}, la limite est de {limit}). Désolé — ouvrez-la dans le programme pour ordinateur.", + "Diese Datenbank ist zu groß für den Browser ({size}, die Grenze liegt bei {limit}). Entschuldigung – öffnen Sie sie im Programm für den Computer.", + "Esta base es demasiado grande para el navegador ({size}, el límite es {limit}). Lo sentimos: ábrela en el programa para ordenador.", + "Questo database è troppo grande per il browser ({size}, il limite è {limit}). Ci dispiace: aprilo nel programma per computer.", + "Esta base é grande demais para o navegador ({size}, o limite é {limit}). Desculpe — abra no programa para computador.", + "Bu baza brauzer uchun juda katta ({size}, chegara {limit}). Kechirasiz — uni kompyuter dasturida oching.", + "Бұл база браузер үшін тым үлкен ({size}, шегі {limit}). Кешіріңіз — оны компьютерге арналған бағдарламада ашыңыз.", + ], + [ + "Download ChessPenguin for the computer", + "Скачать ChessPenguin для компьютера", + "Télécharger ChessPenguin pour ordinateur", + "ChessPenguin für den Computer herunterladen", + "Descargar ChessPenguin para ordenador", + "Scarica ChessPenguin per computer", + "Baixar o ChessPenguin para computador", + "ChessPenguin’ni kompyuter uchun yuklab olish", + "ChessPenguin-ді компьютерге жүктеп алу", + ], + [ + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + "База ChessBase состоит из нескольких файлов (.cbh, .cbg, .cba…). Выберите её папку или сразу все её файлы.", + "Une base ChessBase se compose de plusieurs fichiers (.cbh, .cbg, .cba…). Choisissez son dossier ou tous ses fichiers à la fois.", + "Eine ChessBase-Datenbank besteht aus mehreren Dateien (.cbh, .cbg, .cba…). Wählen Sie ihren Ordner oder alle ihre Dateien auf einmal.", + "Una base de ChessBase consta de varios archivos (.cbh, .cbg, .cba…). Elige su carpeta o todos sus archivos a la vez.", + "Un database ChessBase è composto da più file (.cbh, .cbg, .cba…). Scegli la sua cartella o tutti i suoi file insieme.", + "Uma base do ChessBase é formada por vários arquivos (.cbh, .cbg, .cba…). Escolha a pasta dela ou todos os arquivos de uma vez.", + "ChessBase bazasi bir nechta fayldan iborat (.cbh, .cbg, .cba…). Uning papkasini yoki barcha fayllarini birdaniga tanlang.", + "ChessBase базасы бірнеше файлдан тұрады (.cbh, .cbg, .cba…). Оның қалтасын немесе барлық файлдарын бірден таңдаңыз.", + ], + [ + "Allow access to the database's folder — its other files will be found by themselves.", + "Разрешите доступ к папке базы — остальные файлы базы найдутся сами.", + "Autorisez l'accès au dossier de la base — ses autres fichiers seront trouvés automatiquement.", + "Erlauben Sie den Zugriff auf den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.", + "Permite el acceso a la carpeta de la base: sus demás archivos se encontrarán solos.", + "Consenti l'accesso alla cartella del database: gli altri suoi file verranno trovati da soli.", + "Permita o acesso à pasta da base — os outros arquivos dela serão encontrados sozinhos.", + "Baza papkasiga ruxsat bering — uning qolgan fayllari o‘zi topiladi.", + "База қалтасына рұқсат беріңіз — оның қалған файлдары өздігінен табылады.", + ], + [ + "Choose the database's folder — its other files will be found by themselves.", + "Выберите папку базы — остальные файлы базы найдутся сами.", + "Choisissez le dossier de la base — ses autres fichiers seront trouvés automatiquement.", + "Wählen Sie den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.", + "Elige la carpeta de la base: sus demás archivos se encontrarán solos.", + "Scegli la cartella del database: gli altri suoi file verranno trovati da soli.", + "Escolha a pasta da base — os outros arquivos dela serão encontrados sozinhos.", + "Baza papkasini tanlang — uning qolgan fayllari o‘zi topiladi.", + "База қалтасын таңдаңыз — оның қалған файлдары өздігінен табылады.", + ], + [ + "📁 Choose the database's folder", + "📁 Выбрать папку базы", + "📁 Choisir le dossier de la base", + "📁 Ordner der Datenbank wählen", + "📁 Elegir la carpeta de la base", + "📁 Scegli la cartella del database", + "📁 Escolher a pasta da base", + "📁 Baza papkasini tanlash", + "📁 База қалтасын таңдау", + ], + [ + "Choose the database's files", + "Выбрать файлы базы", + "Choisir les fichiers de la base", + "Dateien der Datenbank wählen", + "Elegir los archivos de la base", + "Scegli i file del database", + "Escolher os arquivos da base", + "Baza fayllarini tanlash", + "База файлдарын таңдау", + ], + [ + "There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z).", + "В этой папке нет базы (.pgn, .cbh, .cbv, .zip, .7z).", + "Ce dossier ne contient aucune base (.pgn, .cbh, .cbv, .zip, .7z).", + "In diesem Ordner gibt es keine Datenbank (.pgn, .cbh, .cbv, .zip, .7z).", + "En esta carpeta no hay ninguna base (.pgn, .cbh, .cbv, .zip, .7z).", + "In questa cartella non c'è nessun database (.pgn, .cbh, .cbv, .zip, .7z).", + "Não há nenhuma base nesta pasta (.pgn, .cbh, .cbv, .zip, .7z).", + "Bu papkada baza yo‘q (.pgn, .cbh, .cbv, .zip, .7z).", + "Бұл қалтада база жоқ (.pgn, .cbh, .cbv, .zip, .7z).", + ], + [ + "The browser doesn't have enough memory for this database. Open it in the desktop program.", + "Браузеру не хватает памяти для этой базы. Откройте её в программе для компьютера.", + "Le navigateur n'a pas assez de mémoire pour cette base. Ouvrez-la dans le programme pour ordinateur.", + "Dem Browser fehlt der Speicher für diese Datenbank. Öffnen Sie sie im Programm für den Computer.", + "Al navegador le falta memoria para esta base. Ábrela en el programa para ordenador.", + "Al browser manca la memoria per questo database. Aprilo nel programma per computer.", + "O navegador não tem memória suficiente para esta base. Abra no programa para computador.", + "Brauzerda bu baza uchun xotira yetmaydi. Uni kompyuter dasturida oching.", + "Браузерге бұл база үшін жад жетпейді. Оны компьютерге арналған бағдарламада ашыңыз.", + ], + [ + "A dropped file is not remembered: after a reload, choose the file again or keep a copy in the browser.", + "Перетащенный файл не запоминается: после перезагрузки выберите его снова или сохраните копию в браузере.", + "Un fichier déposé n'est pas mémorisé : après un rechargement, choisissez-le à nouveau ou gardez-en une copie dans le navigateur.", + "Eine hineingezogene Datei wird nicht gemerkt: Wählen Sie sie nach dem Neuladen erneut oder behalten Sie eine Kopie im Browser.", + "Un archivo arrastrado no se recuerda: tras recargar, elíjalo de nuevo o guarde una copia en el navegador.", + "Un file trascinato non viene ricordato: dopo il ricaricamento sceglilo di nuovo o conserva una copia nel browser.", + "Um arquivo arrastado não é lembrado: após recarregar, escolha-o novamente ou guarde uma cópia no navegador.", + "Sudrab tashlangan fayl eslab qolinmaydi: qayta yuklangandan keyin uni yana tanlang yoki brauzerda nusxasini saqlang.", + "Сүйреп әкелінген файл есте сақталмайды: қайта жүктегеннен кейін оны қайта таңдаңыз немесе браузерде көшірмесін сақтаңыз.", + ], + [ + "🔒 Allow reading", + "🔒 Разрешить чтение", + "🔒 Autoriser la lecture", + "🔒 Lesen erlauben", + "🔒 Permitir lectura", + "🔒 Consenti la lettura", + "🔒 Permitir leitura", + "🔒 O‘qishga ruxsat berish", + "🔒 Оқуға рұқсат беру", + ], + [ + "The browser remembers this file and asks before the page reads it again.", + "Браузер помнит этот файл и спрашивает, прежде чем страница прочитает его снова.", + "Le navigateur se souvient de ce fichier et demande avant que la page le relise.", + "Der Browser merkt sich diese Datei und fragt, bevor die Seite sie erneut liest.", + "El navegador recuerda este archivo y pregunta antes de que la página vuelva a leerlo.", + "Il browser ricorda questo file e chiede prima che la pagina lo rilegga.", + "O navegador lembra este arquivo e pergunta antes que a página o leia novamente.", + "Brauzer bu faylni eslab qoladi va sahifa uni qayta o‘qishidan oldin so‘raydi.", + "Браузер бұл файлды есте сақтайды және бет оны қайта оқымас бұрын сұрайды.", + ], + [ + "There is an unsaved game: {title}, moves: {n}.", + "Есть несохранённая партия: {title}, ходов: {n}.", + "Il y a une partie non enregistrée : {title}, coups : {n}.", + "Es gibt eine nicht gespeicherte Partie: {title}, Züge: {n}.", + "Hay una partida sin guardar: {title}, jugadas: {n}.", + "C'è una partita non salvata: {title}, mosse: {n}.", + "Há uma partida não salva: {title}, lances: {n}.", + "Saqlanmagan partiya bor: {title}, yurishlar: {n}.", + "Сақталмаған партия бар: {title}, жүрістер: {n}.", + ], + [ + "📋 Keep a copy in the browser", + "📋 Оставить копию в браузере", + "📋 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} береді. «Браузердегі деректер» бөлімінде орын босатыңыз немесе файлды дисктен ашыңыз.", + ], + [ + "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", + "Отпустите, чтобы открыть", + "Relâchez pour ouvrir", + "Zum Öffnen loslassen", + "Suelta para abrir", + "Rilascia per aprire", + "Solte para abrir", + "Ochish uchun qo‘yib yuboring", + "Ашу үшін жіберіңіз", + ], + [ + "⇩ Download PGN", + "⇩ Скачать PGN", + "⇩ Télécharger le PGN", + "⇩ PGN herunterladen", + "⇩ Descargar PGN", + "⇩ Scarica PGN", + "⇩ Baixar PGN", + "⇩ PGN yuklab olish", + "⇩ PGN жүктеп алу", + ], + [ + "Download the game as a PGN file: the browser puts it where it puts downloads", + "Скачать партию файлом PGN: браузер положит его туда же, куда все загрузки", + "Télécharger la partie en fichier PGN : le navigateur le met avec les autres téléchargements", + "Die Partie als PGN-Datei herunterladen: Der Browser legt sie zu den anderen Downloads", + "Descargar la partida como archivo PGN: el navegador lo guarda con las demás descargas", + "Scarica la partita come file PGN: il browser lo mette insieme agli altri download", + "Baixar a partida como arquivo PGN: o navegador o coloca junto dos outros downloads", + "Partiyani PGN fayl sifatida yuklab olish: brauzer uni boshqa yuklamalar qatoriga qo‘yadi", + "Партияны PGN файлы ретінде жүктеп алу: браузер оны басқа жүктемелермен бірге сақтайды", + ], + [ + "The PGN could not be downloaded: {e}", + "Не удалось скачать PGN: {e}", + "Impossible de télécharger le PGN : {e}", + "PGN konnte nicht heruntergeladen werden: {e}", + "No se pudo descargar el PGN: {e}", + "Impossibile scaricare il PGN: {e}", + "Não foi possível baixar o PGN: {e}", + "PGN yuklab olinmadi: {e}", + "PGN жүктеп алынбады: {e}", + ], + [ + "a browser cannot start it", + "браузер не может его запустить", + "un navigateur ne peut pas le lancer", + "ein Browser kann ihn nicht starten", + "un navegador no puede iniciarlo", + "un browser non può avviarlo", + "um navegador não consegue iniciá-lo", + "brauzer uni ishga tushira olmaydi", + "браузер оны іске қоса алмайды", + ], // --- engine download --- [ "Stockfish installed — game analysis started", diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 94953be..0be27f7 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -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, + /// 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) { @@ -1695,7 +1701,7 @@ impl LargeView { .weak(), ); ui.add_space(6.0); - ui.label(RichText::new(trf("File: {path}", &[("path", &path.display())])).weak()); + ui.label(RichText::new(trf("File: {path}", &[("path", &crate::platform::files::shown(path))])).weak()); }); return open_notes; } @@ -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 { @@ -1846,6 +1860,7 @@ impl LargeView { .on_disabled_hover_text(&online.hint) .clicked() { + #[cfg(not(web))] actions.push(LibraryAction::UpdateOnline(path.to_path_buf())); } } @@ -1912,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. diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs new file mode 100644 index 0000000..978557f --- /dev/null +++ b/apps/desktop/src/lib.rs @@ -0,0 +1,176 @@ +//! ChessPenguin's window: the library, the game, analysis, play, preparation. +//! +//! One interface for two platforms. The desktop program (`src/main.rs`) starts it in a +//! native window ([`run_native`]); the web version (`apps/web`) in a page's canvas +//! ([`start_web`]). What differs between them — files, background work, storage, +//! dialogs, the clipboard — is behind [`platform`]. Features a platform does not have +//! are not built for it (`cfg(web)`: WebAssembly in a browser, set by `build.rs`), or, +//! where the interface only needs to know, hidden by [`platform::CAPS`]. The web build +//! compiles parts of the interface it never shows: what is unused there is the desktop +//! build's to find (the platform layer, [`platform`], is checked in both). +// (A browser's `std::fs::File` has no destructor: dropping one there is no closing.) +#![cfg_attr(web, allow(unused, clippy::drop_non_drop))] + +mod adjourned; +mod analysis; +mod app; +mod assets; +mod board; +mod board_search; +mod chatgpt; +mod db_counts; +mod engine_download; +mod engine_offer; +mod engines; +mod examples; +mod file_state; +mod game_view; +#[cfg(not(web))] +mod graphics; +mod i18n; +mod large_db; +mod library; +mod maia_download; +#[cfg(web)] +mod my_games; +mod notation; +mod online; +#[cfg(not(web))] +mod online_ui; +mod own_db; +pub mod platform; +mod play; +mod player_games; +mod prep_ui; +mod reference; +mod review; +mod rodent4_download; +mod rodent_download; +mod san; +mod settings; +mod settings_ui; +mod sound; +mod translate; +mod translate_ui; +#[cfg(not(web))] +mod update; +#[cfg(not(web))] +mod update_ui; +mod viewed; +mod widgets; + +/// Learning an opening: shared with the Android app. +use trainer as train; + +/// The web version in the page's `canvas`: the program's data is read from the +/// browser's storage first, then the interface starts. `lang`: the language the page +/// was opened in (`?lang=` of the site's link), over the one chosen before. +#[cfg(web)] +pub async fn start_web( + canvas: web_sys::HtmlCanvasElement, + lang: Option, +) -> Result<(), wasm_bindgen::JsValue> { + platform::web::vfs::load().await; + platform::web::remembered::restore().await; + platform::web::engine::probe().await; + platform::web::storage::refresh(|| {}); + let mut settings = settings::Settings::load(); + if let Some(chosen) = lang.as_deref().and_then(i18n::Lang::from_locale) + && chosen != settings.language + { + settings.language = chosen; + let _ = settings.save(); + } + i18n::set_lang(settings.language); + eframe::WebRunner::new() + .start( + canvas, + eframe::WebOptions::default(), + Box::new(|cc| { + assets::install(&cc.egui_ctx); + Ok(Box::new(app::App::new(&cc.egui_ctx))) + }), + ) + .await +} + +/// The page's reader (`import-worker.js`, a worker with an instance of its own): takes +/// the files of a database one by one ([`reader_give`]), reads it and answers with its +/// text and index, or only how many games it holds (`count`; `platform::web::import`). +#[cfg(web)] +pub fn reader_give(name: String, bytes: Vec) { + platform::web::import::give(name, bytes); +} + +#[cfg(web)] +pub fn reader_read(count: bool) -> wasm_bindgen::JsValue { + platform::web::import::answer(count) +} + +/// The desktop program: `chesspenguin [--bench [report.txt]]`. +#[cfg(not(web))] +pub fn run_native() -> eframe::Result { + // `chesspenguin --bench [report.txt]`: timings instead of the window + // (`docs/dev/import.md`, "Замер на другой машине"). + let args: Vec = std::env::args_os().skip(1).collect(); + if args.first().is_some_and(|a| a == "--bench") { + let Some(db) = args.get(1) else { + eprintln!("usage: chesspenguin --bench [report.txt]"); + std::process::exit(2); + }; + let cache = settings::Settings::cache_dir().map(|d| d.join("boosters")); + let result = match args.get(2) { + Some(file) => std::fs::File::create(file) + .and_then(|mut f| chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut f)), + None => chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut std::io::stdout()), + }; + if let Err(e) = result { + eprintln!("bench: {e}"); + std::process::exit(1); + } + return Ok(()); + } + crate::i18n::set_lang(settings::Settings::load().language); + // The runs of the opening trainer (`CP_TRAINING_FILE` elsewhere: development). + if let Some(file) = std::env::var_os("CP_TRAINING_FILE") + .map(std::path::PathBuf::from) + .or_else(|| { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("training.json")) + }) + { + train::set_file(file); + } + graphics::install_panic_hook(); + graphics::init_library_log(); + let mode = graphics::choose(); + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_app_id("io.github.vrubelroman.chessPenguin") + .with_title("ChessPenguin") + .with_inner_size([1400.0, 900.0]) + .with_min_inner_size([640.0, 480.0]) + // X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id. + .with_icon( + eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png")) + .unwrap_or_default(), + ), + wgpu_options: graphics::options(mode), + ..Default::default() + }; + let result = eframe::run_native( + "ChessPenguin", + options, + Box::new(|cc| { + assets::install(&cc.egui_ctx); + Ok(Box::new(app::App::new(&cc.egui_ctx))) + }), + ); + if let Err(e) = &result { + if graphics::retry(&e.to_string()) { + return Ok(()); + } + graphics::fatal(&e.to_string()); + } + result +} diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index bd099e3..2ecc3fa 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -48,12 +48,26 @@ pub enum LibraryAction { PastePgn, AddDatabases, /// The window for downloading games from Lichess and Chess.com. + #[cfg(not(web))] OnlineGames, /// Fetch the new games of an online database. + #[cfg(not(web))] UpdateOnline(PathBuf), /// The window offering a newer version. + #[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), + /// Let the page read the remembered file again (the browser asks the user). + #[cfg(web)] + AllowReading(PathBuf), + /// Choose the folder of the ChessBase database whose `.cbh` alone is there. + #[cfg(web)] + ChooseFolderAgain(PathBuf), + /// Keep a copy of a file in the browser (it opens then without choosing it). + KeepCopy(PathBuf), OpenSettings, /// A new, empty PGN database (own-databases.md §2). NewDatabase, @@ -106,18 +120,15 @@ fn button_w(ui: &Ui, text: &str) -> f32 { /// A PGN file whose beginning is in a legacy (single-byte) encoding: it takes games only /// through a UTF-8 copy. For a file not read yet (its card's menu). fn legacy_pgn(path: &Path) -> bool { - use std::io::Read; let pgn = path .extension() .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("pgn")); if !pgn || crate::online::is_online(path) || crate::examples::is_example(path) { return false; } - let mut head = Vec::with_capacity(64 << 10); - let read = std::fs::File::open(path).and_then(|f| f.take(64 << 10).read_to_end(&mut head)); - if read.is_err() { + let Ok(head) = crate::platform::fs::read_head(path, 64 << 10) else { return false; - } + }; let guess = chess_core::detect_encoding(&head); guess.encoding != chess_core::TextEncoding::Utf8 && !guess.ascii_only } @@ -136,9 +147,14 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 { tr("♞ Play"), ] }; - texts.iter().map(|t| button_w(ui, t)).sum::() + let play = crate::platform::CAPS.play; + let groups = if play { 2.0 } else { 1.0 }; + texts[..if play { 4 } else { 3 }] + .iter() + .map(|t| button_w(ui, t)) + .sum::() + update.map_or(0.0, |v| button_w(ui, v)) - + 2.0 * GROUP_GAP + + groups * GROUP_GAP } /// A shelf button's tooltip: with icons only, its name first. @@ -257,27 +273,20 @@ impl Library { })); let cancel = Arc::new(AtomicBool::new(false)); let (tx, rx) = channel(); - let (p, c, path_owned, ctx) = ( - progress.clone(), + let (p, ctx, wake) = (progress.clone(), ctx.clone(), ctx.clone()); + let spawned = crate::platform::open_database( + path, + move |sp| { + if let Ok(mut g) = p.lock() { + *g = sp; + } + wake.request_repaint(); + }, cancel.clone(), - path.to_path_buf(), - ctx.clone(), - ); - let spawned = std::thread::Builder::new() - .name("db-open".into()) - .spawn(move || { - let res = chess_import::open( - &path_owned, - &mut |sp| { - if let Ok(mut g) = p.lock() { - *g = sp; - } - ctx.request_repaint(); - }, - &c, - ); + move |res| { // The filters' index of a PGN is built here, not on the screen's thread - // (a large download takes a second, §9.7). + // (a large download takes a second, §9.7; in a browser, which reads + // smaller files, it is the page's thread). if let Ok(opened) = &res && let Database::Pgn(pgn) = &opened.db { @@ -285,7 +294,8 @@ impl Library { } let _ = tx.send(res); ctx.request_repaint(); - }); + }, + ); let slot = match spawned { Ok(_) => Slot::Loading { progress, @@ -338,6 +348,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); } @@ -638,6 +652,7 @@ impl Library { if let Some(path) = self.selected_db.clone() && let Some(view) = self.large.get_mut(&path) && let Some(entry) = view.prepare.take() + && crate::platform::CAPS.prep { actions.push(LibraryAction::PrepareAgainst { path, entry }); } @@ -759,6 +774,7 @@ impl Library { { actions.push(LibraryAction::OpenSettings); } + #[cfg(not(web))] if let Some(v) = &self.update && crate::widgets::update_button(ui, v).clicked() { @@ -772,8 +788,10 @@ impl Library { self.shelf_actions(ui, folded, actions); ui.separator(); self.game_buttons(ui, icons, actions); - ui.separator(); - self.play_button(ui, icons, actions); + if crate::platform::CAPS.play { + ui.separator(); + self.play_button(ui, icons, actions); + } } /// "♞ Play": a game against Maia, a group of its own. @@ -934,10 +952,11 @@ impl Library { actions.push(LibraryAction::AddDatabases); ui.close(); } - if ui - .button(tr("New database…")) - .on_hover_text(new_hint) - .clicked() + if crate::platform::CAPS.own_databases + && ui + .button(tr("New database…")) + .on_hover_text(new_hint) + .clicked() { actions.push(LibraryAction::NewDatabase); ui.close(); @@ -951,10 +970,11 @@ impl Library { { actions.push(LibraryAction::AddDatabases); } - if ui - .button(tr("✚ New database")) - .on_hover_text(new_hint) - .clicked() + if crate::platform::CAPS.own_databases + && ui + .button(tr("✚ New database")) + .on_hover_text(new_hint) + .clicked() { actions.push(LibraryAction::NewDatabase); } @@ -970,6 +990,7 @@ impl Library { None => online_hint.to_owned(), }; if ui.button(label).on_hover_text(hint).clicked() { + #[cfg(not(web))] actions.push(LibraryAction::OnlineGames); } if let Some(n) = self.online_running { @@ -1027,9 +1048,10 @@ impl Library { { actions.push(LibraryAction::AddDatabases); } - if card(ui, new_w, tr("✚ New database"), None) - .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) - .clicked() + if crate::platform::CAPS.own_databases + && card(ui, new_w, tr("✚ New database"), None) + .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) + .clicked() { actions.push(LibraryAction::NewDatabase); } @@ -1043,6 +1065,7 @@ impl Library { .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) .clicked() { + #[cfg(not(web))] actions.push(LibraryAction::OnlineGames); } }); @@ -1079,6 +1102,17 @@ impl Library { }); trf("loading… {n}", &[("n", &p.games)]) } + Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(path) => { + tr("📁 Choose the database's folder").into() + } + Some(Slot::Failed(_)) | None if crate::platform::files::waiting_to_read(path) => { + tr("🔒 Allow reading").into() + } + 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. @@ -1142,9 +1176,9 @@ impl Library { &[("name", name)], ) }; - resp.on_hover_text(format!("{whose}\n{}", path.display())) + resp.on_hover_text(format!("{whose}\n{}", crate::platform::files::shown(path))) } - None => resp.on_hover_text(path.display().to_string()), + None => resp.on_hover_text(crate::platform::files::shown(path)), }; if resp.clicked() { self.select_db(path, ui.ctx()); @@ -1240,7 +1274,10 @@ impl Library { ui.add_space(40.0); ui.label(trf( "Reading {path} — games found: {n}", - &[("path", &path.display()), ("n", &p.games)], + &[ + ("path", &crate::platform::files::shown(&path)), + ("n", &p.games), + ], )); ui.add(egui::ProgressBar::new(frac).desired_width(400.0)); if ui.button(tr("Cancel")).clicked() { @@ -1249,6 +1286,75 @@ impl Library { }); return; } + #[cfg(web)] + Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(&path) => { + // A ChessBase database's .cbh without its other files (one chosen + // alone at an earlier visit): its folder or all its files. + ui.vertical_centered(|ui| { + ui.add_space(40.0); + ui.label(tr( + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("📁 Choose the database's folder")).clicked() { + actions.push(LibraryAction::ChooseFolderAgain(path.clone())); + } + if ui.button(tr("Choose the database's files")).clicked() { + actions.push(LibraryAction::ChooseAgain(path.clone())); + } + if ui.button(tr("Remove from list")).clicked() { + actions.push(LibraryAction::RemoveDatabase(path.clone())); + } + }); + }); + return; + } + #[cfg(web)] + Some(Slot::Failed(_)) if crate::platform::files::waiting_to_read(&path) => { + // Chrome, Edge: the file is remembered; the browser asks before the + // page reads it again. + ui.vertical_centered(|ui| { + ui.add_space(40.0); + ui.label(tr( + "The browser remembers this file and asks before the page reads it again.", + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("🔒 Allow reading")).clicked() { + actions.push(LibraryAction::AllowReading(path.clone())); + } + if ui.button(tr("Remove from list")).clicked() { + actions.push(LibraryAction::RemoveDatabase(path.clone())); + } + }); + }); + return; + } + Some(Slot::Failed(_)) + if crate::platform::files::session_only(&path) && !self.files.exists(&path) => + { + // A browser keeps no way back to a file the user chose (Firefox, Safari). + ui.vertical_centered(|ui| { + ui.add_space(40.0); + // Chrome and Edge remember chosen files, not dropped ones. + ui.label(if crate::platform::files::remembers_chosen() { + tr("A dropped file is not remembered: after a reload, choose the file again or keep a copy in the browser.") + } else { + 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| { @@ -1256,7 +1362,7 @@ impl Library { ui.label( RichText::new(trf( "Could not open {path}: {e}", - &[("path", &path.display()), ("e", &e)], + &[("path", &crate::platform::files::shown(&path)), ("e", &e)], )) .color(ui.visuals().error_fg_color), ); @@ -1337,6 +1443,7 @@ impl Library { format, format_hint, online, + keep_copy: crate::platform::files::session_only(path), } } } @@ -1365,6 +1472,17 @@ fn import_error(e: &ImportError) -> String { "The ChessBase 2CBH format is not supported: export the database from ChessBase as CBH or PGN", ) .into(), + ImportError::Unsupported(Unsupported::ChessBaseFiles) => tr( + "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", + ) + .into(), + ImportError::Io { source, .. } if source.kind() == std::io::ErrorKind::OutOfMemory => tr( + "The browser doesn't have enough memory for this database. Open it in the desktop program.", + ) + .into(), + // A browser's places of files mean nothing to the user: only what happened. + #[cfg(web)] + ImportError::Io { source, .. } => source.to_string(), e => e.to_string(), } } diff --git a/apps/desktop/src/maia_download.rs b/apps/desktop/src/maia_download.rs index 390d5cf..3af1a95 100644 --- a/apps/desktop/src/maia_download.rs +++ b/apps/desktop/src/maia_download.rs @@ -102,6 +102,19 @@ pub struct Download { } impl Download { + /// A browser downloads no weights into files: there is no download for it. + #[cfg(web)] + pub fn start(_ctx: &egui::Context, model: Model) -> Download { + Download { + model, + stage: Arc::new(Mutex::new(Stage::Failed( + crate::i18n::tr("not yet for this system").to_owned(), + ))), + cancel: Arc::new(AtomicBool::new(false)), + } + } + + #[cfg(not(web))] pub fn start(ctx: &egui::Context, model: Model) -> Download { let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0 })); let cancel = Arc::new(AtomicBool::new(false)); @@ -142,6 +155,7 @@ impl Drop for Download { } } +#[cfg(not(web))] fn run(model: Model, report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let dir = dir().ok_or("no data directory")?; std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index b7a2ab1..ab8a1a2 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -1,112 +1,6 @@ // No console window for release builds on Windows. #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] -mod adjourned; -mod analysis; -mod app; -mod assets; -mod board; -mod board_search; -mod chatgpt; -mod db_counts; -mod engine_download; -mod engine_offer; -mod engines; -mod examples; -mod file_state; -mod game_view; -mod graphics; -mod i18n; -mod large_db; -mod library; -mod maia_download; -mod notation; -mod online; -mod online_ui; -mod own_db; -mod play; -mod player_games; -mod prep_ui; -mod reference; -mod review; -mod rodent4_download; -mod rodent_download; -mod san; -mod settings; -mod settings_ui; -mod sound; -mod translate; -mod translate_ui; -mod update; -mod update_ui; -mod viewed; -mod widgets; - -/// Learning an opening: shared with the Android app. -use trainer as train; - fn main() -> eframe::Result { - // `chesspenguin --bench [report.txt]`: timings instead of the window - // (`docs/dev/import.md`, "Замер на другой машине"). - let args: Vec = std::env::args_os().skip(1).collect(); - if args.first().is_some_and(|a| a == "--bench") { - let Some(db) = args.get(1) else { - eprintln!("usage: chesspenguin --bench [report.txt]"); - std::process::exit(2); - }; - let cache = settings::Settings::cache_dir().map(|d| d.join("boosters")); - let result = match args.get(2) { - Some(file) => std::fs::File::create(file) - .and_then(|mut f| chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut f)), - None => chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut std::io::stdout()), - }; - if let Err(e) = result { - eprintln!("bench: {e}"); - std::process::exit(1); - } - return Ok(()); - } - crate::i18n::set_lang(settings::Settings::load().language); - // The runs of the opening trainer (`CP_TRAINING_FILE` elsewhere: development). - if let Some(file) = std::env::var_os("CP_TRAINING_FILE") - .map(std::path::PathBuf::from) - .or_else(|| { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") - .map(|d| d.data_local_dir().join("training.json")) - }) - { - train::set_file(file); - } - graphics::install_panic_hook(); - graphics::init_library_log(); - let mode = graphics::choose(); - let options = eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_app_id("io.github.vrubelroman.chessPenguin") - .with_title("ChessPenguin") - .with_inner_size([1400.0, 900.0]) - .with_min_inner_size([640.0, 480.0]) - // X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id. - .with_icon( - eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png")) - .unwrap_or_default(), - ), - wgpu_options: graphics::options(mode), - ..Default::default() - }; - let result = eframe::run_native( - "ChessPenguin", - options, - Box::new(|cc| { - assets::install(&cc.egui_ctx); - Ok(Box::new(app::App::new(&cc.egui_ctx))) - }), - ); - if let Err(e) = &result { - if graphics::retry(&e.to_string()) { - return Ok(()); - } - graphics::fatal(&e.to_string()); - } - result + chesspenguin_app::run_native() } diff --git a/apps/desktop/src/my_games.rs b/apps/desktop/src/my_games.rs new file mode 100644 index 0000000..6d18096 --- /dev/null +++ b/apps/desktop/src/my_games.rs @@ -0,0 +1,98 @@ +//! «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/.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-.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) +} + +/// A game left unsaved when the page was closed (docs/design/web-version.md §2.6): one, +/// the last, written every few seconds while it has changes. It guards against a +/// closed tab; it is not a save: offered at the next start, opened or deleted. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +pub struct Draft { + pub title: String, + pub moves: usize, + pub pgn: String, +} + +fn draft_path() -> PathBuf { + crate::platform::data_dir() + .unwrap_or_default() + .join("draft.json") +} + +pub fn write_draft(draft: &Draft) { + if let Ok(json) = serde_json::to_vec(draft) { + let _ = crate::platform::fs::write_atomic(&draft_path(), &json); + } +} + +pub fn read_draft() -> Option { + let bytes = crate::platform::fs::read(&draft_path()).ok()?; + serde_json::from_slice(&bytes).ok() +} + +pub fn delete_draft() { + let _ = crate::platform::fs::remove_file(&draft_path()); +} diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index a45cbfe..c73ee2c 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -445,6 +445,10 @@ fn handle_move_response( out.context = Some((id, NotationCommand::Delete)); ui.close(); } + // Games against the computer and the trainer: not in every version. + if !crate::platform::CAPS.play { + return; + } ui.separator(); // A finished position has nothing to play. let over = n.game.position(id).and_then(|p| { diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs index dae2c32..fc8880e 100644 --- a/apps/desktop/src/online.rs +++ b/apps/desktop/src/online.rs @@ -1,14 +1,15 @@ //! Games from Lichess and Chess.com on the desktop: the databases live in //! `/online/`; the downloads themselves are the `online-games` crate's //! (shared with the Android app). Both public APIs are probed at start; a platform that -//! does not answer as expected (offline, the API changed) is simply not offered. +//! does not answer as expected (offline, the API changed) is simply not offered. The +//! web version has no online games: there only the names of such databases are known. use std::path::{Path, PathBuf}; -use std::time::Duration; +pub use online_games::{Account, Platform, State}; +#[cfg(not(web))] pub use online_games::{ - Account, Done, Failure, LICHESS_RATE, Lookup, Platform, Progress, State, download, lookup, - probe_all, valid_nick, + Done, Failure, LICHESS_RATE, Lookup, Progress, download, lookup, probe_all, valid_nick, }; /// Where the online databases live. @@ -43,18 +44,20 @@ pub fn ago(t: i64) -> String { } } +#[cfg(not(web))] /// The probe results and what the window shows, kept by the application. pub struct Probe { job: Option>, pub available: [bool; 2], /// When the last probe finished (a platform that did not answer is asked again /// after [`Probe::RETRY`]: the machine may have come online). - last: Option, + last: Option, ctx: egui::Context, } +#[cfg(not(web))] impl Probe { - const RETRY: Duration = Duration::from_secs(300); + const RETRY: std::time::Duration = std::time::Duration::from_secs(300); /// Starts probing both platforms in the background. pub fn start(ctx: &egui::Context) -> Probe { @@ -90,7 +93,7 @@ impl Probe { *have |= now; } self.job = None; - self.last = Some(std::time::Instant::now()); + self.last = Some(web_time::Instant::now()); } if self.job.is_none() && !self.available.iter().all(|a| *a) { match self.last { diff --git a/apps/desktop/src/online_ui.rs b/apps/desktop/src/online_ui.rs index 249cf18..75e04be 100644 --- a/apps/desktop/src/online_ui.rs +++ b/apps/desktop/src/online_ui.rs @@ -37,7 +37,7 @@ struct Job { work: Background>, /// When Stop was pressed: a download that does not stop soon (a stalled /// connection) leaves the list; its database stays claimed until it ends. - stopped: Option, + stopped: Option, /// Started on its own at the program's start: says something only when it added /// games (no "no new games" on every start, no error over a network that is off). quiet: bool, @@ -198,7 +198,7 @@ impl OnlineDialog { for j in &self.jobs { j.work.cancel(); } - let start = std::time::Instant::now(); + let start = web_time::Instant::now(); while !self.jobs.is_empty() && start.elapsed() < std::time::Duration::from_secs(3) { self.jobs.retain(|j| j.work.poll().is_none()); std::thread::sleep(std::time::Duration::from_millis(30)); @@ -642,7 +642,7 @@ impl OnlineDialog { self.jobs[k].work.cancel(); self.jobs[k] .stopped - .get_or_insert_with(std::time::Instant::now); + .get_or_insert_with(web_time::Instant::now); } ui.label( RichText::new(tr( diff --git a/apps/desktop/src/platform/clipboard.rs b/apps/desktop/src/platform/clipboard.rs new file mode 100644 index 0000000..82c8cd3 --- /dev/null +++ b/apps/desktop/src/platform/clipboard.rs @@ -0,0 +1,50 @@ +//! Reading the clipboard on request («Paste PGN», «Paste a line»): at once on a +//! computer; in a browser asked of it (it may ask the user, and answers later). +//! Writing needs nothing of this: `egui::Context::copy_text` works everywhere. + +use std::sync::{Arc, Mutex}; + +/// A reading of the clipboard under way. +pub struct Reading { + text: Arc>>>, +} + +impl Reading { + /// The text once read (`Some(None)`: empty, refused or unavailable). + pub fn poll(&self) -> Option> { + self.text.lock().ok()?.take() + } +} + +/// Starts reading the clipboard's text; `ctx` is woken when it is there. +pub fn read_text(ctx: &egui::Context) -> Reading { + let text = Arc::new(Mutex::new(None)); + #[cfg(not(web))] + { + let _ = ctx; + let read = arboard::Clipboard::new() + .and_then(|mut c| c.get_text()) + .ok(); + if let Ok(mut t) = text.lock() { + *t = Some(read); + } + } + #[cfg(web)] + { + let (slot, ctx) = (text.clone(), ctx.clone()); + wasm_bindgen_futures::spawn_local(async move { + let read = match web_sys::window().map(|w| w.navigator().clipboard()) { + Some(c) => wasm_bindgen_futures::JsFuture::from(c.read_text()) + .await + .ok() + .and_then(|v| v.as_string()), + None => None, + }; + if let Ok(mut t) = slot.lock() { + *t = Some(read); + } + ctx.request_repaint(); + }); + } + Reading { text } +} diff --git a/apps/desktop/src/platform/files.rs b/apps/desktop/src/platform/files.rs new file mode 100644 index 0000000..8a429f0 --- /dev/null +++ b/apps/desktop/src/platform/files.rs @@ -0,0 +1,286 @@ +//! The files the user opens and saves: the system's dialogs on a computer; in a +//! browser its file chooser, files dropped on the page, and downloads. A file the user +//! gives the page is only read (decisions «Веб-версия»): it gets a path of the page's +//! file tree for the session and is opened by that path like a file on a disk. Chrome +//! and Edge remember a chosen file for the next visit ([`super::web::remembered`]). + +use std::path::PathBuf; + +/// The extensions of the databases the program opens (both cases for the dialogs of +/// systems that tell them apart). +const DATABASES: [&str; 10] = [ + "pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z", +]; + +/// Databases a browser does not open: their files together larger than this (the +/// program for the computer opens them). +pub const TOO_BIG: u64 = 2_000_000_000; + +/// What the user chose or dropped: the databases to open, the ones left out because +/// they are too big for a browser (name, bytes of their files), the ChessBase +/// databases not all files of which were given (the name of their `.cbh`), and +/// whether a chosen folder held no database. +#[derive(Default)] +pub struct Picked { + pub paths: Vec, + pub too_big: Vec<(String, u64)>, + pub incomplete: Vec, + pub empty_folder: bool, +} + +/// The files the user gave the page, made databases: the ChessBase ones of their +/// several files (`chess_import::group_chosen`), each kept for the session in a folder +/// of its own. Also the files of each database kept (its path, their places in +/// `files`), for the browser to remember. +#[cfg(web)] +pub(super) fn gather( + files: &[web_sys::File], + folder: bool, +) -> (Picked, Vec<(PathBuf, Vec)>) { + let names: Vec = files.iter().map(|f| f.name()).collect(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let chosen = chess_import::group_chosen(&refs, folder); + let mut picked = Picked { + incomplete: chosen.incomplete, + ..Picked::default() + }; + let mut kept = Vec::new(); + for db in chosen.databases { + let size: u64 = db.iter().map(|&i| files[i].size() as u64).sum(); + if size > TOO_BIG { + picked.too_big.push((names[db[0]].clone(), size)); + continue; + } + let path = super::web::vfs::add_opened(db.iter().map(|&i| files[i].clone()).collect()); + picked.paths.push(path.clone()); + kept.push((path, db)); + } + picked.empty_folder = folder + && picked.paths.is_empty() + && picked.too_big.is_empty() + && picked.incomplete.is_empty(); + (picked, kept) +} + +/// A ChessBase database's `.cbh` given without the files it cannot be read without +/// (a browser has only the files the user gave it). +pub fn chessbase_incomplete(path: &std::path::Path) -> bool { + #[cfg(web)] + { + let cbh = path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("cbh")); + cbh && super::web::vfs::database_files(path).is_ok_and(|files| { + !files + .iter() + .any(|(name, _)| name.to_lowercase().ends_with(".cbg")) + }) + } + #[cfg(not(web))] + { + let _ = path; + false + } +} + +/// How the user's file `path` is named to the user: on a computer its path, in a +/// browser its name (the page's own places, `/opened/…`, mean nothing to the user). +pub fn shown(path: &std::path::Path) -> String { + #[cfg(web)] + return path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + #[cfg(not(web))] + path.display().to_string() +} + +/// A file the browser holds for this visit only (one the user chose or dropped): after +/// 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 database `path` (all its files) in the browser's +/// storage, where it stays between visits; `then` gets the copy's path. Refused when +/// the browser gives the site too little room (the size and what is free, for the +/// message). +#[cfg(web)] +pub fn keep_copy(path: &std::path::Path, then: impl FnOnce(Result) + 'static) { + use wasm_bindgen::JsCast; + let parts = match super::web::vfs::database_files(path) { + Ok(p) => p, + Err(e) => return then(Err(KeepCopy::Failed(e.to_string()))), + }; + let need: u64 = parts + .iter() + .map(|(_, s)| match s.dyn_ref::() { + Some(b) => b.size() as u64, + None => js_sys::Reflect::get(s, &"length".into()) + .ok() + .and_then(|l| l.as_f64()) + .unwrap_or(0.0) as u64, + }) + .sum(); + if let Some(free) = super::storage_free() + && need + need / 10 > free + { + return then(Err(KeepCopy::NoRoom { need, free })); + } + // A folder of its own, as the database had: the names stay as they were. + let dir = super::data_dir() + .unwrap_or_default() + .join("copies") + .join((js_sys::Date::now() as u64).to_string()); + let first = dir.join(&parts[0].0); + wasm_bindgen_futures::spawn_local(async move { + for (name, source) in parts { + let bytes = match source.dyn_into::() { + Ok(blob) => match wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await { + Ok(buf) => js_sys::Uint8Array::new(&buf).to_vec(), + Err(e) => return then(Err(KeepCopy::Failed(format!("{e:?}")))), + }, + Err(array) => js_sys::Uint8Array::new(&array).to_vec(), + }; + if let Err(e) = super::fs::write_atomic(&dir.join(name), &bytes) { + return then(Err(KeepCopy::Failed(e.to_string()))); + } + } + then(Ok(first)); + }); +} + +/// Why no copy was kept. +#[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(Picked) + Send + 'static) { + #[cfg(not(web))] + { + use crate::i18n::tr; + let _ = std::thread::Builder::new() + .name("dialog".into()) + .spawn(move || { + let picked = rfd::FileDialog::new() + .set_title(tr("Open database")) + .add_filter(tr("Chess databases"), &DATABASES) + .add_filter("PGN", &["pgn", "PGN"]) + .add_filter(tr("All files"), &["*"]) + .pick_files(); + then(Picked { + paths: picked.unwrap_or_default(), + ..Picked::default() + }); + }); + } + #[cfg(web)] + { + let extensions: Vec = DATABASES + .iter() + .step_by(2) + .map(|e| format!(".{e}")) + .collect(); + if super::web::remembered::supported() { + super::web::remembered::pick(&extensions, then); + } else { + super::web::page::pick_files(&extensions.join(","), move |files| { + then(gather(&files, false).0) + }); + } + } +} + +/// Asks the user for a database's folder (a ChessBase database is several files): its +/// databases are found by their files' names. Chrome and Edge remember the folder. +#[cfg(web)] +pub fn pick_database_folder(then: impl FnOnce(Picked) + Send + 'static) { + if super::web::remembered::supported_folder() { + super::web::remembered::pick_folder(then); + } else { + super::web::page::pick_folder(move |files| then(gather(&files, true).0)); + } +} + +/// The browser remembers the files chosen in its dialog for the next visit (Chrome, +/// Edge); the others, and a computer, have no need or no way. +pub fn remembers_chosen() -> bool { + #[cfg(web)] + return super::web::remembered::supported(); + #[cfg(not(web))] + false +} + +/// The browser remembers the file `path` of an earlier visit and asks the user before +/// the page reads it again ([`allow_reading`]). Never on a computer. +pub fn waiting_to_read(path: &std::path::Path) -> bool { + #[cfg(web)] + return super::web::remembered::waiting(path); + #[cfg(not(web))] + { + let _ = path; + false + } +} + +/// Asks the browser to let the page read the remembered file `path` again (soon after +/// the user's click); `then`: whether it is back. +#[cfg(web)] +pub fn allow_reading(path: &std::path::Path, then: impl FnOnce(bool) + 'static) { + super::web::remembered::allow(path, then); +} + +/// The file `path` left the library: a browser forgets it too. +pub fn forget(path: &std::path::Path) { + #[cfg(web)] + super::web::remembered::forget(path); + #[cfg(not(web))] + let _ = path; +} + +/// The files dropped on the window in this frame, as databases to open: `then` gets +/// their paths once read (in a browser they are kept for the session like chosen +/// ones). The desktop program does not take dropped files: nothing comes there. +pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Picked) + Send + 'static) { + #[cfg(not(web))] + { + let _ = (ctx, then); + } + #[cfg(web)] + { + let files: Vec = ctx.input(|i| { + i.raw + .dropped_files + .iter() + .filter_map(|f| f.web_file().cloned()) + .collect() + }); + if files.is_empty() { + return; + } + then(gather(&files, false).0); + } +} + +/// Files are dragged over the window now (the page shows where they go). +pub fn dragging(ctx: &egui::Context) -> bool { + cfg!(web) && ctx.input(|i| !i.raw.hovered_files.is_empty()) +} + +/// Gives `pgn` to the user as the file `name` (a download, where the browser puts +/// them). Only a browser does this: the desktop program saves into files it chose. +#[cfg(web)] +pub fn download_pgn(name: &str, pgn: &str) -> Result<(), String> { + super::web::page::download(name, "application/x-chess-pgn", pgn.as_bytes()) + .map_err(|e| format!("{e:?}")) +} diff --git a/apps/desktop/src/platform/fs.rs b/apps/desktop/src/platform/fs.rs new file mode 100644 index 0000000..fe980d1 --- /dev/null +++ b/apps/desktop/src/platform/fs.rs @@ -0,0 +1,105 @@ +//! Files of the program and the files the user opened: the disk on a computer; in a +//! browser the page's files ([`super::web::vfs`]): the program's data kept in the +//! browser's storage, the user's files in memory for the session. + +use std::io; +use std::path::Path; + +/// What is known of a file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Meta { + pub len: u64, + /// Last change, ms since the Unix epoch (0: not known). + pub modified_ms: u64, + pub readonly: bool, +} + +pub fn read(path: &Path) -> io::Result> { + #[cfg(not(web))] + { + std::fs::read(path) + } + #[cfg(web)] + { + super::web::vfs::read(path) + } +} + +pub fn read_to_string(path: &Path) -> io::Result { + String::from_utf8(read(path)?).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) +} + +/// The first `len` bytes of the file (fewer when it is shorter). +pub fn read_head(path: &Path, len: usize) -> io::Result> { + #[cfg(not(web))] + { + use std::io::Read; + let mut head = Vec::with_capacity(len); + std::fs::File::open(path)? + .take(len as u64) + .read_to_end(&mut head)?; + Ok(head) + } + #[cfg(web)] + { + let mut all = super::web::vfs::read(path)?; + all.truncate(len); + Ok(all) + } +} + +/// Writes the file whole: a reader sees the old text or the new one, never a part +/// (on a computer through a temporary file and a rename; its folder is made). +pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + #[cfg(not(web))] + { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path).inspect_err(|_| { + let _ = std::fs::remove_file(&tmp); + }) + } + #[cfg(web)] + { + super::web::vfs::write(path, bytes.to_vec()) + } +} + +pub fn exists(path: &Path) -> bool { + meta(path).is_ok() +} + +pub fn meta(path: &Path) -> io::Result { + #[cfg(not(web))] + { + let m = std::fs::metadata(path)?; + let modified_ms = m + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_millis() as u64); + Ok(Meta { + len: m.len(), + modified_ms, + readonly: m.permissions().readonly(), + }) + } + #[cfg(web)] + { + super::web::vfs::meta(path) + } +} + +pub fn remove_file(path: &Path) -> io::Result<()> { + #[cfg(not(web))] + { + std::fs::remove_file(path) + } + #[cfg(web)] + { + super::web::vfs::remove(path) + } +} diff --git a/apps/desktop/src/platform/mod.rs b/apps/desktop/src/platform/mod.rs new file mode 100644 index 0000000..ebc6171 --- /dev/null +++ b/apps/desktop/src/platform/mod.rs @@ -0,0 +1,164 @@ +//! What differs between the desktop program and the web version (`docs/dev/web.md`). +//! +//! The interface asks this module, never the system, for: where the program keeps its +//! data ([`config_dir`] and the others), files ([`fs`]), background work ([`spawn`]), +//! the files the user opens or saves ([`files`]), the clipboard ([`clipboard`]) and +//! what the platform offers at all ([`CAPS`]). On a computer it is the system's +//! (`native.rs`); in a browser (`cfg(web)`) the page's (`web/`): the program's data in +//! the browser's storage (IndexedDB), the files the user opened in memory, background +//! work between frames. +#![cfg_attr(web, warn(unused))] + +use std::path::PathBuf; + +#[cfg(not(web))] +mod native; +#[cfg(not(web))] +use native as imp; +#[cfg(web)] +pub mod web; +#[cfg(web)] +use web as imp; + +pub mod clipboard; +pub mod files; +pub mod fs; +pub mod page; +pub mod pgn_store; + +/// What the platform offers the interface: a feature it lacks is not shown. +#[derive(Clone, Copy, Debug)] +pub struct Caps { + /// Checking for a new version and installing it (the web version is always the + /// latest: a reload brings it). + pub updates: bool, + /// Downloading games from Lichess and Chess.com. + pub online_games: bool, + /// Games against the computer (Maia, Rodent). + pub play: bool, + /// Preparing against an opponent. + pub prep: bool, + /// Machine translation of comments. + pub translation: bool, + /// The user's own PGN databases on the disk: new ones, games added and replaced. + pub own_databases: bool, + /// Engines as programs on the disk: chosen, downloaded, started. + pub engine_programs: bool, + /// The opening trainer. + 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. +#[cfg(not(web))] +pub const CAPS: Caps = Caps { + updates: true, + online_games: true, + play: true, + prep: true, + translation: true, + own_databases: true, + engine_programs: true, + training: true, + download_pgn: false, + reference: true, +}; + +/// The features of this platform: the light web version (`docs/decisions.md`, «Веб-версия»). +#[cfg(web)] +pub const CAPS: Caps = Caps { + updates: false, + online_games: false, + play: false, + prep: false, + translation: false, + own_databases: false, + engine_programs: false, + training: false, + download_pgn: true, + reference: false, +}; + +/// The program's settings (`~/.config/chesspenguin`; in a browser, its storage). +pub fn config_dir() -> Option { + imp::config_dir() +} + +/// The program's data kept for good (`~/.local/share/chesspenguin`). +pub fn data_dir() -> Option { + imp::data_dir() +} + +/// Data the program can make again (`~/.cache/chesspenguin`). +pub fn cache_dir() -> Option { + imp::cache_dir() +} + +/// The sample databases: files of the program, written at the first start on a +/// computer; built in and only read in a browser. +pub fn examples_dir() -> Option { + imp::examples_dir() +} + +/// Runs `job` in the background and returns at once: on a thread of its own named +/// `name` on a computer; in a browser (which gives a page no threads) on the page's +/// thread after the current frame, so a job there is one finite piece of work, never a +/// loop that waits. The error: the job could not be started. +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 { + #[cfg(web)] + return web::storage::usage().map(|(used, quota)| quota.saturating_sub(used)); + #[cfg(not(web))] + None +} + +/// A size for people in the interface's language: "340 KB", "96 MB", "9.6 GB" +/// («9,6 ГБ», «9,6 Go»: its units and its decimal sign). +pub fn size_text(bytes: u64) -> String { + use crate::i18n::{tr, trf}; + let b = bytes as f64; + let (n, unit) = if b >= 1e9 { + (format!("{:.1}", b / 1e9), "{n} GB") + } else if b >= 1e6 { + (format!("{:.0}", b / 1e6), "{n} MB") + } else { + (format!("{:.0}", (b / 1e3).max(1.0)), "{n} KB") + }; + // The key's own text where the language writes a decimal point. + let n = if tr("decimal comma") == "," { + n.replace('.', ",") + } else { + n + }; + trf(unit, &[("n", &n)]) +} + +/// A line for the program's log (`chesspenguin.log`; in a browser its console). +pub fn log(line: &str) { + #[cfg(not(web))] + crate::graphics::log(line); + #[cfg(web)] + log::info!("{line}"); +} + +/// Reads a database the library shows away from the screen's thread: its file on the +/// disk on a thread of its own (`progress` follows the reading), or in a browser the +/// file the user gave the page (or a sample built in) in the page's reader, a worker +/// (no progress). `done` gets the database: on that thread, or on the page's. +pub fn open_database( + path: &std::path::Path, + progress: impl FnMut(chess_core::ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + imp::open_database(path, progress, cancel, done) +} diff --git a/apps/desktop/src/platform/native.rs b/apps/desktop/src/platform/native.rs new file mode 100644 index 0000000..b416015 --- /dev/null +++ b/apps/desktop/src/platform/native.rs @@ -0,0 +1,46 @@ +//! The desktop program: the system's folders, files and threads. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::ScanProgress; +use chess_import::{ImportError, Opened}; + +fn project() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") +} + +pub fn config_dir() -> Option { + project().map(|d| d.config_dir().to_path_buf()) +} + +pub fn data_dir() -> Option { + project().map(|d| d.data_dir().to_path_buf()) +} + +pub fn cache_dir() -> Option { + project().map(|d| d.cache_dir().to_path_buf()) +} + +pub fn examples_dir() -> Option { + project().map(|d| d.data_local_dir().join("examples")) +} + +pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + std::thread::Builder::new() + .name(name.to_owned()) + .spawn(job) + .map(drop) +} + +pub fn open_database( + path: &Path, + mut progress: impl FnMut(ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + let path = path.to_owned(); + spawn("db-open", move || { + done(chess_import::open(&path, &mut progress, &cancel)); + }) +} diff --git a/apps/desktop/src/platform/page.rs b/apps/desktop/src/platform/page.rs new file mode 100644 index 0000000..ea73823 --- /dev/null +++ b/apps/desktop/src/platform/page.rs @@ -0,0 +1,110 @@ +//! The program as a page of a browser (docs/design/web-version.md §1.1, §1.3): a game +//! on the screen is an entry of the browser's history, so its «Back» means «← Library»; +//! unsaved work makes the browser ask before the page is left. A desktop program has +//! neither: nothing happens there. + +#[cfg(web)] +mod imp { + use std::cell::Cell; + + use wasm_bindgen::JsCast; + use wasm_bindgen::prelude::*; + + thread_local! { + /// The history has our entry for the game on the screen. + static IN_GAME: Cell = const { Cell::new(false) }; + /// «Back» was pressed (the entry left) and not taken yet. + static BACK: Cell = const { Cell::new(false) }; + /// Our own `history.back()`: its `popstate` is not the user's. + static OWN_BACK: Cell = const { Cell::new(false) }; + static LISTENING: Cell = const { Cell::new(false) }; + static WARN: Cell = const { Cell::new(false) }; + /// The page's `beforeunload`: the browser asks before the page is left. + static ASK: Closure = + Closure::new(|e: web_sys::BeforeUnloadEvent| { + e.prevent_default(); + e.set_return_value(""); + }); + } + + fn listen(ctx: &egui::Context) { + if LISTENING.replace(true) { + return; + } + let ctx = ctx.clone(); + let on_pop = Closure::::new(move || { + if OWN_BACK.replace(false) { + return; + } + if IN_GAME.replace(false) { + BACK.set(true); + ctx.request_repaint(); + } + }); + if let Some(w) = web_sys::window() { + let _ = w.add_event_listener_with_callback("popstate", on_pop.as_ref().unchecked_ref()); + } + // Listens as long as the page lives. + on_pop.forget(); + } + + pub fn game_shown(ctx: &egui::Context, shown: bool) { + listen(ctx); + let Some(history) = web_sys::window().and_then(|w| w.history().ok()) else { + return; + }; + if shown && !IN_GAME.get() { + let state = js_sys::Object::new(); + let _ = js_sys::Reflect::set(&state, &"cpGame".into(), &JsValue::TRUE); + if history.push_state(&state, "").is_ok() { + IN_GAME.set(true); + } + } else if !shown && IN_GAME.get() { + // The game left by the program's own button: its entry goes too. + IN_GAME.set(false); + OWN_BACK.set(true); + let _ = history.back(); + } + } + + pub fn take_back() -> bool { + BACK.replace(false) + } + + pub fn warn_on_leave(warn: bool) { + if WARN.replace(warn) == warn { + return; + } + let Some(w) = web_sys::window() else { return }; + if warn { + ASK.with(|ask| w.set_onbeforeunload(Some(ask.as_ref().unchecked_ref()))); + } else { + w.set_onbeforeunload(None); + } + } +} + +/// The game is on the screen (`true`) or not: kept in step with the browser's history. +pub fn game_shown(ctx: &egui::Context, shown: bool) { + #[cfg(web)] + imp::game_shown(ctx, shown); + #[cfg(not(web))] + let _ = (ctx, shown); +} + +/// The browser's «Back» left the game since the last call (then it is «← Library»). +pub fn take_back() -> bool { + #[cfg(web)] + return imp::take_back(); + #[cfg(not(web))] + false +} + +/// Whether leaving the page (closing the tab, reloading) should be asked about: the +/// browser asks in its own words. +pub fn warn_on_leave(warn: bool) { + #[cfg(web)] + imp::warn_on_leave(warn); + #[cfg(not(web))] + let _ = warn; +} diff --git a/apps/desktop/src/platform/pgn_store.rs b/apps/desktop/src/platform/pgn_store.rs new file mode 100644 index 0000000..3f85435 --- /dev/null +++ b/apps/desktop/src/platform/pgn_store.rs @@ -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) -> 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 { + #[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 { + #[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)?) + } +} diff --git a/apps/desktop/src/platform/web/engine.rs b/apps/desktop/src/platform/web/engine.rs new file mode 100644 index 0000000..94d15df --- /dev/null +++ b/apps/desktop/src/platform/web/engine.rs @@ -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> = 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::() + .map(|e| String::from(e.message())) + }) + .unwrap_or_else(|| format!("{e:?}")) +} + +fn caches() -> Result { + web_sys::window().ok_or("no window")?.caches().map_err(js) +} + +async fn open() -> Result { + 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::() 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 { + 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) -> 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 = 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) +} diff --git a/apps/desktop/src/platform/web/idb.rs b/apps/desktop/src/platform/web/idb.rs new file mode 100644 index 0000000..3641f1c --- /dev/null +++ b/apps/desktop/src/platform/web/idb.rs @@ -0,0 +1,167 @@ +//! The program's data in the browser's storage: one IndexedDB database, a store of +//! files by path, read whole at the start (settings and marks are small), every write +//! going there behind the interface, in the order made; and a store of the user's files +//! a Chromium browser remembers (their handles, by the page's path: [`super::remembered`]). + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +const DB: &str = "chesspenguin"; +const STORE: &str = "files"; +const HANDLES: &str = "handles"; +/// 2: the store of handles. +const VERSION: u32 = 2; + +/// The request's outcome once it is done. +async fn done(request: &web_sys::IdbRequest) -> Result { + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let ok = Closure::once_into_js(move |ev: web_sys::Event| { + let r = ev + .target() + .and_then(|t| t.dyn_into::().ok()) + .and_then(|r| r.result().ok()) + .unwrap_or(JsValue::UNDEFINED); + let _ = resolve.call1(&JsValue::NULL, &r); + }); + let err = Closure::once_into_js(move |ev: web_sys::Event| { + let _ = reject.call1(&JsValue::NULL, &ev); + }); + request.set_onsuccess(Some(ok.unchecked_ref())); + request.set_onerror(Some(err.unchecked_ref())); + }); + wasm_bindgen_futures::JsFuture::from(promise).await +} + +async fn open() -> Result { + let factory = web_sys::window() + .ok_or("no window")? + .indexed_db()? + .ok_or("no IndexedDB")?; + let request = factory.open_with_u32(DB, VERSION)?; + let upgrade = Closure::once_into_js(move |ev: web_sys::Event| { + if let Some(db) = ev + .target() + .and_then(|t| t.dyn_into::().ok()) + .and_then(|r| r.result().ok()) + .and_then(|r| r.dyn_into::().ok()) + { + for store in [STORE, HANDLES] { + if !db.object_store_names().contains(store) { + let _ = db.create_object_store(store); + } + } + } + }); + request.set_onupgradeneeded(Some(upgrade.unchecked_ref())); + done(&request).await?.dyn_into() +} + +thread_local! { + /// The database once opened (`None` until then, or when the browser refused it: + /// a private window of some browsers; then nothing is kept between visits). + static OPENED: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Everything kept: (path, bytes). Empty when the browser keeps nothing for the page. +pub async fn load_all() -> Vec<(String, Vec)> { + let db = match open().await { + Ok(db) => db, + Err(e) => { + log::warn!("browser storage unavailable: {e:?}"); + return Vec::new(); + } + }; + let read = async { + let tx = db.transaction_with_str(STORE)?; + let store = tx.object_store(STORE)?; + let keys = done(&store.get_all_keys()?).await?; + let values = done(&store.get_all()?).await?; + let keys: js_sys::Array = keys.dyn_into()?; + let values: js_sys::Array = values.dyn_into()?; + Ok::<_, JsValue>( + keys.iter() + .zip(values.iter()) + .filter_map(|(k, v)| { + let bytes = v.dyn_into::().ok()?.to_vec(); + Some((k.as_string()?, bytes)) + }) + .collect(), + ) + }; + let files = read.await.unwrap_or_else(|e| { + log::warn!("browser storage unreadable: {e:?}"); + Vec::new() + }); + OPENED.with_borrow_mut(|o| *o = Some(db)); + files +} + +fn store_named(name: &str) -> Option { + OPENED.with_borrow(|db| { + let tx = db + .as_ref()? + .transaction_with_str_and_mode(name, web_sys::IdbTransactionMode::Readwrite) + .ok()?; + tx.object_store(name).ok() + }) +} + +fn store() -> Option { + store_named(STORE) +} + +/// The handles kept: (the page's path, the handle). Read after [`load_all`]. +pub async fn handles() -> Vec<(String, JsValue)> { + let Some(db) = OPENED.with_borrow(|db| db.clone()) else { + return Vec::new(); + }; + let read = async { + let tx = db.transaction_with_str(HANDLES)?; + let store = tx.object_store(HANDLES)?; + let keys: js_sys::Array = done(&store.get_all_keys()?).await?.dyn_into()?; + let values: js_sys::Array = done(&store.get_all()?).await?.dyn_into()?; + Ok::<_, JsValue>( + keys.iter() + .zip(values.iter()) + .filter_map(|(k, v)| Some((k.as_string()?, v))) + .collect(), + ) + }; + read.await.unwrap_or_else(|e: JsValue| { + log::warn!("browser storage: remembered files unreadable: {e:?}"); + Vec::new() + }) +} + +pub fn put_handle(path: &str, handle: &JsValue) { + if let Some(store) = store_named(HANDLES) + && let Err(e) = store.put_with_key(handle, &JsValue::from_str(path)) + { + log::warn!("browser storage: cannot remember {path}: {e:?}"); + } +} + +pub fn delete_handle(path: &str) { + if let Some(store) = store_named(HANDLES) { + let _ = store.delete(&JsValue::from_str(path)); + } +} + +/// Keeps `bytes` as `path` (transactions of one page run in the order made). +pub fn put(path: String, bytes: Vec) { + if let Some(store) = store() { + let value = js_sys::Uint8Array::from(bytes.as_slice()); + if let Err(e) = store.put_with_key(&value, &JsValue::from_str(&path)) { + log::warn!("browser storage: cannot keep {path}: {e:?}"); + } + } +} + +pub fn delete(path: String) { + if let Some(store) = store() + && let Err(e) = store.delete(&JsValue::from_str(&path)) + { + log::warn!("browser storage: cannot delete {path}: {e:?}"); + } +} diff --git a/apps/desktop/src/platform/web/import.rs b/apps/desktop/src/platform/web/import.rs new file mode 100644 index 0000000..dde9afd --- /dev/null +++ b/apps/desktop/src/platform/web/import.rs @@ -0,0 +1,316 @@ +//! Opening a database without holding the page: a Web Worker runs a second instance of +//! the program (`import-worker.js` → [`answer`]) that reads the file — PGN, CBV, ZIP, +//! 7Z, converted and indexed — and gives back its text and index; the page puts the +//! database together from them without reading it again +//! (`chess_core::PgnDatabase::from_index`); the cards of the shelf only ask it how many +//! games a file holds. One worker serves the visit and reads the files one after +//! another, in the order they were given. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use chess_core::{PgnDatabase, PgnIndex}; +use chess_import::{Database, Format, ImportError, Opened, PgnDb, Unsupported}; +use serde::{Deserialize, Serialize}; +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The worker's script, beside the page. +const SCRIPT: &str = "import-worker.js"; + +/// What the worker gives back besides the text. +#[derive(Serialize, Deserialize)] +struct Read { + index: PgnIndex, + /// Its place in [`Format::ALL`]. + format: usize, + notes: Vec, +} + +/// Why the worker could not read a file: [`ImportError`] in serde's terms. +#[derive(Serialize, Deserialize)] +enum Failure { + Io(String), + Corrupt(String), + Encrypted, + ChessBase2, + ChessBaseFiles, + Empty, + Cancelled, +} + +impl Failure { + fn of(e: ImportError) -> Failure { + match e { + ImportError::Io { source, .. } => Failure::Io(source.to_string()), + ImportError::Corrupt(s) => Failure::Corrupt(s), + ImportError::Unsupported(Unsupported::Encrypted) => Failure::Encrypted, + ImportError::Unsupported(Unsupported::ChessBase2) => Failure::ChessBase2, + ImportError::Unsupported(Unsupported::ChessBaseFiles) => Failure::ChessBaseFiles, + ImportError::Empty => Failure::Empty, + ImportError::Cancelled => Failure::Cancelled, + } + } + + fn error(self, path: &Path) -> ImportError { + match self { + Failure::Io(e) => io_error(path, e), + Failure::Corrupt(s) => ImportError::Corrupt(s), + Failure::Encrypted => ImportError::Unsupported(Unsupported::Encrypted), + Failure::ChessBase2 => ImportError::Unsupported(Unsupported::ChessBase2), + Failure::ChessBaseFiles => ImportError::Unsupported(Unsupported::ChessBaseFiles), + Failure::Empty => ImportError::Empty, + Failure::Cancelled => ImportError::Cancelled, + } + } +} + +fn io_error(path: &Path, e: impl ToString) -> ImportError { + ImportError::Io { + path: path.to_owned(), + source: std::io::Error::other(e.to_string()), + } +} + +fn set(object: &js_sys::Object, key: &str, value: &JsValue) { + let _ = js_sys::Reflect::set(object, &key.into(), value); +} + +thread_local! { + /// The worker's side: the files of the database being given, one by one (so that + /// the worker holds each file's bytes once: in the program, not also in the page's + /// script). + static GIVEN: RefCell)>> = const { RefCell::new(Vec::new()) }; +} + +/// The worker's side: one more file of the database to read (its own file first). +pub fn give(name: String, bytes: Vec) { + // The reader's panics to the console (the page's own hook is eframe's). + static HOOK: std::sync::Once = std::sync::Once::new(); + HOOK.call_once(|| { + std::panic::set_hook(Box::new(|info| { + web_sys::console::error_1(&format!("the reader: {info}").into()); + })); + }); + GIVEN.with_borrow_mut(|g| g.push((name, bytes))); +} + +/// The worker's side: reads the database given ([`give`]). The answer: `{text, index}` +/// (the text and the index in JSON), only `{games}` when `count` is asked, or `{error}` +/// (a [`Failure`] in JSON). +pub fn answer(count: bool) -> JsValue { + let never = std::sync::atomic::AtomicBool::new(false); + let answer = js_sys::Object::new(); + let mut files = GIVEN.with_borrow_mut(std::mem::take); + if files.is_empty() { + files.push((String::new(), Vec::new())); + } + let name = files[0].0.clone(); + let chessbase = name.to_lowercase().ends_with(".cbh"); + let opened = if chessbase { + chess_import::open_chessbase_owned(&name, files, &mut |_| {}, &never) + } else { + let bytes = files.swap_remove(0).1; + chess_import::open_bytes(&name, bytes, &mut |_| {}, &never) + }; + let read = opened.and_then(|opened| { + // Read from bytes, a database is always converted to PGN. + let Database::Pgn(pgn) = opened.db else { + return Err(ImportError::Corrupt("not a PGN database".into())); + }; + Ok((pgn.db, opened.format, opened.notes)) + }); + match read { + Ok((db, _, _)) if count => set(&answer, "games", &JsValue::from(db.len() as f64)), + Ok((db, format, notes)) => { + let (text, index) = db.into_index(); + let read = Read { + index, + format: Format::ALL.iter().position(|f| *f == format).unwrap_or(0), + notes, + }; + set(&answer, "text", &js_sys::Uint8Array::from(text.as_slice())); + let json = serde_json::to_string(&read).unwrap_or_default(); + set(&answer, "index", &JsValue::from_str(&json)); + } + Err(e) => { + let json = serde_json::to_string(&Failure::of(e)).unwrap_or_default(); + set(&answer, "error", &JsValue::from_str(&json)); + } + } + answer.into() +} + +/// Who waits for an answer. +enum Waiting { + Open(PathBuf, Box)>), + Count(Box)>), +} + +impl Waiting { + fn out_of_memory(self) { + match self { + Waiting::Open(path, done) => done(Err(ImportError::Io { + path, + source: std::io::Error::from(std::io::ErrorKind::OutOfMemory), + })), + Waiting::Count(done) => done(None), + } + } + + fn failed(self, e: impl ToString) { + match self { + Waiting::Open(path, done) => done(Err(io_error(&path, e))), + Waiting::Count(done) => done(None), + } + } +} + +thread_local! { + static WORKER: RefCell> = const { RefCell::new(None) }; + static WAITING: RefCell> = RefCell::new(HashMap::new()); + static NEXT: RefCell = const { RefCell::new(0) }; +} + +/// The worker's answer to a request: the database, or why there is none. +fn answered(data: JsValue) { + let get = |k: &str| js_sys::Reflect::get(&data, &k.into()).unwrap_or(JsValue::UNDEFINED); + let id = get("id").as_f64().unwrap_or(-1.0) as u32; + if let Some(e) = get("crashed").as_string() { + // The worker's program stopped (out of its memory, most likely: a browser gives + // a page at most 4 GB): this database cannot be read here; the others waiting + // go to a new worker's program — they fail too, to be opened again. + log::warn!("the reader stopped: {e}"); + if let Some(w) = WORKER.with_borrow_mut(Option::take) { + w.terminate(); + } + for (n, waiting) in WAITING.with_borrow_mut(std::mem::take) { + if n == id { + waiting.out_of_memory(); + } else { + waiting.failed(&e); + } + } + return; + } + let (path, done) = match WAITING.with_borrow_mut(|w| w.remove(&id)) { + Some(Waiting::Open(path, done)) => (path, done), + Some(Waiting::Count(done)) => { + done(get("games").as_f64().map(|n| n as usize)); + return; + } + None => return, + }; + if let Some(json) = get("error").as_string() { + let e = serde_json::from_str::(&json) + .map_or_else(|_| io_error(&path, json.clone()), |f| f.error(&path)); + done(Err(e)); + return; + } + let text = get("text") + .dyn_into::() + .map(|a| a.to_vec()); + let read = get("index") + .as_string() + .and_then(|j| serde_json::from_str::(&j).ok()); + let (Ok(text), Some(read)) = (text, read) else { + done(Err(io_error( + &path, + "the reader's answer is not a database", + ))); + return; + }; + let db = PgnDatabase::from_index(text, read.index); + log::info!( + "database read: {} ({} games)", + path.file_name().unwrap_or_default().to_string_lossy(), + db.len() + ); + done(Ok(Opened { + db: Database::Pgn(PgnDb::new(db)), + format: Format::ALL.get(read.format).copied().unwrap_or(Format::Pgn), + notes: read.notes, + })) +} + +fn worker() -> Result { + if let Some(w) = WORKER.with_borrow(|w| w.clone()) { + return Ok(w); + } + let options = web_sys::WorkerOptions::new(); + options.set_type(web_sys::WorkerType::Module); + let w = web_sys::Worker::new_with_options(SCRIPT, &options)?; + let on_message = + Closure::::new(|e: web_sys::MessageEvent| { + answered(e.data()); + }); + w.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + // The worker serves the whole visit. + on_message.forget(); + let on_error = Closure::::new(|e: web_sys::ErrorEvent| { + // The worker itself failed (out of memory, its script not loaded): the files + // waiting for it fail, and the next one gets a new worker. + let message = e.message(); + if let Some(w) = WORKER.with_borrow_mut(Option::take) { + w.terminate(); + } + for (_, waiting) in WAITING.with_borrow_mut(std::mem::take) { + waiting.failed(&message); + } + }); + w.set_onerror(Some(on_error.as_ref().unchecked_ref())); + on_error.forget(); + WORKER.with_borrow_mut(|slot| *slot = Some(w.clone())); + Ok(w) +} + +/// Reads the page's file `path` in the worker; `done` gets the database on the page's +/// thread. +pub fn open(path: &Path, done: impl FnOnce(Result) + 'static) { + ask(path, false, Waiting::Open(path.to_owned(), Box::new(done))); +} + +/// How many games the page's file `path` holds (`None`: it cannot be read), read in +/// the worker; `done` gets it on the page's thread. +pub fn count(path: &Path, done: impl FnOnce(Option) + 'static) { + ask(path, true, Waiting::Count(Box::new(done))); +} + +fn ask(path: &Path, count: bool, waiting: Waiting) { + let files = match super::vfs::database_files(path) { + Ok(f) => f, + Err(e) => return waiting.failed(e), + }; + let w = match worker() { + Ok(w) => w, + Err(e) => return waiting.failed(format!("{e:?}")), + }; + let id = NEXT.with_borrow_mut(|n| { + *n += 1; + *n + }); + WAITING.with_borrow_mut(|m| m.insert(id, waiting)); + let names = js_sys::Array::new(); + let parts = js_sys::Array::new(); + // The bytes the page holds go over without a copy; the user's files are the + // browser's, read by the worker. + let transfer = js_sys::Array::new(); + for (name, source) in files { + names.push(&JsValue::from_str(&name)); + if let Some(array) = source.dyn_ref::() { + transfer.push(&array.buffer()); + } + parts.push(&source); + } + let message = js_sys::Object::new(); + set(&message, "id", &JsValue::from(id)); + set(&message, "names", &names); + set(&message, "parts", &parts); + set(&message, "count", &JsValue::from_bool(count)); + if let Err(e) = w.post_message_with_transfer(&message, &transfer) + && let Some(waiting) = WAITING.with_borrow_mut(|m| m.remove(&id)) + { + waiting.failed(format!("{e:?}")); + } +} diff --git a/apps/desktop/src/platform/web/mod.rs b/apps/desktop/src/platform/web/mod.rs new file mode 100644 index 0000000..4515a21 --- /dev/null +++ b/apps/desktop/src/platform/web/mod.rs @@ -0,0 +1,63 @@ +//! The web version: a page in a browser, without threads, processes or a file system. +//! +//! The program's folders are names in the page's own file tree ([`vfs`]): `/config`, +//! `/data` and `/cache` are kept in the browser's storage ([`idb`], loaded before the +//! interface starts, written behind it); `/examples` (the samples, built in) and +//! `/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 import; +pub mod page; +pub mod remembered; +pub mod storage; +pub mod vfs; + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::ScanProgress; +use chess_import::{ImportError, Opened}; + +pub fn config_dir() -> Option { + Some(PathBuf::from(vfs::CONFIG)) +} + +pub fn data_dir() -> Option { + Some(PathBuf::from(vfs::DATA)) +} + +pub fn cache_dir() -> Option { + Some(PathBuf::from(vfs::CACHE)) +} + +pub fn examples_dir() -> Option { + Some(PathBuf::from(vfs::EXAMPLES)) +} + +/// The page has no threads: the job runs on its thread once the current frame is +/// done (the screen shows the state before it, «Opening…», first). +pub fn spawn(_name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + wasm_bindgen_futures::spawn_local(async move { + page::next_task().await; + job(); + }); + Ok(()) +} + +pub fn open_database( + path: &Path, + _progress: impl FnMut(ScanProgress) + Send + 'static, + cancel: std::sync::Arc, + done: impl FnOnce(Result) + Send + 'static, +) -> std::io::Result<()> { + import::open(path, move |read| { + done(if cancel.load(std::sync::atomic::Ordering::Relaxed) { + Err(ImportError::Cancelled) + } else { + read + }) + }); + Ok(()) +} diff --git a/apps/desktop/src/platform/web/page.rs b/apps/desktop/src/platform/web/page.rs new file mode 100644 index 0000000..e00806f --- /dev/null +++ b/apps/desktop/src/platform/web/page.rs @@ -0,0 +1,144 @@ +//! The page around the program: choosing files, downloads, the next task. + +use std::cell::RefCell; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The elements through which files and a folder are chosen (one each for the page; +/// checks give them files). +pub const OPEN_INPUT_ID: &str = "cp-open-files"; +pub const OPEN_FOLDER_ID: &str = "cp-open-folder"; +/// The program's canvas (`page/index.html`). +const CANVAS_ID: &str = "cp-canvas"; + +fn document() -> Option { + web_sys::window()?.document() +} + +/// Resolves after the tasks queued now: the page draws its frame first. +pub async fn next_task() { + let promise = js_sys::Promise::new(&mut |resolve, _| { + if let Some(w) = web_sys::window() { + let _ = w.set_timeout_with_callback(&resolve); + } + }); + let _ = wasm_bindgen_futures::JsFuture::from(promise).await; +} + +type Picked = Box)>; + +thread_local! { + /// What to do with the files chosen next. + static ON_PICKED: RefCell> = const { RefCell::new(None) }; +} + +/// The page's file input `id`, made once: hidden, several files, `accept` the +/// extensions; `folder`: it chooses a folder (`webkitdirectory`, every browser has it). +fn open_input(id: &str, accept: &str, folder: bool) -> Result { + let doc = document().ok_or("no document")?; + if let Some(el) = doc.get_element_by_id(id) { + let input: web_sys::HtmlInputElement = el.dyn_into()?; + input.set_accept(accept); + return Ok(input); + } + let input: web_sys::HtmlInputElement = doc.create_element("input")?.dyn_into()?; + input.set_id(id); + input.set_type("file"); + input.set_multiple(true); + input.set_accept(accept); + if folder { + input.set_attribute("webkitdirectory", "")?; + } + input.style().set_property("display", "none")?; + let on_change = Closure::::new(move |ev: web_sys::Event| { + let Some(input) = ev + .target() + .and_then(|t| t.dyn_into::().ok()) + else { + return; + }; + let files: Vec = input + .files() + .map(|list| (0..list.length()).filter_map(|i| list.get(i)).collect()) + .unwrap_or_default(); + // The same file chosen again is a change too. + input.set_value(""); + // The keys go to the program again, not to the hidden input. + if let Some(canvas) = document() + .and_then(|d| d.get_element_by_id(CANVAS_ID)) + .and_then(|c| c.dyn_into::().ok()) + { + let _ = canvas.focus(); + } + let files = if folder { + // The folder's own files: a database's folder, not what is below it. + files + .into_iter() + .filter(|f| { + js_sys::Reflect::get(f, &"webkitRelativePath".into()) + .ok() + .and_then(|p| p.as_string()) + .is_none_or(|p| p.matches('/').count() <= 1) + }) + .collect() + } else { + files + }; + if let Some(then) = ON_PICKED.with_borrow_mut(Option::take) { + then(files); + } + }); + input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref())?; + // The input lives as long as the page. + on_change.forget(); + doc.body().ok_or("no body")?.append_child(&input)?; + Ok(input) +} + +/// Asks the user for files (the browser's dialog); `then` gets them once chosen (not +/// read: the page's reader reads them). Must run soon after the user's click or key (a +/// browser opens the dialog only then: egui handles input in the next frame, well +/// within that time). +pub fn pick_files(accept: &str, then: impl FnOnce(Vec) + 'static) { + pick(OPEN_INPUT_ID, accept, false, then); +} + +/// Asks the user for a folder; `then` gets the files right in it. +pub fn pick_folder(then: impl FnOnce(Vec) + 'static) { + pick(OPEN_FOLDER_ID, "", true, then); +} + +fn pick(id: &str, accept: &str, folder: bool, then: impl FnOnce(Vec) + 'static) { + match open_input(id, accept, folder) { + Ok(input) => { + ON_PICKED.with_borrow_mut(|p| *p = Some(Box::new(then))); + input.click(); + } + Err(e) => log::warn!("cannot choose files: {e:?}"), + } +} + +/// Gives the user `bytes` as a downloaded file named `name`. +pub fn download(name: &str, mime: &str, bytes: &[u8]) -> Result<(), JsValue> { + let doc = document().ok_or("no document")?; + let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); + let opts = web_sys::BlobPropertyBag::new(); + opts.set_type(mime); + let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts)?; + let url = web_sys::Url::create_object_url_with_blob(&blob)?; + let a: web_sys::HtmlAnchorElement = doc.create_element("a")?.dyn_into()?; + a.set_href(&url); + a.set_download(name); + a.style().set_property("display", "none")?; + let body = doc.body().ok_or("no body")?; + body.append_child(&a)?; + a.click(); + body.remove_child(&a)?; + // The download has taken the data by the next task. + wasm_bindgen_futures::spawn_local(async move { + next_task().await; + let _ = web_sys::Url::revoke_object_url(&url); + }); + Ok(()) +} diff --git a/apps/desktop/src/platform/web/remembered.rs b/apps/desktop/src/platform/web/remembered.rs new file mode 100644 index 0000000..21ae25e --- /dev/null +++ b/apps/desktop/src/platform/web/remembered.rs @@ -0,0 +1,306 @@ +//! Databases a Chromium browser remembers (Chrome, Edge: the File System Access API): +//! files chosen through `showOpenFilePicker`, or a database's folder chosen through +//! `showDirectoryPicker`, leave handles the page keeps in the browser's storage; at the +//! next visit the database is there again through them — at once when the browser still +//! allows reading, else after the user's «Allow reading» (the browser's own question). +//! Only reading: the page never writes the user's files (decisions «Веб-версия»). +//! Firefox and Safari have no such handles: there the user chooses the file again +//! ([`super::page::pick_files`]). +//! +//! What is kept for a database (its path on the page): `{handles: [file handles]}`, its +//! own file first, or `{dir: folder handle, names: [its files' names]}`; a bare file +//! handle (an earlier version) is a database of one file. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +use crate::platform::files::{Picked, gather}; + +thread_local! { + /// Databases of earlier visits the browser asks about first: the page's path, what + /// is kept for it. + static WAITING: RefCell> = RefCell::new(HashMap::new()); + /// The handle of a `.cbh` chosen alone: the folder's dialog opens where it is. + static LONE_CBH: RefCell> = const { RefCell::new(None) }; +} + +fn get(object: &JsValue, key: &str) -> JsValue { + js_sys::Reflect::get(object, &key.into()).unwrap_or(JsValue::UNDEFINED) +} + +fn set(object: &JsValue, key: &str, value: &JsValue) { + let _ = js_sys::Reflect::set(object, &key.into(), value); +} + +/// Calls `object.method(arg)` (its promise, not awaited): within the user's gesture. +fn start(object: &JsValue, method: &str, arg: &JsValue) -> Result { + let f: js_sys::Function = get(object, method).dyn_into()?; + f.call1(object, arg)?.dyn_into() +} + +/// Calls `object.method(arg)` and waits for the promise it gives. +async fn call(object: &JsValue, method: &str, arg: &JsValue) -> Result { + wasm_bindgen_futures::JsFuture::from(start(object, method, arg)?).await +} + +/// `{mode: "read"}`: the permission asked for. +fn read_mode() -> JsValue { + let o = js_sys::Object::new(); + set(&o, "mode", &"read".into()); + o.into() +} + +/// The browser remembers chosen files (it has `showOpenFilePicker`). +pub fn supported() -> bool { + web_sys::window().is_some_and(|w| get(&w, "showOpenFilePicker").is_function()) +} + +/// The browser remembers a chosen folder (it has `showDirectoryPicker`). +pub fn supported_folder() -> bool { + web_sys::window().is_some_and(|w| get(&w, "showDirectoryPicker").is_function()) +} + +async fn file_of(handle: &JsValue) -> Result { + call(handle, "getFile", &JsValue::UNDEFINED) + .await? + .dyn_into() +} + +/// Opens a dialog of the window (`showOpenFilePicker`, `showDirectoryPicker`) now, +/// within the user's gesture. +fn dialog(method: &str, options: &js_sys::Object) -> Result { + let window = web_sys::window().ok_or("no window")?; + start(&window, method, options) +} + +/// Asks the user for files (the browser's dialog, `extensions` like `.pgn`); `then` +/// gets the databases they make, each remembered. Must run soon after the user's click +/// or key, like [`super::page::pick_files`]. +pub fn pick(extensions: &[String], then: impl FnOnce(Picked) + 'static) { + let accept = js_sys::Object::new(); + let list = extensions + .iter() + .map(|e| JsValue::from_str(e)) + .collect::(); + set(&accept, "application/octet-stream", &list); + let kind = js_sys::Object::new(); + set(&kind, "accept", &accept); + let options = js_sys::Object::new(); + set(&options, "multiple", &JsValue::TRUE); + set(&options, "types", &js_sys::Array::of1(&kind)); + set(&options, "id", &"chesspenguin-databases".into()); + let chosen = dialog("showOpenFilePicker", &options); + wasm_bindgen_futures::spawn_local(async move { + // Cancelled by the user: an error, nothing chosen. + let handles: Vec = match chosen { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p) + .await + .and_then(|h| h.dyn_into::()) + .map(|a| a.to_vec()) + .unwrap_or_default(), + Err(_) => Vec::new(), + }; + let mut files = Vec::new(); + let mut kept_handles = Vec::new(); + for h in handles { + match file_of(&h).await { + Ok(f) => { + files.push(f); + kept_handles.push(h); + } + Err(e) => log::warn!("cannot read a chosen file: {e:?}"), + } + } + let (picked, kept) = gather(&files, false); + for (path, members) in kept { + let entry = js_sys::Object::new(); + let list: js_sys::Array = members.iter().map(|&i| kept_handles[i].clone()).collect(); + set(&entry, "handles", &list); + super::idb::put_handle(&path.to_string_lossy(), &entry); + } + // A .cbh alone: the folder's dialog will open beside it. + let lone = picked.incomplete.first().and_then(|name| { + files + .iter() + .position(|f| f.name() == *name) + .map(|i| kept_handles[i].clone()) + }); + LONE_CBH.with_borrow_mut(|l| *l = lone); + then(picked); + }); +} + +/// Asks the user for a database's folder; `then` gets the databases in it (the files +/// right in it, found by their names), each remembered with the folder. +pub fn pick_folder(then: impl FnOnce(Picked) + 'static) { + let options = js_sys::Object::new(); + set(&options, "id", &"chesspenguin-databases".into()); + set(&options, "mode", &"read".into()); + if let Some(cbh) = LONE_CBH.with_borrow_mut(Option::take) { + set(&options, "startIn", &cbh); + } + let chosen = dialog("showDirectoryPicker", &options); + wasm_bindgen_futures::spawn_local(async move { + let dir = match chosen { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p).await.ok(), + Err(_) => None, + }; + let Some(dir) = dir else { + return then(Picked::default()); + }; + let mut files = Vec::new(); + if let Err(e) = folder_files(&dir, &mut files).await { + log::warn!("cannot read the folder: {e:?}"); + } + let (mut picked, kept) = gather(&files, true); + for (path, members) in kept { + let entry = js_sys::Object::new(); + set(&entry, "dir", &dir); + let names: js_sys::Array = members + .iter() + .map(|&i| JsValue::from_str(&files[i].name())) + .collect(); + set(&entry, "names", &names); + super::idb::put_handle(&path.to_string_lossy(), &entry); + } + picked.empty_folder = + picked.paths.is_empty() && picked.too_big.is_empty() && picked.incomplete.is_empty(); + then(picked); + }); +} + +/// The files right in the folder `dir` (its `values()`, an asynchronous iterator). +async fn folder_files(dir: &JsValue, out: &mut Vec) -> Result<(), JsValue> { + let entries = js_sys::Reflect::apply( + &get(dir, "values").dyn_into::()?, + dir, + &js_sys::Array::new(), + )?; + loop { + let step = call(&entries, "next", &JsValue::UNDEFINED).await?; + if get(&step, "done").is_truthy() { + return Ok(()); + } + let handle = get(&step, "value"); + if get(&handle, "kind").as_string().as_deref() == Some("file") { + out.push(file_of(&handle).await?); + } + } +} + +/// What the browser is asked to let the page read: the folder, or the files. +fn targets(kept: &JsValue) -> Vec { + let dir = get(kept, "dir"); + if !dir.is_undefined() { + return vec![dir]; + } + match get(kept, "handles").dyn_into::() { + Ok(list) => list.to_vec(), + // A bare file handle. + Err(_) => vec![kept.clone()], + } +} + +/// The database's files through what is kept for it, its own first. +async fn files_of(kept: &JsValue) -> Result, JsValue> { + let dir = get(kept, "dir"); + let mut files = Vec::new(); + if dir.is_undefined() { + for h in targets(kept) { + files.push(file_of(&h).await?); + } + } else { + let names: js_sys::Array = get(kept, "names").dyn_into()?; + for name in names.iter() { + files.push(file_of(&call(&dir, "getFileHandle", &name).await?).await?); + } + } + Ok(files) +} + +/// Brings back the databases remembered at earlier visits that the browser still lets +/// the page read (nothing is read now: the page's reader reads them when opened); the +/// others wait for the user ([`waiting`], [`allow`]). Called once before the +/// interface starts. +pub async fn restore() { + if !supported() { + return; + } + for (path, kept) in super::idb::handles().await { + let path = PathBuf::from(path); + let mut granted = true; + for t in targets(&kept) { + let state = call(&t, "queryPermission", &read_mode()) + .await + .ok() + .and_then(|s| s.as_string()); + granted &= state.as_deref() == Some("granted"); + } + if !granted { + WAITING.with_borrow_mut(|w| w.insert(path, kept)); + continue; + } + match files_of(&kept).await { + Ok(files) => { + log::info!("remembered file read again: {}", path.display()); + super::vfs::put_opened(&path, files); + } + Err(e) => log::warn!("a remembered file is gone: {e:?}"), + } + } +} + +/// The browser remembers the database `path` and asks the user before it is read again. +pub fn waiting(path: &Path) -> bool { + WAITING.with_borrow(|w| w.contains_key(path)) +} + +/// Asks the browser to let the page read `path` again (its question to the user; soon +/// after the user's click). `then`: whether the database is back at its path. +pub fn allow(path: &Path, then: impl FnOnce(bool) + 'static) { + let Some(kept) = WAITING.with_borrow(|w| w.get(path).cloned()) else { + then(false); + return; + }; + let path = path.to_owned(); + // Asked now, all within the user's gesture. + let asked: Vec<_> = targets(&kept) + .iter() + .map(|t| start(t, "requestPermission", &read_mode())) + .collect(); + wasm_bindgen_futures::spawn_local(async move { + let mut granted = true; + for a in asked { + granted &= match a { + Ok(p) => wasm_bindgen_futures::JsFuture::from(p) + .await + .ok() + .and_then(|s| s.as_string()) + .is_some_and(|s| s == "granted"), + Err(_) => false, + }; + } + let files = if granted { + files_of(&kept).await.ok() + } else { + None + }; + let back = files.is_some(); + if let Some(files) = files { + log::info!("remembered file allowed again: {}", path.display()); + WAITING.with_borrow_mut(|w| w.remove(&path)); + super::vfs::put_opened(&path, files); + } + then(back); + }); +} + +/// The database `path` is no longer the library's: the browser's handles are let go. +pub fn forget(path: &Path) { + WAITING.with_borrow_mut(|w| w.remove(path)); + super::idb::delete_handle(&path.to_string_lossy()); +} diff --git a/apps/desktop/src/platform/web/storage.rs b/apps/desktop/src/platform/web/storage.rs new file mode 100644 index 0000000..b345c95 --- /dev/null +++ b/apps/desktop/src/platform/web/storage.rs @@ -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> = const { Cell::new(None) }; + static PERSISTED: Cell> = const { Cell::new(None) }; +} + +fn manager() -> Option { + Some(web_sys::window()?.navigator().storage()) +} + +fn number(o: &wasm_bindgen::JsValue, key: &str) -> Option { + 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 { + 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::().ok()) + .is_some_and(|b| b.value_of()), + None => false, + }; + PERSISTED.set(Some(granted)); + then(granted); + }); +} diff --git a/apps/desktop/src/platform/web/vfs.rs b/apps/desktop/src/platform/web/vfs.rs new file mode 100644 index 0000000..eee561c --- /dev/null +++ b/apps/desktop/src/platform/web/vfs.rs @@ -0,0 +1,236 @@ +//! The page's file tree: files by path, in memory. The program's data (`/config`, +//! `/data`, `/cache`) is written through to the browser's storage ([`super::idb`]) and +//! read from it at the start ([`load`]); the rest lives for the session. The user's +//! files are the browser's `File`s, not their contents: the page's reader reads them +//! (`super::import`), so a database's bytes never fill the page's memory. + +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::io; +use std::path::{Path, PathBuf}; + +use crate::platform::fs::Meta; + +pub const CONFIG: &str = "/config"; +pub const DATA: &str = "/data"; +pub const CACHE: &str = "/cache"; +pub const EXAMPLES: &str = "/examples"; +pub const OPENED: &str = "/opened"; + +/// The folders kept in the browser's storage. +const KEPT: [&str; 3] = [CONFIG, DATA, CACHE]; + +struct Entry { + content: Content, + modified_ms: u64, + readonly: bool, +} + +enum Content { + Bytes(Vec), + /// A file the user gave the page: the browser reads it when asked. + File(web_sys::File), +} + +impl Content { + fn len(&self) -> u64 { + match self { + Content::Bytes(b) => b.len() as u64, + Content::File(f) => f.size() as u64, + } + } +} + +thread_local! { + static FILES: RefCell> = const { RefCell::new(BTreeMap::new()) }; + /// The number of the last file opened (each gets a folder of its own; numbered from + /// the visit's start time, so that a file of an earlier visit keeps its own). + static OPENED_COUNT: RefCell = const { RefCell::new(0) }; +} + +fn now_ms() -> u64 { + js_sys::Date::now() as u64 +} + +fn kept(path: &Path) -> bool { + KEPT.iter().any(|k| path.starts_with(k)) +} + +fn not_found(path: &Path) -> io::Error { + io::Error::new( + io::ErrorKind::NotFound, + format!("{}: no such file", path.display()), + ) +} + +/// Takes in what the browser's storage keeps; called once before the interface starts. +pub async fn load() { + let stored = super::idb::load_all().await; + FILES.with_borrow_mut(|files| { + for (path, bytes) in stored { + files.insert( + PathBuf::from(path), + Entry { + content: Content::Bytes(bytes), + modified_ms: 0, + readonly: false, + }, + ); + } + }); +} + +/// The file's bytes; a user's file is read by the page's reader instead +/// ([`source`]). +pub fn read(path: &Path) -> io::Result> { + FILES.with_borrow( + |files| match &files.get(path).ok_or_else(|| not_found(path))?.content { + Content::Bytes(b) => Ok(b.clone()), + Content::File(_) => Err(io::Error::new( + io::ErrorKind::Unsupported, + "the user's file is read by the page's reader", + )), + }, + ) +} + +/// The file for the page's reader: its bytes (a `Uint8Array`) or the user's `File`. +pub fn source(path: &Path) -> io::Result { + FILES.with_borrow(|files| { + Ok( + match &files.get(path).ok_or_else(|| not_found(path))?.content { + Content::Bytes(b) => js_sys::Uint8Array::from(b.as_slice()).into(), + Content::File(f) => f.clone().into(), + }, + ) + }) +} + +pub fn meta(path: &Path) -> io::Result { + FILES.with_borrow(|files| { + files + .get(path) + .map(|e| Meta { + len: e.content.len(), + modified_ms: e.modified_ms, + readonly: e.readonly, + }) + .ok_or_else(|| not_found(path)) + }) +} + +pub fn write(path: &Path, bytes: Vec) -> io::Result<()> { + let keep = kept(path); + FILES.with_borrow_mut(|files| { + if files.get(path).is_some_and(|e| e.readonly) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("{}: only read", path.display()), + )); + } + if keep { + super::idb::put(path.to_string_lossy().into_owned(), bytes.clone()); + } + files.insert( + path.to_owned(), + Entry { + content: Content::Bytes(bytes), + modified_ms: now_ms(), + readonly: false, + }, + ); + Ok(()) + }) +} + +pub fn remove(path: &Path) -> io::Result<()> { + FILES.with_borrow_mut(|files| { + files.remove(path).ok_or_else(|| not_found(path))?; + if kept(path) { + super::idb::delete(path.to_string_lossy().into_owned()); + } + Ok(()) + }) +} + +/// The files right in the folder `dir`. +pub fn list(dir: &Path) -> Vec { + FILES.with_borrow(|files| { + files + .keys() + .filter(|p| p.parent() == Some(dir)) + .cloned() + .collect() + }) +} + +/// A database the user gave the page (chosen, dropped, found in a chosen folder): +/// its files (its own first: a ChessBase database's `.cbh`, then its other files), +/// kept for the session, only read, in a folder of their own; the path of the first. +pub fn add_opened(files: Vec) -> PathBuf { + let n = OPENED_COUNT.with_borrow_mut(|n| { + *n = (*n + 1).max(now_ms()); + *n + }); + let path = Path::new(OPENED) + .join(n.to_string()) + .join(files.first().map(name_of).unwrap_or_default()); + put_opened(&path, files); + path +} + +/// A database of an earlier visit the browser let the page read again, at its old +/// path (its other files beside it). +pub fn put_opened(path: &Path, files: Vec) { + let dir = path.parent().unwrap_or(Path::new(OPENED)).to_owned(); + FILES.with_borrow_mut(|entries| { + for (i, f) in files.into_iter().enumerate() { + let at = if i == 0 { + path.to_owned() + } else { + dir.join(name_of(&f)) + }; + entries.insert( + at, + Entry { + content: Content::File(f), + modified_ms: now_ms(), + readonly: true, + }, + ); + } + }); +} + +/// A file's name, not a path (a browser gives no folders; this makes sure). +fn name_of(f: &web_sys::File) -> String { + let name = f.name(); + name.rsplit(['/', '\\']).next().unwrap_or(&name).to_owned() +} + +/// The files of the database `path` for the page's reader: (name, [`source`]); a +/// ChessBase database's `.cbh` with the files of its name beside it. +pub fn database_files(path: &Path) -> io::Result> { + let name = |p: &Path| { + p.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default() + }; + let mut out = vec![(name(path), source(path)?)]; + let cbh = path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("cbh")); + if cbh && let Some(dir) = path.parent() { + let stem = |p: &Path| { + p.file_stem() + .map(|s| s.to_string_lossy().to_lowercase()) + .unwrap_or_default() + }; + for p in list(dir) { + if p != path && stem(&p) == stem(path) { + out.push((name(&p), source(&p)?)); + } + } + } + Ok(out) +} diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 01749fc..1c8e8fc 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -4,7 +4,8 @@ use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; +use web_time::Instant; use chess_core::shakmaty::{Chess, Color, Move, Position}; use serde::{Deserialize, Serialize}; @@ -457,6 +458,27 @@ struct Request { pause: Duration, } +/// The engine judging a game (Stockfish at `exe`), waking `ctx` with its answers. +/// A browser starts no engine processes: there is no judge there, and the game goes +/// without resignations, as when the engine does not start. +pub fn start_judge(exe: crate::engines::EngineLocation, ctx: &egui::Context) -> Option { + #[cfg(not(web))] + { + let crate::engines::EngineLocation::Program(exe) = exe; + let ctx = ctx.clone(); + Some(Judge::start( + uci::EngineConfig::new(exe), + Vec::new(), + Box::new(move || ctx.request_repaint()), + )) + } + #[cfg(web)] + { + let _ = (exe, ctx); + None + } +} + /// What computes the opponent's moves. enum Worker { /// Maia in a thread of her own; her error, if loading failed. @@ -466,7 +488,8 @@ enum Worker { generation: u64, error: Arc>>, }, - /// Rodent, a UCI engine (the shared crate's player). + /// Rodent, a UCI engine (the shared crate's player): a process, not in a browser. + #[cfg(not(web))] Rodent(::play::rodent::RodentPlayer), } @@ -551,6 +574,7 @@ impl Opponent { pause, }); } + #[cfg(not(web))] Worker::Rodent(player) => { if let (Some(pos), Some(now)) = (engine_pos, positions.last().cloned()) { player.ask(pos, now, pause); @@ -561,6 +585,7 @@ impl Opponent { /// Rodent (`exe` in its folder) playing in `style` at `uci_elo` (none: full /// strength), with its opening book. + #[cfg(not(web))] pub fn start_rodent( exe: std::path::PathBuf, style: String, @@ -585,10 +610,28 @@ impl Opponent { } } + /// An opponent that did not start, for `why`: the game ends at once with it (in a + /// browser, which starts no engine processes, Rodent). + #[cfg(web)] + pub fn not_started(why: String) -> Opponent { + let (tx, _) = channel(); + let (_, rx) = channel(); + Opponent { + worker: Worker::Maia { + tx, + rx, + generation: 0, + error: Arc::new(Mutex::new(Some(why))), + }, + thinking: false, + } + } + /// Forgets what was asked (its answer will be dropped). pub fn forget(&mut self) { match &mut self.worker { Worker::Maia { generation, .. } => *generation += 1, + #[cfg(not(web))] Worker::Rodent(player) => player.forget(), } self.thinking = false; @@ -607,6 +650,7 @@ impl Opponent { } } } + #[cfg(not(web))] Worker::Rodent(player) => { if let Some((m, pause)) = player.answer() { self.thinking = false; @@ -618,13 +662,13 @@ impl Opponent { } pub fn failed(&self) -> Option { - use ::play::rodent::Failure; match &self.worker { Worker::Maia { error, .. } => error.lock().ok().and_then(|g| g.clone()), + #[cfg(not(web))] Worker::Rodent(player) => player.failure().map(|f| match f { - Failure::Start(e) => start_failure(&e), - Failure::Stopped => tr("it stopped while playing").to_owned(), - Failure::Search(e) => e, + ::play::rodent::Failure::Start(e) => start_failure(&e), + ::play::rodent::Failure::Stopped => tr("it stopped while playing").to_owned(), + ::play::rodent::Failure::Search(e) => e, }), } } diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index dd0bdbc..abb99e0 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -15,7 +15,7 @@ use chess_import::Database; use chess_import::chessbase::base::{Side, fold}; use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Sense, Ui, vec2}; use egui_extras::{Column, TableBuilder}; -use game_review::{JobEvent, JobFailure, JobSettings, Judgement}; +use game_review::{JobEvent, JobSettings, Judgement}; use prep::{ BookExit, BookOptions, Candidate, ErrorCounts, GameInfo, Options, Player, PositionCache, PrepReport, Tally, @@ -946,13 +946,10 @@ struct ListRow { event: String, } -enum JobMsg { - Event(JobEvent), - Done, - Failed(String), -} +use crate::review::JobMsg; struct EngineJob { + runner: crate::review::JobRunner, rx: Receiver, cancel: Arc, total: usize, @@ -1972,35 +1969,24 @@ impl PrepScreen { let total = targets.len(); let job_settings = JobSettings::new(review::processes(), None); let processes = job_settings.processes; - let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone()); - let spawned = std::thread::Builder::new() - .name("prep-engine".into()) - .spawn(move || { - let result = game_review::run( - review::engine_config(&path), - &job_settings, - targets, - &cancel_w, - &mut |e| { - let _ = tx.send(JobMsg::Event(e)); - ctx_w.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); - ctx_w.request_repaint(); - }); - if let Err(e) = spawned { - self.error = Some(e.to_string()); - return; - } + let spawned = review::spawn_job( + "prep-engine", + path, + job_settings, + targets, + cancel.clone(), + tx, + ctx.clone(), + ); + let runner = match spawned { + Ok(r) => r, + Err(e) => { + self.error = Some(e.to_string()); + return; + } + }; self.job = Some(EngineJob { + runner, rx, cancel, total, @@ -2019,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) => { diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index 6402e42..60baa28 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -33,13 +33,118 @@ pub enum ReportAction { Analyse, } -enum JobMsg { +/// What an engine job sends to the screen. +pub enum JobMsg { Event(JobEvent), Done, Failed(String), } +/// 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, + #[cfg(web)] + cancel: Arc, +} + +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, + engine: crate::engines::EngineLocation, + settings: JobSettings, + targets: Vec, + cancel: Arc, + tx: std::sync::mpsc::Sender, + ctx: egui::Context, +) -> std::io::Result { + #[cfg(not(web))] + { + let crate::engines::EngineLocation::Program(path) = engine; + std::thread::Builder::new() + .name(name.to_owned()) + .spawn(move || { + let result = game_review::run( + engine_config(&path), + &settings, + targets, + &cancel, + &mut |e| { + let _ = tx.send(JobMsg::Event(e)); + ctx.request_repaint(); + }, + ); + let _ = tx.send(job_end(result)); + ctx.request_repaint(); + }) + .map(|_| JobRunner {}) + } + #[cfg(web)] + { + let _ = name; + let crate::engines::EngineLocation::Worker(script) = engine; + let wake: Arc = Arc::new(move || ctx.request_repaint()); + game_review::Dispatcher::start(&script, &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, cancel: Arc, total: usize, @@ -70,9 +175,27 @@ fn cache_dir() -> Option { 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> { + 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, @@ -108,7 +231,13 @@ impl Review { /// Starts the engine job with the engine at `path` (ChessPenguin's Stockfish). `full` /// discards earlier results; otherwise only positions without an evaluation are /// analysed (all of them for a stale analysis). Returns false if there is nothing to do. - pub fn start(&mut self, game: &Game, path: &Path, full: bool, ctx: &egui::Context) -> bool { + pub fn start( + &mut self, + game: &Game, + engine: &crate::engines::EngineLocation, + full: bool, + ctx: &egui::Context, + ) -> bool { self.job = None; self.error = None; let targets = self.analysis.begin(game, full); @@ -119,30 +248,24 @@ impl Review { let cancel = Arc::new(AtomicBool::new(false)); let total = targets.len(); let settings = JobSettings::new(processes(), None); - let config = engine_config(path); - let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone()); - let spawned = std::thread::Builder::new() - .name("game-review".into()) - .spawn(move || { - let result = game_review::run(config, &settings, targets, &cancel_w, &mut |e| { - let _ = tx.send(JobMsg::Event(e)); - ctx_w.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); - ctx_w.request_repaint(); - }); - if let Err(e) = spawned { - self.error = Some(e.to_string()); - return false; - } + let spawned = spawn_job( + "game-review", + engine.clone(), + settings, + targets, + cancel.clone(), + tx, + ctx.clone(), + ); + 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, @@ -164,6 +287,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) => { @@ -221,7 +345,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()); } @@ -720,15 +844,10 @@ 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. -pub fn engine_config(path: &Path) -> uci::EngineConfig { +#[cfg(not(web))] +fn engine_config(path: &Path) -> uci::EngineConfig { uci::EngineConfig { nice: 10, ..uci::EngineConfig::new(path) diff --git a/apps/desktop/src/rodent4_download.rs b/apps/desktop/src/rodent4_download.rs index 63a104d..6138de4 100644 --- a/apps/desktop/src/rodent4_download.rs +++ b/apps/desktop/src/rodent4_download.rs @@ -8,7 +8,9 @@ use std::path::PathBuf; use std::sync::atomic::AtomicBool; -use crate::engine_download::{Asset, Download, Failure, Stage, already, disk, fetch}; +#[cfg(not(web))] +use crate::engine_download::fetch; +use crate::engine_download::{Asset, Download, Failure, Stage, already, disk}; use ::play::rodent::{BOOK_NAMES, FILES, file_url}; /// This platform's build: the release of our builds it is in (the macOS build of @@ -104,10 +106,18 @@ pub fn remove() -> std::io::Result<()> { } } +#[cfg(not(web))] pub fn start(ctx: &egui::Context) -> Download { Download::spawn(ctx, total(), run) } +/// A browser downloads no engine programs. +#[cfg(web)] +pub fn start(_ctx: &egui::Context) -> Download { + Download::unsupported() +} + +#[cfg(not(web))] fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let (tag, bin) = binary().ok_or(Failure::Unsupported)?; let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; diff --git a/apps/desktop/src/rodent_download.rs b/apps/desktop/src/rodent_download.rs index c7a6dbc..6df8893 100644 --- a/apps/desktop/src/rodent_download.rs +++ b/apps/desktop/src/rodent_download.rs @@ -7,7 +7,9 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::AtomicBool; -use crate::engine_download::{Asset, Download, Failure, Stage, disk, fetch}; +#[cfg(not(web))] +use crate::engine_download::fetch; +use crate::engine_download::{Asset, Download, Failure, Stage, disk}; const TAG: &str = "Rodent_v_1.2"; @@ -77,10 +79,18 @@ pub fn remove() -> std::io::Result<()> { } } +#[cfg(not(web))] pub fn start(ctx: &egui::Context) -> Download { Download::spawn(ctx, ARCHIVE.size, run) } +/// A browser downloads no engine programs. +#[cfg(web)] +pub fn start(_ctx: &egui::Context) -> Download { + Download::unsupported() +} + +#[cfg(not(web))] fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let bin = binary().ok_or(Failure::Unsupported)?; let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; @@ -108,6 +118,7 @@ fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result result } +#[cfg(not(web))] /// Takes this platform's engine and the folders it reads (personalities, nets, books) /// out of the archive; the other builds and the pictures of the manual stay out. fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result { @@ -152,6 +163,7 @@ fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result { /// Starts the engine once from its folder and waits for its name: it runs here (the /// release needs AVX2: an older processor fails this). +#[cfg(not(web))] pub(crate) fn check_runs(exe: &Path) -> Result<(), Failure> { use std::io::Write; let mut cmd = std::process::Command::new(exe); diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index c2d96f5..15eec29 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -53,13 +53,23 @@ impl EngineConfig { /// Executable to start; `None` if ChessPenguin's Stockfish is neither bundled nor /// downloaded yet (it is offered for download then). - pub fn executable(&self) -> Option { + pub fn executable(&self) -> Option { if self.builtin { crate::engines::own_stockfish() } else { - Some(self.path.clone()) + // A browser runs no engine programs: there are none but its own. + #[cfg(not(web))] + return Some(crate::engines::EngineLocation::Program(self.path.clone())); + #[cfg(web)] + None } } + + /// 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 { + self.executable().is_some_and(|l| l.present()) + } } /// Piece animation, with Lichess's durations. @@ -222,14 +232,12 @@ impl Default for Settings { impl Settings { pub fn config_dir() -> Option { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") - .map(|d| d.config_dir().to_path_buf()) + crate::platform::config_dir() } /// `~/.cache/chesspenguin` (derived data that can be deleted at any time). pub fn cache_dir() -> Option { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") - .map(|d| d.cache_dir().to_path_buf()) + crate::platform::cache_dir() } fn file() -> Option { @@ -241,7 +249,7 @@ impl Settings { return Self::first_start(); }; migrate_legacy_config(&path); - match std::fs::read(&path) { + match crate::platform::fs::read(&path) { Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| { eprintln!( "settings: cannot parse {}: {e}; using defaults", @@ -283,7 +291,7 @@ impl Settings { /// Copies settings of the pre-rename build (`chessbase-linux`) once, if the new file is absent. fn migrate_legacy_config(new_file: &Path) { - if new_file.exists() { + if crate::platform::fs::exists(new_file) { return; } let legacy = directories::ProjectDirs::from("org", "chessbase-linux", "chessbase-linux") @@ -297,14 +305,7 @@ fn migrate_legacy_config(new_file: &Path) { /// Writes via a temp file in the same directory and renames over the target. pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension(format!("tmp{}", std::process::id())); - std::fs::write(&tmp, bytes)?; - std::fs::rename(&tmp, path).inspect_err(|_| { - let _ = std::fs::remove_file(&tmp); - }) + crate::platform::fs::write_atomic(path, bytes) } #[cfg(test)] diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index 19bf50f..ca52add 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -15,10 +15,20 @@ 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). DownloadEngine, @@ -29,10 +39,13 @@ pub enum SettingsAction { /// The active engine (or its options) changed; a running analysis should restart. EngineChanged, /// Ask now whether a newer version is out. + #[cfg(not(web))] CheckUpdates, /// Choose the folder for new databases. + #[cfg(not(web))] PickBaseFolder, /// Open the update window. + #[cfg(not(web))] OpenUpdate, } @@ -86,7 +99,11 @@ impl SettingsWindow { ui.selectable_value(&mut self.tab, Tab::Board, tr("Board & pieces")); ui.selectable_value(&mut self.tab, Tab::Sound, tr("Sound")); ui.selectable_value(&mut self.tab, Tab::Interface, tr("Interface")); - ui.selectable_value(&mut self.tab, Tab::Translation, tr("Translation")); + 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(); @@ -94,40 +111,19 @@ 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) = (self.update_status.clone(), self.update_available.clone()); about_tab(ui, s.language, |ui| { - // Updates, right under the version. - ui.add_space(4.0); - ui.horizontal_wrapped(|ui| { - match (&available, &status) { - (Some(v), _) => { - let label = RichText::new(trf( - "⬆ Update to {v}…", - &[("v", v)], - )) - .color(ui.visuals().hyperlink_color); - if ui.button(label).clicked() { - actions.push(SettingsAction::OpenUpdate); - } - } - (None, Some(st)) => { - ui.label(RichText::new(st).weak()); - } - (None, None) => {} - } - if ui.button(tr("Check now")).clicked() { - actions.push(SettingsAction::CheckUpdates); - } - }); - changed |= ui - .checkbox(&mut s.check_updates, tr("Check for updates at start")) - .on_hover_text(tr( - "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", - )) - .changed(); + // Updates, right under the version (the web version is + // always the latest: a reload brings it). + #[cfg(not(web))] + updates(ui, s, &status, &available, &mut actions, &mut changed); + #[cfg(web)] + let _ = (ui, &status, &available); }); } Tab::Interface => { @@ -171,16 +167,19 @@ impl SettingsWindow { RichText::new(tr("Written as the annotator of the games you add")) .weak(), ); + // A browser has no folders for databases. + #[cfg(not(web))] ui.horizontal(|ui| { ui.label(tr("Folder for new databases:")); let dir = crate::own_db::default_base_dir(s.new_database_dir.as_deref()); // Short, under the home folder; the whole path on hover. - let home = directories::UserDirs::new() - .map(|u| u.home_dir().to_path_buf()); - let short = match home.as_ref().and_then(|h| dir.strip_prefix(h).ok()) - { - Some(rest) => format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()), + let home = + directories::UserDirs::new().map(|u| u.home_dir().to_path_buf()); + let short = match home.as_ref().and_then(|h| dir.strip_prefix(h).ok()) { + Some(rest) => { + format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()) + } None => dir.display().to_string(), }; ui.label(RichText::new(short).weak()) @@ -244,6 +243,8 @@ impl SettingsWindow { { actions.push(SettingsAction::DownloadEngine); } + // A browser has no engine programs. + #[cfg(not(web))] if ui.button(tr("Choose engine file…")).clicked() { actions.push(SettingsAction::AddEngine); } @@ -297,7 +298,7 @@ impl SettingsWindow { ) .on_hover_text(p.display().to_string()); } else if let Some(p) = crate::engine_download::installed() { - let mb = std::fs::metadata(&p).map_or(0, |m| m.len() / 1_000_000); + let mb = crate::engine_download::installed_mb(); ui.label( RichText::new(trf( "Downloaded by ChessPenguin · {mb} MB", @@ -306,7 +307,7 @@ impl SettingsWindow { .small() .weak(), ) - .on_hover_text(p.display().to_string()); + .on_hover_text(p.to_string()); } else { ui.horizontal(|ui| { ui.label( @@ -332,9 +333,7 @@ impl SettingsWindow { let mut answer = None; let modal = egui::Modal::new(egui::Id::new("remove_engine")).show(ui.ctx(), |ui| { ui.set_width(360.0); - let mb = crate::engine_download::installed() - .and_then(|p| std::fs::metadata(p).ok()) - .map_or(0, |m| m.len() / 1_000_000); + let mb = crate::engine_download::installed_mb(); ui.label(trf( "Remove Stockfish 19? This frees {mb} MB. You can download it again at any time.", &[("mb", &mb)], @@ -382,9 +381,8 @@ impl SettingsWindow { ui.label(RichText::new(tr("Found on this computer:")).strong()); for cfg in found { ui.horizontal(|ui| { - let path = cfg.executable().unwrap_or_default(); - ui.label(&cfg.name) - .on_hover_text(path.display().to_string()); + let path = cfg.executable().map(|l| l.to_string()).unwrap_or_default(); + ui.label(&cfg.name).on_hover_text(path); if ui.button(tr("Add")).clicked() { s.engines.push(cfg); if s.active_engine.is_none() { @@ -424,6 +422,8 @@ impl SettingsWindow { }); } ui.add_space(6.0); + // A browser has no engine programs. + #[cfg(not(web))] ui.horizontal(|ui| { if ui .add_enabled( @@ -767,3 +767,104 @@ fn sound_tab(ui: &mut Ui, s: &mut Settings, actions: &mut Vec, c }); }); } + +/// Updates in the About tab: the version out, «Check now», the check at start. +#[cfg(not(web))] +fn updates( + ui: &mut Ui, + s: &mut Settings, + status: &Option, + available: &Option, + actions: &mut Vec, + changed: &mut bool, +) { + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + match (available, status) { + (Some(v), _) => { + let label = RichText::new(trf("⬆ Update to {v}…", &[("v", v)])) + .color(ui.visuals().hyperlink_color); + if ui.button(label).clicked() { + actions.push(SettingsAction::OpenUpdate); + } + } + (None, Some(st)) => { + ui.label(RichText::new(st).weak()); + } + (None, None) => {} + } + if ui.button(tr("Check now")).clicked() { + actions.push(SettingsAction::CheckUpdates); + } + }); + *changed |= ui + .checkbox(&mut s.check_updates, tr("Check for updates at start")) + .on_hover_text(tr( + "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", + )) + .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) { + 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(), + ); +} diff --git a/apps/desktop/src/sound.rs b/apps/desktop/src/sound.rs index cb10a76..9474fb1 100644 --- a/apps/desktop/src/sound.rs +++ b/apps/desktop/src/sound.rs @@ -1,14 +1,19 @@ -//! Sound playback on a dedicated thread; missing audio devices are tolerated silently. +//! Sound playback: on a computer on a dedicated thread (missing audio devices are +//! tolerated silently); in a browser by its audio elements, each sound's file made once. +#[cfg(not(web))] use std::io::Cursor; +#[cfg(not(web))] use std::sync::mpsc::{Sender, channel}; use crate::assets::{Sound, SoundSet, sound_bytes}; +#[cfg(not(web))] pub struct SoundPlayer { tx: Option>, } +#[cfg(not(web))] impl SoundPlayer { pub fn new() -> Self { let (tx, rx) = channel::<(SoundSet, Sound, f32)>(); @@ -50,3 +55,45 @@ impl SoundPlayer { } } } + +/// The sounds' files for the page's audio elements (`blob:` addresses), by the sound's +/// bytes (each sound is a file of its own). +#[cfg(web)] +pub struct SoundPlayer { + urls: std::cell::RefCell>, +} + +#[cfg(web)] +impl SoundPlayer { + pub fn new() -> Self { + Self { + urls: Default::default(), + } + } + + fn url(&self, bytes: &'static [u8]) -> Option { + let key = bytes.as_ptr() as usize; + if let Some(u) = self.urls.borrow().get(&key) { + return Some(u.clone()); + } + let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); + let opts = web_sys::BlobPropertyBag::new(); + opts.set_type("audio/ogg"); + let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).ok()?; + let url = web_sys::Url::create_object_url_with_blob(&blob).ok()?; + self.urls.borrow_mut().insert(key, url.clone()); + Some(url) + } + + /// Plays the sound; a browser that cannot (no audio, not allowed yet) stays silent. + pub fn play(&self, set: SoundSet, sound: Sound, volume: f32) { + let Some(url) = self.url(sound_bytes(set, sound)) else { + return; + }; + if let Ok(audio) = web_sys::HtmlAudioElement::new_with_src(&url) { + audio.set_volume(f64::from(volume.clamp(0.0, 1.0))); + // The promise fails when the page may not play yet: nothing to do then. + let _ = audio.play(); + } + } +} diff --git a/apps/desktop/src/translate.rs b/apps/desktop/src/translate.rs index a4a0d2a..ad63370 100644 --- a/apps/desktop/src/translate.rs +++ b/apps/desktop/src/translate.rs @@ -789,6 +789,7 @@ impl std::fmt::Display for Failure { } } +#[cfg(not(web))] pub fn agent(body_timeout: Duration) -> ureq::Agent { let config = ureq::Agent::config_builder() .user_agent(format!( @@ -883,6 +884,34 @@ impl Backend { } } +/// Why nothing is asked of a service in a browser: the web version has no machine +/// translation (its requests would block a thread the page does not have). +#[cfg(web)] +pub fn no_requests() -> Failure { + Failure::Offline("the web version makes no requests to translation services".into()) +} + +#[cfg(web)] +pub fn list_models(_base: &str, _key: Option<&str>, _local: bool) -> Result, Failure> { + Err(no_requests()) +} + +#[cfg(web)] +#[allow(clippy::too_many_arguments)] +fn chat( + _base: &str, + _key: Option<&str>, + _model: &str, + _json_mode: bool, + _local: bool, + _system: &str, + _user: &str, + _cancel: &AtomicBool, +) -> Result { + Err(no_requests()) +} + +#[cfg(not(web))] /// The models a key connection offers (`GET {base}/models`). pub fn list_models(base: &str, key: Option<&str>, local: bool) -> Result, Failure> { let mut req = agent(Duration::from_secs(30)).get(format!("{base}/models")); @@ -915,6 +944,7 @@ pub fn list_models(base: &str, key: Option<&str>, local: bool) -> Result Failure { if local { Failure::LocalDown @@ -939,6 +969,7 @@ fn status_failure(status: u16, body: &str, model: &str) -> Failure { } } +#[cfg(not(web))] #[allow(clippy::too_many_arguments)] fn chat( base: &str, @@ -1195,13 +1226,11 @@ impl Job { let cancel = Arc::new(AtomicBool::new(false)); let c = cancel.clone(); let ctx = ctx.clone(); - let _ = std::thread::Builder::new() - .name("translate".into()) - .spawn(move || { - run(&backend, target, &via, &context, texts, &c, &tx, &ctx); - let _ = tx.send(Event::Finished); - ctx.request_repaint(); - }); + let _ = crate::platform::spawn("translate", move || { + run(&backend, target, &via, &context, texts, &c, &tx, &ctx); + let _ = tx.send(Event::Finished); + ctx.request_repaint(); + }); Job { rx, cancel } } @@ -1601,7 +1630,7 @@ mod tests { ); let mut done = Vec::new(); let mut bad = Vec::new(); - let start = std::time::Instant::now(); + let start = web_time::Instant::now(); 'wait: while start.elapsed() < Duration::from_secs(20) { for e in job.poll() { match e { @@ -1653,7 +1682,7 @@ mod tests { texts.clone(), ); let mut done = Vec::new(); - let start = std::time::Instant::now(); + let start = web_time::Instant::now(); 'wait: while start.elapsed() < Duration::from_secs(20) { for e in job.poll() { match e { diff --git a/apps/desktop/src/translate_ui.rs b/apps/desktop/src/translate_ui.rs index e3d0698..fe85b0c 100644 --- a/apps/desktop/src/translate_ui.rs +++ b/apps/desktop/src/translate_ui.rs @@ -368,7 +368,7 @@ impl Hub { } let ok = c.result.is_ok(); if let Err(e) = &c.result { - crate::graphics::log(&format!("translation check via {}: {e}", s.service_id())); + crate::platform::log(&format!("translation check via {}: {e}", s.service_id())); } self.check_result = Some(c.result); let flow = self.resume || (self.setup_open && self.step == Step::Checking); @@ -1640,7 +1640,7 @@ impl GameTranslation { } } Event::Failed(f) => { - crate::graphics::log(&format!("translation via {}: {f}", self.job_service)); + crate::platform::log(&format!("translation via {}: {f}", self.job_service)); match f { Failure::PlanLimit => hub.chatgpt = ChatGptState::Limit, Failure::SignedOut => hub.chatgpt = ChatGptState::SignedOut, diff --git a/apps/desktop/src/viewed.rs b/apps/desktop/src/viewed.rs index 693a50d..9f3cf91 100644 --- a/apps/desktop/src/viewed.rs +++ b/apps/desktop/src/viewed.rs @@ -12,13 +12,12 @@ pub struct Viewed { impl Viewed { fn file() -> Option { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") - .map(|d| d.data_dir().join("viewed.json")) + crate::platform::data_dir().map(|d| d.join("viewed.json")) } pub fn load() -> Viewed { let games = Self::file() - .and_then(|p| std::fs::read(p).ok()) + .and_then(|p| crate::platform::fs::read(&p).ok()) .and_then(|b| serde_json::from_slice::>(&b).ok()) .unwrap_or_default(); Viewed { diff --git a/apps/web/Cargo.toml b/apps/web/Cargo.toml new file mode 100644 index 0000000..889099e --- /dev/null +++ b/apps/web/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "chesspenguin-web" +description = "ChessPenguin in a browser: the entry point of the web version (the interface is apps/desktop's)" +version.workspace = true +authors.workspace = true +repository.workspace = true +homepage.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish = false + +# Built for WebAssembly only (apps/web/build.sh); elsewhere the crate is empty. +[lib] +crate-type = ["cdylib"] + +[target.'cfg(target_family = "wasm")'.dependencies] +chesspenguin = { path = "../desktop" } +wasm-bindgen = "0.2.129" +wasm-bindgen-futures = "0.4" +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "UrlSearchParams"] } +log = "0.4" +eframe.workspace = true diff --git a/apps/web/build.sh b/apps/web/build.sh new file mode 100755 index 0000000..b17514a --- /dev/null +++ b/apps/web/build.sh @@ -0,0 +1,79 @@ +#!/bin/sh +# Builds the web version into a folder served as the site's /app/ (docs/dev/web.md): +# +# apps/web/build.sh [out-dir] (default: target/web/app) +# PROFILE=release apps/web/build.sh (the default profile is `web`: small, slower to build) +# +# Needs: the target wasm32-unknown-unknown (rustup target add wasm32-unknown-unknown), +# wasm-bindgen-cli of the version in Cargo.lock (cargo install wasm-bindgen-cli --version …; +# WASM_BINDGEN= points at another binary), python3. wasm-opt (binaryen) makes the program +# smaller when it is there. +set -eu + +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../.." && pwd) +out=${1:-$root/target/web/app} +profile=${PROFILE:-web} +bindgen=${WASM_BINDGEN:-wasm-bindgen} + +want=$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' "$root/Cargo.lock") +have=$("$bindgen" --version | awk '{ print $2 }') +if [ "$want" != "$have" ]; then + echo "wasm-bindgen $have, but Cargo.lock has $want: cargo install wasm-bindgen-cli --version $want" >&2 + exit 1 +fi + +cd "$root" +cargo build -p chesspenguin-web --target wasm32-unknown-unknown --profile "$profile" +wasm="$root/target/wasm32-unknown-unknown/$profile/chesspenguin_web.wasm" + +rm -rf "$out" +mkdir -p "$out" +"$bindgen" --target web --no-typescript --out-dir "$out" --out-name chesspenguin_web "$wasm" +if command -v wasm-opt >/dev/null 2>&1; then + wasm-opt -Os --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext \ + --enable-mutable-globals --enable-reference-types \ + "$out/chesspenguin_web_bg.wasm" -o "$out/chesspenguin_web_bg.wasm" +fi + +cp "$here/page/device.js" "$here/page/page.js" "$here/page/import-worker.js" "$out/" + +# The engine: Stockfish.js 19.0.1 (npm `stockfish`, GPL-3.0), its single-threaded build, +# checked against the registry's integrity (THIRD_PARTY_NOTICES.md). STOCKFISH_TGZ= points +# 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 +# The page's texts in the site's languages: the app_* keys and the shared ones it uses. +python3 -I - "$here/page/index.html" "$root/website/site/i18n" "$out/index.html" <<'PY' +import json, pathlib, sys +template, i18n, target = sys.argv[1], pathlib.Path(sys.argv[2]), sys.argv[3] +shared = ["btn_android", "and_light_title", "and_full_title", "and_requires", "next_android", + "copy_link", "link_copied", "email", "language"] +texts = {} +for f in sorted(i18n.glob("*.json")): + d = json.loads(f.read_text(encoding="utf-8")) + texts[f.stem] = {k: v for k, v in d.items() if k.startswith("app_") or k in shared} +page = pathlib.Path(template).read_text(encoding="utf-8") +blob = json.dumps(texts, ensure_ascii=False, separators=(",", ":")).replace("; what is checked is printed. +// +// node apps/web/check/app.mjs (app-dir: apps/web/build.sh's) +import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; + +const [appDir, outDir] = process.argv.slice(2).map((p) => resolve(p)); +const root = fileURLToPath(new URL('../../..', import.meta.url)); +mkdirSync(outDir, { recursive: true }); +let failures = 0; +const check = (ok, what) => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); + if (!ok) failures++; +}; +// Places of buttons in a 1400×860 window. +const DOWNLOAD = [Number(process.env.DOWNLOAD_X || 1263), Number(process.env.DOWNLOAD_Y || 24)]; +const E2 = [519, 703]; +const E4 = [519, 505]; +// The card of «Test games» on the shelf after a reload (the draft's strip above it) and +// «Allow reading» on its pane. +const TEST_CARD = [300, 88]; +const ALLOW = [70, 232]; + +const s = await session(appDir, 18766); +const { t } = s; +const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot()); +const text = () => t.evaluate(`document.getElementById('cp-device').innerText`); +const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); +try { + // ----- the page for phones and tablets, without the program ---------------------------- + await t.navigate(`${s.base}?phone=1&lang=ru`); + await sleep(800); + check(/ChessPenguin на телефоне и планшете/.test(await text()), 'the device page in Russian'); + check(/Всё равно открыть веб-версию/.test(await text()), 'with «open the web version anyway»'); + const wasm = await t.evaluate(`performance.getEntriesByType('resource').some(e => e.name.endsWith('.wasm'))`); + check(!wasm, 'the program is not downloaded on it'); + await shot('web-phone-ru.png'); + await t.navigate(`${s.base}?phone=1&lang=de`); + await sleep(500); + check(/auf Handy und Tablet/.test(await text()), 'the device page in German'); + await t.navigate(`${s.base}?phone=android&lang=ru`); + await sleep(800); + check(/Скачать для Android/.test(await text()), 'the Android variant'); + await t.navigate(`${s.base}?phone=ios&lang=en`); + await sleep(800); + check(/iPhone and iPad app is coming soon/.test(await text()), 'the iPhone and iPad variant'); + + // ----- the program ------------------------------------------------------------------------- + await t.navigate(`${s.base}?lang=en`); + await started(); + await sleep(2500); + check(true, `the program started in ${s.b.name}`); + await shot('web-1-library.png'); + + // Open a PGN by the button's shortcut: the browser's file chooser gets the file. + const pgn = join(s.b.profile, 'Test games.pgn'); + copyFileSync(join(root, 'examples/alekhine.pgn'), pgn); + await t.choose([pgn], () => t.key('o', ['ctrl'])); + await sleep(3000); + await shot('web-2-opened.png'); + + // Drop a file on the window. + const dropped = readFileSync(join(root, 'examples/classics.pgn'), 'utf8'); + await t.evaluate(`(() => { + const dt = new DataTransfer(); + dt.items.add(new File([${JSON.stringify(dropped)}], 'Dropped classics.pgn', { type: 'application/x-chess-pgn' })); + const c = document.getElementById('cp-canvas'); + for (const type of ['dragenter', 'dragover', 'drop']) + c.dispatchEvent(new DragEvent(type, { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 700, clientY: 400 })); + return true; + })()`); + await sleep(3000); + await shot('web-3-dropped.png'); + + // A game from the table (double click), its moves on the board. + await t.click(300, 322, { double: true }); + await sleep(1500); + await shot('web-4-game.png'); + await t.key('right', [], 12); + await sleep(800); + await shot('web-5-moves.png'); + + // Download the PGN of the game (the header's button). + await t.click(...DOWNLOAD); + await sleep(2500); + const files = existsSync(s.b.downloads) ? readdirSync(s.b.downloads).filter((f) => f.endsWith('.pgn')) : []; + check(files.length === 1, `a PGN downloaded: ${files.join(', ') || 'none'}`); + if (files.length) { + const body = readFileSync(join(s.b.downloads, files[0]), 'utf8'); + check(/\[White "/.test(body) && /1\. /.test(body), 'the download is the game in PGN'); + } + + // The browser's Back is «← Library». + await t.evaluate(`history.back()`); + await sleep(1500); + await shot('web-6-back.png'); + check(await t.evaluate(`history.state === null || !history.state.cpGame`), 'Back left the game for the library'); + + // A move on the board of a new game (Ctrl+N; N in a browser): e2–e4 by two clicks. + await t.key('n'); + await sleep(1200); + await t.click(...E2); + await sleep(300); + await t.click(...E4); + await sleep(1000); + await shot('web-8-e4.png'); + + // An unsaved game: the browser asks before the page is left, and its draft is kept. + check(await t.evaluate(`typeof window.onbeforeunload === 'function'`), 'unsaved: the browser asks before leaving'); + await sleep(1500); + const draft = () => t.evaluate(`new Promise((ok) => { + const q = indexedDB.open('chesspenguin'); + q.onsuccess = () => { + const r = q.result.transaction('files').objectStore('files').get('/data/draft.json'); + r.onsuccess = () => ok(r.result ? JSON.parse(new TextDecoder().decode(r.result)).pgn : ''); + }; + q.onerror = () => ok(''); + })`); + check(/1\. e4/.test(await draft()), 'the draft of the unsaved game is kept'); + + // The settings and the shelf after a reload (the browser's storage). The question on + // leaving is answered «Leave». + await t.evaluate(`(window.onbeforeunload = null, true)`); + await t.navigate(`${s.base}?lang=en`); + await started(); + await sleep(2500); + await shot('web-9-reloaded.png'); + check(/1\. e4/.test(await draft()), 'the draft is there after the reload (offered over the library)'); + if (await t.evaluate(`typeof window.showOpenFilePicker === 'function'`)) { + // Chrome, Edge: the file chosen before the reload is read again by itself. + check(s.logs.some((l) => /remembered file read again: .*Test games\.pgn/.test(l)), 'the chosen file is remembered (File System Access)'); + // When the browser asks first (its permission not kept): the card offers «Allow + // reading», the browser's question is answered «Allow», the file is read. + await t.beforeLoad(`FileSystemHandle.prototype.queryPermission = async () => 'prompt'; + FileSystemHandle.prototype.requestPermission = async () => 'granted';`); + await t.navigate(`${s.base}?lang=en`); + await started(); + await sleep(2500); + await t.click(...TEST_CARD); + await sleep(1500); + await shot('web-10-allow.png'); + await t.click(...ALLOW); + await sleep(2500); + await shot('web-11-allowed.png'); + check(s.logs.some((l) => /remembered file allowed again: .*Test games\.pgn/.test(l)), '«Allow reading» reads the remembered file again'); + } +} finally { + await s.stop(); +} +for (const e of s.errors) console.log('console:', e); +check(s.errors.length === 0, 'no panic or error in the console'); +console.log(failures ? `${failures} failed` : 'all ok'); +process.exit(failures ? 1 : 0); diff --git a/apps/web/check/bidi.mjs b/apps/web/check/bidi.mjs new file mode 100644 index 0000000..c73a929 --- /dev/null +++ b/apps/web/check/bidi.mjs @@ -0,0 +1,78 @@ +// A minimal WebDriver BiDi client for headless Firefox (Node 22+: global WebSocket). +// Used by the web checks (docs/dev/web.md, «Проверки»); no windows are opened. + +export async function connect(port) { + const ws = new WebSocket(`ws://127.0.0.1:${port}/session`); + let id = 0; + const pending = new Map(); + const listeners = []; + ws.onmessage = (m) => { + const d = JSON.parse(m.data); + if (d.id && pending.has(d.id)) { + const p = pending.get(d.id); + pending.delete(d.id); + if (d.type === 'error') p.rej(new Error(`${d.error}: ${d.message}`)); + else p.res(d.result); + } else if (d.method) { + for (const l of listeners) l(d.method, d.params); + } + }; + await new Promise((res, rej) => { + ws.onopen = res; + ws.onerror = () => rej(new Error('cannot connect to Firefox')); + }); + const send = (method, params) => + new Promise((res, rej) => { + const i = ++id; + pending.set(i, { res, rej }); + ws.send(JSON.stringify({ id: i, method, params })); + }); + await send('session.new', { capabilities: {} }); + return { + send, + on: (f) => listeners.push(f), + close: async () => { + await send('session.end', {}).catch(() => {}); + ws.close(); + }, + }; +} + +export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// A tab of `width`×`height` CSS pixels with the console forwarded to `log`. +export async function tab(b, width, height, log = console.log) { + await b.send('session.subscribe', { events: ['log.entryAdded'] }); + b.on((method, p) => { + if (method === 'log.entryAdded') log(`[${p.level}] ${p.text}`); + }); + const { context } = await b.send('browsingContext.create', { type: 'tab' }); + await b.send('browsingContext.setViewport', { context, viewport: { width, height } }); + const evaluate = async (expression) => { + const r = await b.send('script.evaluate', { + expression, + target: { context }, + awaitPromise: true, + }); + if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed'); + return r.result?.value; + }; + return { + context, + evaluate, + navigate: (url) => b.send('browsingContext.navigate', { context, url, wait: 'complete' }), + screenshot: async () => + Buffer.from((await b.send('browsingContext.captureScreenshot', { context })).data, 'base64'), + actions: (actions) => b.send('input.performActions', { context, actions }), + // Waits until `expression` is truthy (polled), or throws after `ms`. + waitFor: async (expression, ms = 10000) => { + const end = Date.now() + ms; + for (;;) { + const v = await evaluate(expression).catch(() => undefined); + if (v) return v; + if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`); + await sleep(100); + } + }, + }; +} diff --git a/apps/web/check/browser.mjs b/apps/web/check/browser.mjs new file mode 100644 index 0000000..45ae52a --- /dev/null +++ b/apps/web/check/browser.mjs @@ -0,0 +1,296 @@ +// One way to drive a headless browser for the web checks: Firefox over WebDriver BiDi +// (firefox.mjs, bidi.mjs) or Chromium / Chrome for Testing over the DevTools protocol. +// The browser: CP_BROWSER=firefox (default) | chromium, the Chromium binary in +// CP_CHROME. No window is ever shown; the browser is stopped by its PID. +// +// const b = await open(port); const t = await b.tab(1400, 860, log); +// t.navigate(url) · t.evaluate(js) · t.waitFor(js, ms) · t.screenshot() +// t.click(x, y, {double, right}) · t.key(key, mods, times) · t.setFiles(inputId, paths) +// t.choose(paths, open): the user chooses the files in the dialog open() brings up +// t.chooseFolder(dir, open): … the folder +// t.beforeLoad(js): js runs in every page loaded later, before its scripts +import { spawn } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, join } from 'node:path'; +import { launch as launchFirefox } from './firefox.mjs'; +import { sleep, tab as bidiTab } from './bidi.mjs'; + +// WebDriver key values (BiDi) and their DevTools descriptions. +const KEYS = { + ctrl: { bidi: '', key: 'Control', code: 'ControlLeft', vk: 17, mod: 2 }, + shift: { bidi: '', key: 'Shift', code: 'ShiftLeft', vk: 16, mod: 8 }, + alt: { bidi: '', key: 'Alt', code: 'AltLeft', vk: 18, mod: 1 }, + esc: { bidi: '', key: 'Escape', code: 'Escape', vk: 27 }, + enter: { bidi: '', key: 'Enter', code: 'Enter', vk: 13, text: '\r' }, + right: { bidi: '', key: 'ArrowRight', code: 'ArrowRight', vk: 39 }, + left: { bidi: '', key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 }, +}; + +function keyOf(k) { + if (KEYS[k]) return KEYS[k]; + if (k === ',') return { bidi: ',', key: ',', code: 'Comma', vk: 188, text: ',' }; + if (/^[0-9]$/.test(k)) return { bidi: k, key: k, code: `Digit${k}`, vk: 48 + Number(k), text: k }; + return { bidi: k, key: k, code: `Key${k.toUpperCase()}`, vk: k.toUpperCase().charCodeAt(0), text: k }; +} + +const waitFor = (evaluate) => async (expression, ms = 10000) => { + const end = Date.now() + ms; + for (;;) { + const v = await evaluate(expression).catch(() => undefined); + if (v) return v; + if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`); + await sleep(100); + } +}; + +// ----- Firefox -------------------------------------------------------------------------- + +async function firefox(port) { + const ff = await launchFirefox(port); + return { + name: 'firefox', + profile: ff.profile, + downloads: ff.downloads, + stop: ff.stop, + tab: async (width, height, log) => { + const t = await bidiTab(ff.browser, width, height, log); + const evaluate = async (expression) => { + const r = await ff.browser.send('script.evaluate', { + expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, + target: { context: t.context }, + awaitPromise: true, + }); + if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed'); + return JSON.parse(r.result.value); + }; + return { + evaluate, + waitFor: waitFor(evaluate), + navigate: t.navigate, + screenshot: t.screenshot, + // `js` runs in every page loaded from now on, before the page's own scripts. + beforeLoad: (js) => ff.browser.send('script.addPreloadScript', { functionDeclaration: `() => { ${js} }`, contexts: [t.context] }), + click: async (x, y, { double = false, right = false } = {}) => { + const acts = [{ type: 'pointerMove', x, y }]; + for (let i = 0; i < (double ? 2 : 1); i++) { + acts.push({ type: 'pointerDown', button: right ? 2 : 0 }, { type: 'pointerUp', button: right ? 2 : 0 }); + } + await t.actions([{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]); + }, + key: async (key, mods = [], times = 1) => { + const m = mods.map((x) => KEYS[x].bidi); + const v = keyOf(key).bidi; + const acts = [...m.map((value) => ({ type: 'keyDown', value })), { type: 'keyDown', value: v }, { type: 'keyUp', value: v }, ...[...m].reverse().map((value) => ({ type: 'keyUp', value }))]; + for (let i = 0; i < times; i++) await t.actions([{ type: 'key', id: 'kb', actions: acts }]); + }, + setFiles: async (id, files) => { + const node = await ff.browser.send('script.evaluate', { + expression: `document.getElementById(${JSON.stringify(id)})`, target: { context: t.context }, awaitPromise: false, + }); + await ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: node.result.sharedId }, files }); + }, + // The user chooses `files` in the dialog `open()` brings up (the page's file input). + async choose(files, open) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); + await this.setFiles('cp-open-files', files); + }, + // The user chooses the folder `dir` (the page's folder input, webkitdirectory). + // WebDriver gives such an input no folder in Firefox ("Is directory"): the + // folder's own files are given, as the browser would give them. + async chooseFolder(dir, open) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000); + const files = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => join(dir, e.name)); + await this.setFiles('cp-open-folder', files); + }, + }; + }, + }; +} + +// ----- Chromium (DevTools protocol) ----------------------------------------------------------- + +async function chromium(port) { + const binary = process.env.CP_CHROME; + if (!binary) throw new Error('CP_CHROME: the Chromium / Chrome for Testing binary'); + const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-chrome-')); + const downloads = join(profile, 'downloads'); + mkdirSync(downloads, { recursive: true }); + const proc = spawn(binary, [ + '--headless=new', `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, + '--no-first-run', '--no-default-browser-check', '--disable-gpu-sandbox', '--use-angle=swiftshader', + '--enable-unsafe-swiftshader', 'about:blank', + ], { stdio: process.env.CP_CHROME_LOG ? 'inherit' : 'ignore' }); + let ws; + for (let i = 0; i < 300 && !ws; i++) { + try { + const v = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json(); + ws = v.webSocketDebuggerUrl; + } catch { + await sleep(100); + } + } + if (!ws) throw new Error('Chromium did not start'); + const sock = new WebSocket(ws); + await new Promise((res) => (sock.onopen = res)); + let id = 0; + const pending = new Map(); + const listeners = []; + sock.onmessage = (m) => { + const d = JSON.parse(m.data); + if (d.id && pending.has(d.id)) { + const p = pending.get(d.id); + pending.delete(d.id); + d.error ? p.rej(new Error(d.error.message)) : p.res(d.result); + } else if (d.method) for (const l of listeners) l(d); + }; + const send = (method, params = {}, sessionId) => + new Promise((res, rej) => { + const i = ++id; + pending.set(i, { res, rej }); + sock.send(JSON.stringify({ id: i, method, params, sessionId })); + }); + await send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }); + return { + name: 'chromium', + profile, + downloads, + send, + on: (f) => listeners.push(f), + stop: async () => { + try { sock.close(); } catch {} + try { process.kill(proc.pid); } catch {} + await sleep(500); + rmSync(profile, { recursive: true, force: true }); + }, + tab: async (width, height, log = console.log) => { + const { targetId } = await send('Target.createTarget', { url: 'about:blank' }); + const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }); + const s = (method, params) => send(method, params, sessionId); + listeners.push((d) => { + if (d.sessionId !== sessionId) return; + if (d.method === 'Runtime.consoleAPICalled') { + log(`[${d.params.type}] ${d.params.args.map((a) => a.value ?? a.description ?? '').join(' ')}`); + } else if (d.method === 'Runtime.exceptionThrown') { + log(`[error] ${d.params.exceptionDetails.exception?.description || d.params.exceptionDetails.text}`); + } else if (d.method === 'Log.entryAdded' && d.params.entry.level === 'error') { + log(`[error] ${d.params.entry.text}`); + } + }); + await s('Page.enable'); + await s('Runtime.enable'); + await s('Log.enable'); + await s('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }); + const evaluate = async (expression) => { + const r = await s('Runtime.evaluate', { expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, awaitPromise: true, returnByValue: true }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text); + return JSON.parse(r.result.value); + }; + let modifiers = 0; + return { + sessionId, + send: s, + evaluate, + waitFor: waitFor(evaluate), + beforeLoad: (js) => s('Page.addScriptToEvaluateOnNewDocument', { source: js }), + navigate: async (url) => { + await s('Page.navigate', { url }); + await waitFor(evaluate)(`document.readyState === 'complete'`, 30000); + }, + screenshot: async () => Buffer.from((await s('Page.captureScreenshot', { format: 'png' })).data, 'base64'), + click: async (x, y, { double = false, right = false } = {}) => { + const button = right ? 'right' : 'left'; + await s('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }); + for (let i = 1; i <= (double ? 2 : 1); i++) { + await s('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button, clickCount: i }); + await s('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button, clickCount: i }); + } + }, + key: async (key, mods = [], times = 1) => { + for (let n = 0; n < times; n++) { + for (const m of mods) { + modifiers |= KEYS[m].mod; + await s('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); + } + const k = keyOf(key); + const text = modifiers & 3 ? undefined : k.text; + await s('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers, text }); + await s('Input.dispatchKeyEvent', { type: 'keyUp', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers }); + for (const m of [...mods].reverse()) { + modifiers &= ~KEYS[m].mod; + await s('Input.dispatchKeyEvent', { type: 'keyUp', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); + } + } + }, + setFiles: async (id, files) => { + const { result } = await s('Runtime.evaluate', { expression: `document.getElementById(${JSON.stringify(id)})` }); + await s('DOM.setFileInputFiles', { objectId: result.objectId, files }); + }, + // The user chooses `files` in the dialog `open()` brings up. Chrome's own dialog + // (showOpenFilePicker, the files remembered) cannot be driven headless: the files + // are put into the site's private file system and its handles are what the + // dialog gives — the same kind of handle, kept and read again the same way. + async choose(files, open) { + const picker = await this.evaluate(`typeof window.showOpenFilePicker === 'function'`); + if (!picker) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); + return this.setFiles('cp-open-files', files); + } + const given = files.map((f) => ({ name: basename(f), b64: readFileSync(f).toString('base64') })); + await this.evaluate(`(() => { + const given = ${JSON.stringify(given)}; + window.showOpenFilePicker = async () => { + const root = await navigator.storage.getDirectory(); + const handles = []; + for (const g of given) { + const h = await root.getFileHandle(g.name, { create: true }); + const w = await h.createWritable(); + await w.write(Uint8Array.from(atob(g.b64), (c) => c.charCodeAt(0))); + await w.close(); + handles.push(h); + } + return handles; + }; + return true; + })()`); + await open(); + }, + // The user chooses the folder `dir`: in Chromium showDirectoryPicker, its files + // put into a folder of the site's private file system (as for choose()). + async chooseFolder(dir, open) { + const picker = await this.evaluate(`typeof window.showDirectoryPicker === 'function'`); + if (!picker) { + await open(); + await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000); + return this.setFiles('cp-open-folder', [dir]); + } + const given = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()) + .map((e) => ({ name: e.name, b64: readFileSync(join(dir, e.name)).toString('base64') })); + await this.evaluate(`(() => { + const given = ${JSON.stringify(given)}; + window.showDirectoryPicker = async () => { + const root = await navigator.storage.getDirectory(); + const d = await root.getDirectoryHandle(${JSON.stringify(basename(dir))}, { create: true }); + for (const g of given) { + const h = await d.getFileHandle(g.name, { create: true }); + const w = await h.createWritable(); + await w.write(Uint8Array.from(atob(g.b64), (c) => c.charCodeAt(0))); + await w.close(); + } + return d; + }; + return true; + })()`); + await open(); + }, + }; + }, + }; +} + +export async function open(port, kind = process.env.CP_BROWSER || 'firefox') { + return kind === 'chromium' ? chromium(port) : firefox(port); +} diff --git a/apps/web/check/chessbase.mjs b/apps/web/check/chessbase.mjs new file mode 100644 index 0000000..96e925c --- /dev/null +++ b/apps/web/check/chessbase.mjs @@ -0,0 +1,80 @@ +// ChessBase databases in the browser (several files): a .cbh chosen alone asks for its +// folder, the folder's files make the database; all its files chosen at once; one too +// big for a browser is refused politely; Chrome remembers the folder. +// +// node apps/web/check/chessbase.mjs [] +// +// : a small ChessBase database's folder (.cbh, .cbg, …), only that +// database in it. Firefox by default, Chromium with CP_BROWSER=chromium (browser.mjs). +import { readdirSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; + +const [appDir, outDir, baseDir, bigDir] = process.argv.slice(2).map((p) => p && resolve(p)); +let failures = 0; +const check = (ok, what) => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); + if (!ok) failures++; +}; +// «📁 Choose the database's folder» in the window about a .cbh chosen alone (1400×860). +const ADD = [155, 20]; +const FOLDER = (process.env.FOLDER || '833,471').split(',').map(Number); +const s = await session(appDir, 18768); +const { t } = s; +const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot()); +const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); +const read = (name) => s.logs.filter((l) => l.includes(`database read: ${name}`)); +const cbh = readdirSync(baseDir).find((n) => n.toLowerCase().endsWith('.cbh')); +const stem = cbh.slice(0, -4); +try { + await t.navigate(`${s.base}?lang=${process.env.CP_LANG || "en"}`); + await started(); + await sleep(2500); + + // A .cbh alone: the window asks for the database's folder; nothing is opened yet. + await t.choose([join(baseDir, cbh)], () => t.key('o', ['ctrl'])); + await sleep(2000); + await shot('cb-1-lone.png'); + check(read(stem).length === 0, 'a .cbh alone is not opened'); + // The folder: the database's files are found by their names. + await t.chooseFolder(baseDir, () => t.click(...FOLDER)); + await sleep(4000); + await shot('cb-2-folder.png'); + check(read(stem).length === 1, `the folder makes the database: ${read(stem)[0] || 'not read'}`); + + // All its files chosen at once. + const all = readdirSync(baseDir).map((n) => join(baseDir, n)); + // By the shelf's «+ Add database». + await t.choose(all, () => t.click(...ADD)); + await sleep(4000); + await shot('cb-3-files.png'); + check(read(stem).length === 2, 'all its files chosen at once make the database'); + + if (bigDir) { + // A database over the limit: refused before it is read, with the way to the + // desktop program. + const big = readdirSync(bigDir).find((n) => n.toLowerCase().endsWith('.cbh')); + await t.choose([join(bigDir, big)], () => t.click(...ADD)); + await sleep(2000); + await t.chooseFolder(bigDir, () => t.click(...FOLDER)); + await sleep(3000); + await shot('cb-4-too-big.png'); + check(read(big.slice(0, -4)).length === 0, 'a database over 2 GB is not read'); + } + + // The next visit: Chrome reads the remembered folder's database again by itself. + await t.navigate(`${s.base}?lang=${process.env.CP_LANG || "en"}`); + await started(); + await sleep(3000); + await shot('cb-5-reloaded.png'); + if (await t.evaluate(`typeof window.showDirectoryPicker === 'function'`)) { + check(s.logs.some((l) => l.includes('remembered file read again') && l.includes(cbh)), 'the folder is remembered (File System Access)'); + } +} finally { + await s.stop(); +} +for (const e of s.errors) console.log('console:', e); +check(s.errors.length === 0, 'no panic or error in the console'); +console.log(failures ? `${failures} failed` : 'all ok'); +process.exit(failures ? 1 : 0); diff --git a/apps/web/check/device.test.mjs b/apps/web/check/device.test.mjs new file mode 100644 index 0000000..f41d1bc --- /dev/null +++ b/apps/web/check/device.test.mjs @@ -0,0 +1,49 @@ +// Which devices get the program and which the page about the apps (page/device.js): +// +// node apps/web/check/device.test.mjs +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import vm from 'node:vm'; + +const source = readFileSync(fileURLToPath(new URL('../page/device.js', import.meta.url)), 'utf8'); + +// device.js in a window that looks like `d`. +function classOf(d) { + const media = { '(pointer: coarse)': d.coarse, '(any-pointer: fine)': d.fine }; + const window = { + navigator: { userAgent: d.ua, platform: d.platform || '', maxTouchPoints: d.touch || 0, userAgentData: d.uad }, + screen: { width: d.screen[0], height: d.screen[1] }, + matchMedia: (q) => ({ matches: !!media[q] }), + }; + window.window = window; + vm.runInNewContext(source, window); + return window.CPDevice.deviceClass(); +} + +const MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15'; +const cases = [ + ['Windows laptop', { ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/159.0', screen: [1920, 1080], fine: true }, 'computer'], + ['Mac', { ua: MAC, platform: 'MacIntel', screen: [1512, 982], fine: true }, 'computer'], + ['laptop with a touch screen', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [1366, 768], touch: 10, coarse: false, fine: true }, 'computer'], + ['Chromebook', { ua: 'Mozilla/5.0 (X11; CrOS x86_64 15000.0.0) Chrome/140.0', screen: [1366, 768], touch: 5, coarse: true }, 'computer'], + ['iPhone', { ua: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Mobile/15E148', screen: [390, 844], touch: 5, coarse: true }, 'iphone'], + ['iPhone asking for the desktop site', { ua: MAC, platform: 'MacIntel', screen: [390, 844], touch: 5, coarse: true }, 'iphone'], + ['iPad (says it is a Mac)', { ua: MAC, platform: 'MacIntel', screen: [820, 1180], touch: 5, coarse: true }, 'ipad'], + ['iPad mini', { ua: MAC, platform: 'MacIntel', screen: [744, 1133], touch: 5, coarse: true }, 'ipad'], + ['Android phone', { ua: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) Chrome/140.0 Mobile', screen: [412, 915], touch: 5, coarse: true }, 'android-phone'], + ['Android tablet', { ua: 'Mozilla/5.0 (Linux; Android 14; SM-X710) Chrome/140.0', screen: [800, 1280], touch: 10, coarse: true }, 'android-tablet'], + ['Galaxy Fold folded', { ua: 'Mozilla/5.0 (Linux; Android 14; SM-F946B) Chrome/140.0 Mobile', screen: [344, 882], touch: 5, coarse: true }, 'android-phone'], + ['tablet asking for the desktop site', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [800, 1280], touch: 10, coarse: true, fine: false }, 'tablet'], + ['phone asking for the desktop site', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [412, 915], touch: 5, coarse: true, fine: false }, 'phone'], + ['a mobile Chromium by its client hints', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', uad: { mobile: true, platform: 'Linux' }, screen: [412, 915], touch: 5, coarse: true }, 'phone'], +]; + +let failed = 0; +for (const [name, device, want] of cases) { + const got = classOf(device); + const ok = got === want; + if (!ok) failed++; + console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${got}${ok ? '' : ` (want ${want})`}`); +} +console.log(failed ? `${failed} of ${cases.length} failed` : `all ${cases.length} ok`); +process.exit(failed ? 1 : 0); diff --git a/apps/web/check/firefox.mjs b/apps/web/check/firefox.mjs new file mode 100644 index 0000000..088ec12 --- /dev/null +++ b/apps/web/check/firefox.mjs @@ -0,0 +1,51 @@ +// Starts a headless Firefox with a temporary profile and WebDriver BiDi; stops it by +// its PID. No window is ever shown (MOZ_HEADLESS). +import { spawn } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { connect, sleep } from './bidi.mjs'; + +export async function launch(port = 19222) { + const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-firefox-')); + writeFileSync( + join(profile, 'user.js'), + [ + 'user_pref("remote.active-protocols", 1);', + 'user_pref("browser.shell.checkDefaultBrowser", false);', + 'user_pref("datareporting.policy.dataSubmissionEnabled", false);', + 'user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);', + // Downloads go to the profile without asking. + 'user_pref("browser.download.folderList", 2);', + `user_pref("browser.download.dir", "${join(profile, 'downloads')}");`, + 'user_pref("browser.download.useDownloadDir", true);', + 'user_pref("browser.download.always_ask_before_handling_new_types", false);', + '', + ].join('\n'), + ); + const log = join(profile, 'firefox.log'); + const out = (await import('node:fs')).openSync(log, 'a'); + const ff = spawn( + 'firefox', + ['--headless', '--no-remote', '--profile', profile, '--remote-debugging-port', String(port), 'about:blank'], + { env: { ...process.env, MOZ_HEADLESS: '1' }, stdio: ['ignore', out, out] }, + ); + for (let i = 0; i < 100; i++) { + if (readFileSync(log, 'utf8').includes('WebDriver BiDi listening')) break; + await sleep(100); + } + const browser = await connect(port); + return { + browser, + profile, + downloads: join(profile, 'downloads'), + stop: async () => { + await browser.close().catch(() => {}); + try { + process.kill(ff.pid); + } catch {} + await sleep(300); + rmSync(profile, { recursive: true, force: true }); + }, + }; +} diff --git a/apps/web/check/review.mjs b/apps/web/check/review.mjs new file mode 100644 index 0000000..c6e8892 --- /dev/null +++ b/apps/web/check/review.mjs @@ -0,0 +1,95 @@ +// 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 ... +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/'))); + }; +}).then((r) => JSON.stringify(r))`; +const readStored = async () => JSON.parse(await t.evaluate(stored)); +let failed = 0; +try { + await s.run({ url: '?lang=en' }, outDir); + await sleep(2000); + // The games in one file, reviewed one by one. + await t.choose([all], () => s.run({ key: 'o', mods: ['ctrl'] }, outDir)); + await sleep(3000); + await s.run({ shot: 'review-0-opened.png' }, outDir); + for (let i = 0; i < games.length; i++) { + const before = (await readStored()).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 readStored()).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 readStored(); + 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); diff --git a/apps/web/check/serve.py b/apps/web/check/serve.py new file mode 100644 index 0000000..122b287 --- /dev/null +++ b/apps/web/check/serve.py @@ -0,0 +1,37 @@ +"""The site's layout for the web version, locally: the built program at /app/ and the +site's static files at /static/ (screenshots of the device page). Only for checks: +the site itself serves /app/ when the web version is published (docs/dev/web.md). + + python3 -I apps/web/check/serve.py [port] +""" + +import functools +import http.server +import pathlib +import sys + +APP, STATIC = pathlib.Path(sys.argv[1]).resolve(), pathlib.Path(sys.argv[2]).resolve() +PORT = int(sys.argv[3]) if len(sys.argv) > 3 else 18765 + + +class Handler(http.server.SimpleHTTPRequestHandler): + extensions_map = { + **http.server.SimpleHTTPRequestHandler.extensions_map, + ".wasm": "application/wasm", + ".js": "text/javascript", + } + + def translate_path(self, path): + path = path.split("?", 1)[0].split("#", 1)[0] + for prefix, base in (("/app/", APP), ("/static/", STATIC), ("/screenshots/", STATIC / "screenshots")): + if path.startswith(prefix): + target = (base / path[len(prefix):]).resolve() + if target == base or base in target.parents: + return str(target / "index.html" if target.is_dir() else target) + return str(APP / "__missing__") + + def log_message(self, *args): + pass + + +http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/apps/web/check/stage2.mjs b/apps/web/check/stage2.mjs new file mode 100644 index 0000000..ab3588e --- /dev/null +++ b/apps/web/check/stage2.mjs @@ -0,0 +1,83 @@ +// «My games», the data in the browser and the files of a visit in headless Firefox: +// Ctrl+S puts a game of the samples into «My games» (kept in IndexedDB), a file kept as +// a copy opens after a reload, a file only opened asks to be chosen again. +// +// node apps/web/check/stage2.mjs +// (KEEP_X, KEEP_Y: where «Keep a copy in the browser» is, for a 1400×860 window) +import { copyFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; + +const [appDir, outDir] = process.argv.slice(2); +mkdirSync(outDir, { recursive: true }); +const root = fileURLToPath(new URL('../../..', import.meta.url)); +let failures = 0; +const check = (ok, what) => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); + if (!ok) failures++; +}; + +const s = await session(appDir, 18810); +const { t } = s; +const kept = `new Promise((ok) => { + const q = indexedDB.open('chesspenguin'); + q.onsuccess = () => { + const st = q.result.transaction('files').objectStore('files'); + const keys = st.getAllKeys(), values = st.getAll(); + values.onsuccess = () => ok(JSON.stringify(keys.result.map((k, i) => [k, new TextDecoder().decode(values.result[i]).slice(0, 2000)]))); + }; +})`; +const files = async () => new Map(JSON.parse(await t.evaluate(kept))); +const step = (x) => s.run(x, outDir); +try { + await step({ url: '?lang=en' }); + await sleep(2500); + await step({ shot: 's2-1-library.png' }); + // A game of the samples into «My games». + await step({ click: [300, 322], double: true }); + await sleep(1500); + await step({ key: 's', mods: ['ctrl'] }); + await sleep(3000); + await step({ shot: 's2-2-saved.png' }); + let f = await files(); + const mine = [...f.keys()].find((k) => k.startsWith('/data/my-games/')); + check(!!mine && /Anderssen/.test(f.get(mine)), `the game is in «My games» in the browser's storage (${mine})`); + await step({ click: [55, 15] }); + await sleep(1500); + await step({ shot: 's2-3-my-games.png' }); + await step({ key: ',', mods: ['ctrl'] }); + await sleep(1000); + await step({ shot: 's2-4-settings.png' }); + await step({ click: [1366, 77] }); + // Two files opened; one kept as a copy. + const a = join(s.b.profile, 'Kept games.pgn'); + const b = join(s.b.profile, 'Visit games.pgn'); + copyFileSync(join(root, 'examples/alekhine.pgn'), a); + copyFileSync(join(root, 'examples/classics.pgn'), b); + for (const file of [b, a]) { + await t.choose([file], () => step({ key: 'o', mods: ['ctrl'] })); + await sleep(2500); + } + await step({ shot: 's2-5-opened.png' }); + if (process.env.KEEP_X) { + await step({ click: [Number(process.env.KEEP_X), Number(process.env.KEEP_Y)] }); + await sleep(2000); + await step({ shot: 's2-6-kept.png' }); + f = await files(); + check([...f.keys()].some((k) => /^\/data\/copies\/[0-9]+\/Kept games\.pgn$/.test(k)), 'a copy of the file is kept in the browser'); + } + // After a reload: «My games» and the copy are there, the other file is to be chosen again. + await step({ url: '?lang=en' }); + await sleep(3000); + await step({ shot: 's2-7-reloaded.png' }); + f = await files(); + check(!!mine && /Anderssen/.test(f.get(mine) || ''), '«My games» after a reload'); +} finally { + await s.stop(); +} +for (const e of s.errors) console.log('console:', e); +check(s.errors.length === 0, 'no panic or error in the console'); +console.log(failures ? `${failures} failed` : 'all ok'); +process.exit(failures ? 1 : 0); diff --git a/apps/web/check/steps.mjs b/apps/web/check/steps.mjs new file mode 100644 index 0000000..559cbbf --- /dev/null +++ b/apps/web/check/steps.mjs @@ -0,0 +1,64 @@ +// A session of the web version in a headless browser (browser.mjs: Firefox, or +// Chromium with CP_BROWSER=chromium) over the site's layout (serve.py), and a runner of +// step lists — for finding the places of buttons, and for the scenario checks. +// +// node apps/web/check/steps.mjs +// +// A step: {"url": "?lang=en"} | {"wait": ms} | {"click": [x, y], "double": true} +// | {"key": "l", "mods": ["ctrl"], "times": 3} | {"shot": "name.png"} | {"eval": "js"} +// | {"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 { open } from './browser.mjs'; +import { sleep } from './bidi.mjs'; + +export async function session(appDir, port = Number(process.env.CP_CHECK_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 b = await open(port + 457); + const errors = []; + const logs = []; + const t = await b.tab(1400, 860, (line) => { + logs.push(line); + if (/panicked|RuntimeError|\[error\]/.test(line) && !/favicon|404/.test(line)) errors.push(line); + if (process.env.CONSOLE) console.log(line); + }); + 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) { + await t.click(step.click[0], step.click[1], step); + await sleep(300); + } + if (step.key) { + await t.key(step.key, step.mods || [], step.times || 1); + 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, b, base, errors, logs, run, + stop: async () => { await b.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); +} diff --git a/apps/web/check/uci-worker.mjs b/apps/web/check/uci-worker.mjs new file mode 100644 index 0000000..6288a65 --- /dev/null +++ b/apps/web/check/uci-worker.mjs @@ -0,0 +1,60 @@ +// The tests of uci's worker transport (crates/uci/tests/worker.rs) in headless +// Firefox. wasm-bindgen-test-runner serves them (NO_HEADLESS: it does not look for a +// WebDriver) and this script opens its page and reads the outcome. +// +// node apps/web/check/uci-worker.mjs +// +// Needs wasm-bindgen-test-runner of the wasm-bindgen version in Cargo.lock in PATH +// or in WASM_BINDGEN_TEST_RUNNER. +import { spawn } from 'node:child_process'; +import { launch } from './firefox.mjs'; +import { sleep, tab } from './bidi.mjs'; + +const runner = process.env.WASM_BINDGEN_TEST_RUNNER || 'wasm-bindgen-test-runner'; +const address = '127.0.0.1:18731'; +const cargo = spawn( + 'cargo', + ['test', '-p', 'uci', '--target', 'wasm32-unknown-unknown', '--test', 'worker'], + { + env: { + ...process.env, + CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: runner, + NO_HEADLESS: '1', + WASM_BINDGEN_TEST_ADDRESS: address, + }, + stdio: ['ignore', 'pipe', 'inherit'], + // Its own process group: the runner it starts is stopped with it. + detached: true, + }, +); +const stopCargo = () => { + try { + process.kill(-cargo.pid); + } catch {} +}; +let served = false; +cargo.stdout.on('data', (d) => { + if (String(d).includes(address)) served = true; +}); +for (let i = 0; i < 1200 && !served; i++) await sleep(100); +if (!served) { + console.error('the test runner did not start'); + stopCargo(); + process.exit(1); +} +const ff = await launch(); +let failed = true; +try { + const t = await tab(ff.browser, 1000, 800, () => {}); + await t.navigate(`http://${address}/`); + const text = await t.waitFor( + `(() => { const t = document.body.innerText; return /test result: /.test(t) && t; })()`, + 60000, + ); + console.log(text.trim()); + failed = !/test result: ok\./.test(text); +} finally { + await ff.stop(); + stopCargo(); +} +process.exit(failed ? 1 : 0); diff --git a/apps/web/page/device.js b/apps/web/page/device.js new file mode 100644 index 0000000..a8ccbb3 --- /dev/null +++ b/apps/web/page/device.js @@ -0,0 +1,43 @@ +// What device opened the page (docs/design/web-version.md §3.6.1; decisions «Веб-версия»: +// the web application is for computers only, phones and tablets get the app page). +// Decided by the page itself before anything large is loaded: a server cannot tell an +// iPad (it says "Macintosh") nor see the size of the screen. +// +// One function for the site and /app/, so that they never disagree whom to send where +// (the site takes this file over when the web version is published). +(function (global) { + "use strict"; + + // "computer" | "iphone" | "ipad" | "android-phone" | "android-tablet" | "phone" | "tablet" + function deviceClass() { + var ua = navigator.userAgent || ""; + var uad = navigator.userAgentData; + var plat = (uad && uad.platform) || navigator.platform || ""; + var touch = navigator.maxTouchPoints > 0; + // CSS pixels of the whole screen, not of the window: a narrow window of a computer + // stays a computer; min() removes the orientation. + var short = Math.min(screen.width, screen.height); + var coarse = matchMedia("(pointer: coarse)").matches; + var finePresent = matchMedia("(any-pointer: fine)").matches; + + // iPadOS (and an iPhone asking for the desktop site) says "Mac"; a Mac has no touch. + var ios = /iPhone|iPod|iPad/.test(ua) || (/Mac/.test(plat) && navigator.maxTouchPoints > 1); + if (ios) return short < 600 ? "iphone" : "ipad"; + if (/Android/i.test(ua)) return short < 600 ? "android-phone" : "android-tablet"; + if (uad && uad.mobile) return short < 600 ? "phone" : "tablet"; + if (/CrOS/.test(ua)) return "computer"; + // A phone or tablet asking for the desktop site (Chrome on large tablets does by + // default): a touch screen and no fine pointer. A laptop with a touch screen has its + // touchpad, so it stays a computer. + if (touch && coarse && !finePresent) return short < 600 ? "phone" : "tablet"; + return "computer"; + } + + // The Android version of an Android device (0: not said). + function androidVersion() { + var m = /Android (\d+)/.exec(navigator.userAgent || ""); + return m ? Number(m[1]) : 0; + } + + global.CPDevice = { deviceClass: deviceClass, androidVersion: androidVersion }; +})(window); diff --git a/apps/web/page/import-worker.js b/apps/web/page/import-worker.js new file mode 100644 index 0000000..49365f9 --- /dev/null +++ b/apps/web/page/import-worker.js @@ -0,0 +1,29 @@ +// The page's reader: a second instance of the program that reads the databases the user +// opens, so that the page does not stop while a large one is read +// (apps/desktop/src/platform/web/import.rs). One database at a time, in order: its files +// one by one (the user's are the browser's File objects, read here), then the reading. +import init, { reader_give, reader_read } from './chesspenguin_web.js'; + +const ready = init(); + +self.onmessage = async (e) => { + await ready; + const { id, names, parts, count } = e.data; + let answer; + try { + for (let i = 0; i < names.length; i++) { + const part = parts[i]; + const bytes = part instanceof Blob ? new Uint8Array(await part.arrayBuffer()) : part; + parts[i] = null; + reader_give(names[i], bytes); + } + answer = reader_read(count); + } catch (err) { + // The program stopped (out of memory, most likely): this instance is spent. + self.postMessage({ id, crashed: String(err) }); + self.close(); + return; + } + answer.id = id; + self.postMessage(answer, answer.text ? [answer.text.buffer] : []); +}; diff --git a/apps/web/page/index.html b/apps/web/page/index.html new file mode 100644 index 0000000..2d20d55 --- /dev/null +++ b/apps/web/page/index.html @@ -0,0 +1,58 @@ + + + + + +ChessPenguin + + + + + + + + + +
+ + + + + + diff --git a/apps/web/page/page.js b/apps/web/page/page.js new file mode 100644 index 0000000..142f0c3 --- /dev/null +++ b/apps/web/page/page.js @@ -0,0 +1,211 @@ +// The page /app/: a computer gets ChessPenguin (the WebAssembly program, loaded only +// then); a phone or a tablet gets the page about the apps (docs/design/web-version.md +// §3.6, decisions «Веб-версия»), with a quiet way to open the web version anyway. +// +// ?phone=1 the device page on any device (checks, screenshots of the site); +// ?phone=android, ?phone=ios: that variant of it +// ?phone=0 the program on any device +// ?lang=xx the language (also of the program) +(function () { + "use strict"; + + var LANGS = [ + ["en", "English"], ["ru", "Русский"], ["fr", "Français"], ["de", "Deutsch"], ["es", "Español"], + ["it", "Italiano"], ["pt", "Português"], ["uz", "Oʻzbekcha"], ["kk", "Қазақша"], + ]; + // The engine the web version downloads for analysis (Stockfish 19, brotli). + var ENGINE_MB = 78; + var ANYWAY_KEY = "cp.web.phoneAnyway"; + var SITE = "https://chess.vrubel.xyz"; + + var params = new URLSearchParams(location.search); + var texts = window.CP_TEXTS || {}; + + function pickLang() { + var asked = (params.get("lang") || "").toLowerCase(); + if (texts[asked]) return asked; + var prefs = navigator.languages || [navigator.language || ""]; + for (var i = 0; i < prefs.length; i++) { + var code = String(prefs[i]).split(/[-_]/)[0].toLowerCase(); + if (texts[code]) return code; + } + return "en"; + } + var lang = pickLang(); + + function t(key, vars) { + var s = (texts[lang] && texts[lang][key]) || (texts.en && texts.en[key]) || key; + for (var k in vars || {}) s = s.split("{" + k + "}").join(vars[k]); + return s; + } + + function el(tag, attrs, children) { + var e = document.createElement(tag); + for (var a in attrs || {}) { + if (a === "text") e.textContent = attrs[a]; + else if (a === "onclick") e.addEventListener("click", attrs[a]); + else e.setAttribute(a, attrs[a]); + } + (children || []).forEach(function (c) { if (c) e.appendChild(c); }); + return e; + } + + function storage(get, value) { + try { + if (get) return localStorage.getItem(ANYWAY_KEY); + if (value === null) localStorage.removeItem(ANYWAY_KEY); + else localStorage.setItem(ANYWAY_KEY, value); + } catch (e) {} + return null; + } + + // ----- the program -------------------------------------------------------------- + + function startApp() { + document.documentElement.lang = lang; + document.title = t("app_title"); + document.getElementById("cp-device").hidden = true; + var status = document.getElementById("cp-status"); + status.textContent = t("app_loading"); + status.hidden = false; + var failed = function (e) { + console.error("ChessPenguin did not start:", e); + document.getElementById("cp-app").hidden = true; + status.textContent = t("app_failed"); + status.className = "failed"; + status.hidden = false; + }; + import("./chesspenguin_web.js") + .then(function (m) { return m.default().then(function () { return m; }); }) + .then(function (m) { + document.getElementById("cp-app").hidden = false; + return m.start("cp-canvas"); + }) + .then(function () { + status.hidden = true; + document.getElementById("cp-canvas").focus(); + }) + .catch(failed); + } + + // ----- the page for phones and tablets --------------------------------------------- + + function shots(names) { + return el("div", { class: "shots" }, names.map(function (n) { + return el("img", { src: "/screenshots/" + n, alt: "", loading: "lazy" }); + })); + } + + function shareButton() { + var url = SITE + "/app/?lang=" + lang; + var label = navigator.share ? t("app_send_link") : t("copy_link"); + var b = el("button", { class: "btn", type: "button", text: "⇪ " + label }); + b.addEventListener("click", function () { + if (navigator.share) { + navigator.share({ title: "ChessPenguin", url: url }).catch(function () {}); + } else if (navigator.clipboard) { + navigator.clipboard.writeText(url).then(function () { b.textContent = t("link_copied"); }); + } + }); + return b; + } + + function anyway() { + var size = ENGINE_MB + (lang === "ru" || lang === "kk" ? " МБ" : " MB"); + return el("div", null, [ + el("hr"), + el("button", { + class: "anyway", type: "button", text: t("app_open_anyway"), + onclick: function () { storage(false, "1"); startApp(); }, + }), + el("p", { class: "weak", text: t("app_open_anyway_note", { size: size }) }), + ]); + } + + function androidPart() { + var v = CPDevice.androidVersion(); + if (v && v < 12) { + return [el("p", { text: t("app_and_old", { version: String(v) }) }), shareButton()]; + } + var hint = el("p", { class: "weak", text: t("next_android"), hidden: "" }); + var show = function () { hint.hidden = false; }; + return [ + el("a", { class: "btn", href: "/download/android-noengine", rel: "nofollow", onclick: show }, [ + document.createTextNode(t("btn_android")), + el("small", { text: t("and_light_title") }), + ]), + el("p", null, [ + el("a", { class: "link", href: "/download/android", rel: "nofollow", onclick: show, text: t("and_full_title") + " ›" }), + ]), + el("p", { class: "weak", text: t("and_requires") }), + hint, + shots(["phone/01-home-360.webp", "phone/03-game-360.webp", "phone/04-engine-360.webp", "phone/08-review-360.webp"]), + el("p", null, [el("a", { class: "link", href: "/" + (lang === "en" ? "" : lang + "/") + "#download-android", text: t("app_and_more") + " ›" })]), + ]; + } + + function iosPart() { + return [ + el("p", { class: "lead", text: t("app_ios_lead") }), + el("p", { text: t("app_ios_now") }), + shareButton(), + el("p", { style: "margin-top:16px", text: t("app_ios_notify") }), + el("div", { class: "contacts" }, [ + el("a", { class: "link", href: "mailto:vrubelroman@gmail.com?subject=ChessPenguin", text: "✉ " + t("email") }), + el("a", { class: "link", href: "https://t.me/vrubelr", rel: "noopener", text: "✈ Telegram" }), + ]), + shots(["01-game-640.webp", "04-review-640.webp"]), + ]; + } + + function showDevicePage(kind) { + document.documentElement.lang = lang; + document.title = t("app_phone_title"); + var page = document.getElementById("cp-device"); + page.textContent = ""; + var select = el("select", { "aria-label": t("language") }, LANGS.map(function (l) { + var o = el("option", { value: l[0], text: l[1] }); + if (l[0] === lang) o.selected = true; + return o; + })); + select.addEventListener("change", function () { + lang = select.value; + showDevicePage(kind); + }); + page.appendChild(el("header", null, [ + el("span", { class: "brand" }, [el("img", { src: "icon-64.png", alt: "" }), document.createTextNode("ChessPenguin")]), + select, + ])); + page.appendChild(el("h1", { text: t("app_phone_title") })); + var body; + if (kind === "android-phone" || kind === "android-tablet") { + body = [el("p", { text: t("app_and_lead") })].concat(androidPart()); + } else if (kind === "iphone" || kind === "ipad") { + body = iosPart(); + } else { + body = [ + el("p", { text: t("app_phone_generic") }), + el("a", { class: "btn", href: "/download/android-noengine", rel: "nofollow", text: t("btn_android") }), + el("p"), + shareButton(), + ]; + } + body.forEach(function (n) { page.appendChild(n); }); + page.appendChild(anyway()); + page.hidden = false; + } + + // ----- which one -------------------------------------------------------------------- + + var asked = params.get("phone"); + var kind = CPDevice.deviceClass(); + if (asked === "1") { + showDevicePage(kind === "computer" ? "phone" : kind); + } else if (asked === "android" || asked === "ios") { + showDevicePage(asked === "android" ? "android-phone" : "iphone"); + } else if (asked === "0" || kind === "computer" || storage(true) === "1") { + startApp(); + } else { + showDevicePage(kind); + } +})(); diff --git a/apps/web/src/lib.rs b/apps/web/src/lib.rs new file mode 100644 index 0000000..147a881 --- /dev/null +++ b/apps/web/src/lib.rs @@ -0,0 +1,37 @@ +//! ChessPenguin in a browser: the entry point the page (`page/index.html`) calls once it +//! has decided the device is a computer. The interface is the desktop program's +//! (`chesspenguin_app`), with the web platform under it (`docs/dev/web.md`). +#![cfg(target_family = "wasm")] + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The reader worker's work (`page/import-worker.js`): one more file of the database +/// to read (its own file first) … +#[wasm_bindgen] +pub fn reader_give(name: String, bytes: Vec) { + chesspenguin_app::reader_give(name, bytes); +} + +/// … and the database read and indexed away from the page (or only its games counted). +#[wasm_bindgen] +pub fn reader_read(count: bool) -> JsValue { + chesspenguin_app::reader_read(count) +} + +/// Starts ChessPenguin in the page's canvas `canvas_id`. Resolves once the interface +/// runs; an error says why it could not start (no WebGL, …). +#[wasm_bindgen] +pub async fn start(canvas_id: String) -> Result<(), JsValue> { + // The program's log and its panics go to the browser's console. + let _ = eframe::WebLogger::init(log::LevelFilter::Info); + let window = web_sys::window().ok_or("no window")?; + let canvas = window + .document() + .ok_or("no document")? + .get_element_by_id(&canvas_id) + .ok_or("no canvas")? + .dyn_into::()?; + let lang = web_sys::UrlSearchParams::new_with_str(&window.location().search()?)?.get("lang"); + chesspenguin_app::start_web(canvas, lang).await +} diff --git a/crates/chess-core/Cargo.toml b/crates/chess-core/Cargo.toml index 2f0293e..a66c3b8 100644 --- a/crates/chess-core/Cargo.toml +++ b/crates/chess-core/Cargo.toml @@ -9,6 +9,12 @@ license.workspace = true shakmaty.workspace = true encoding_rs.workspace = true thiserror.workspace = true +# The index of a database in serde's terms: the web version reads a database in a +# worker and gives its index to the page (`PgnIndex`). +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] [dev-dependencies] # Independent oracle in corpus tests: the core uses its own lexer (byte offsets, diff --git a/crates/chess-core/src/database.rs b/crates/chess-core/src/database.rs index 731fe23..34678df 100644 --- a/crates/chess-core/src/database.rs +++ b/crates/chess-core/src/database.rs @@ -32,6 +32,18 @@ impl From for OpenError { } } +/// What reading a database's text found: everything of a [`PgnDatabase`] but the text. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PgnIndex { + detected: EncodingGuess, + encoding: TextEncoding, + entries: Vec, + content_hash: u64, + letter_repair: LetterRepairDetection, + repair_letters: bool, +} + /// Identity of the source content, for change detection and cache keys. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct SourceFingerprint { @@ -113,6 +125,39 @@ impl PgnDatabase { }) } + /// The database taken apart: its text and its index (to rebuild it elsewhere — + /// the web version reads a database in a worker and gives it to the page). + pub fn into_index(self) -> (Vec, PgnIndex) { + let index = PgnIndex { + detected: self.detected, + encoding: self.encoding, + entries: self.entries, + content_hash: self.fingerprint.content_hash, + letter_repair: self.letter_repair, + repair_letters: self.repair_letters, + }; + (self.bytes, index) + } + + /// The database again from its text and the index [`Self::into_index`] gave, + /// without reading the text once more. + pub fn from_index(bytes: Vec, index: PgnIndex) -> Self { + PgnDatabase { + path: None, + fingerprint: SourceFingerprint { + len: bytes.len() as u64, + modified: None, + content_hash: index.content_hash, + }, + bytes, + detected: index.detected, + encoding: index.encoding, + entries: index.entries, + letter_repair: index.letter_repair, + repair_letters: index.repair_letters, + } + } + pub fn path(&self) -> Option<&Path> { self.path.as_deref() } @@ -223,6 +268,26 @@ impl PgnDatabase { mod tests { use super::*; + /// A database taken apart and put together again is the same database. + #[test] + fn index_round_trip() { + let text = "[White \"A\"]\n[Black \"B\"]\n\n1. e4 e5 *\n\n[White \"C\"]\n\n1. d4 {x} *\n"; + let db = PgnDatabase::from_bytes( + text.as_bytes().to_vec(), + None, + &mut |_| {}, + &AtomicBool::new(false), + ) + .unwrap(); + let (entries, hash) = (db.entries().to_vec(), db.fingerprint.content_hash); + let (bytes, index) = db.into_index(); + let again = PgnDatabase::from_index(bytes, index); + assert_eq!(again.entries(), entries.as_slice()); + assert_eq!(again.fingerprint.content_hash, hash); + assert_eq!(again.bytes(), text.as_bytes()); + assert_eq!(again.load_game(1).unwrap().game.tag("White"), Some("C")); + } + fn assert_send_sync() {} #[test] diff --git a/crates/chess-core/src/encoding.rs b/crates/chess-core/src/encoding.rs index bc06a00..19fa4bb 100644 --- a/crates/chess-core/src/encoding.rs +++ b/crates/chess-core/src/encoding.rs @@ -8,6 +8,7 @@ use std::borrow::Cow; /// Encodings supported for PGN sources. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum TextEncoding { Utf8, @@ -65,6 +66,7 @@ impl TextEncoding { } /// How sure the detector is. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Confidence { /// Valid UTF-8 (or pure ASCII), or a UTF-8 BOM. @@ -74,6 +76,7 @@ pub enum Confidence { } /// Result of [`detect_encoding`]. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct EncodingGuess { pub encoding: TextEncoding, diff --git a/crates/chess-core/src/lib.rs b/crates/chess-core/src/lib.rs index 01d2f39..94c0e7e 100644 --- a/crates/chess-core/src/lib.rs +++ b/crates/chess-core/src/lib.rs @@ -19,7 +19,7 @@ pub use comment::{ Annotation, CommentPart, ShapeColor, comment_display_text, parse_comment, shapes, with_shapes, with_text, }; -pub use database::{OpenError, PgnDatabase, SourceFingerprint}; +pub use database::{OpenError, PgnDatabase, PgnIndex, SourceFingerprint}; pub use diagnostic::{Diagnostic, DiagnosticCode, Severity, SourceLocation}; pub use edit::{EditError, EditOutcome}; pub use encoding::{Confidence, EncodingGuess, TextEncoding, detect_encoding}; diff --git a/crates/chess-core/src/pgn/scan.rs b/crates/chess-core/src/pgn/scan.rs index db47a62..87b1c9e 100644 --- a/crates/chess-core/src/pgn/scan.rs +++ b/crates/chess-core/src/pgn/scan.rs @@ -7,6 +7,7 @@ use crate::encoding::TextEncoding; use crate::pgn::lexer::{Lexer, TokKind, parse_tag}; /// Summary flags computed while scanning. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct EntryFlags { pub has_fen: bool, @@ -28,6 +29,7 @@ pub struct EntryFlags { } /// One record of a PGN file. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct GameEntry { /// 0-based ordinal in the file. diff --git a/crates/chess-core/src/pgn/store.rs b/crates/chess-core/src/pgn/store.rs index 69b4111..28186cd 100644 --- a/crates/chess-core/src/pgn/store.rs +++ b/crates/chess-core/src/pgn/store.rs @@ -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 { 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, 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, 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, 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 { - 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, Removed), WriteError> { let bytes = db.bytes(); let range = db .entries() @@ -142,11 +156,29 @@ pub fn remove(db: &PgnDatabase, index: usize) -> Result { let mut out = Vec::with_capacity(bytes.len()); out.extend_from_slice(&bytes[..range.start]); out.extend_from_slice(&bytes[range.end..]); + 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 { + let path = check_writable(db)?; + let (out, gone) = removed(db, index)?; write_atomic(path, &out)?; - Ok(Removed { - index, - bytes: bytes[range].to_vec(), - }) + 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 { /// 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, 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 diff --git a/crates/chess-core/src/repair.rs b/crates/chess-core/src/repair.rs index d095cb3..77f0831 100644 --- a/crates/chess-core/src/repair.rs +++ b/crates/chess-core/src/repair.rs @@ -45,6 +45,7 @@ impl LetterRepairCounts { } /// Source-level detection result. +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct LetterRepairDetection { /// Substitution pattern found (see [`detect_letter_substitution`]). @@ -73,37 +74,18 @@ pub fn detect_letter_substitution(bytes: &[u8], encoding: TextEncoding) -> Lette ) { return LetterRepairDetection::default(); } - let (text, _) = encoding.decode(bytes); - let genuine_letters = text - .chars() + // The source's letters as they come, never all at once: a large file's text is + // twice its size in UTF-8, four times as `char`s (more than a browser's memory). + let chars = || source_chars(bytes, encoding); + let genuine_letters = chars() .filter(|c| matches!(c, 'ч' | 'Ч' | 'ю' | 'Ю')) .count(); - let chars: Vec = text.chars().collect(); - let is_cyr = - |c: Option<&char>| c.is_some_and(|c| matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё')); - let mut sequences = 0usize; - let mut i = 0; - while i + 1 < chars.len() { - let pair = [chars[i], chars[i + 1]]; - if TABLE - .iter() - .any(|(s, _)| s.chars().eq(pair.iter().copied())) - { - let before = i.checked_sub(1).and_then(|p| chars.get(p)); - let after = chars.get(i + 2); - if is_cyr(before) || is_cyr(after) { - sequences += 1; - } - i += 2; - } else { - i += 1; - } - } - let markers = chars.iter().filter(|c| matches!(c, '~' | '^')).count(); + let sequences = sequences(chars()); + let markers = chars().filter(|c| matches!(c, '~' | '^')).count(); // Each `~~` has two markers, each `x^` one; `><` has none. let detected = sequences >= MIN_SEQUENCES && genuine_letters * 50 < sequences - && markers * 9 <= sequence_markers(&chars) * 10; + && markers * 9 <= sequence_markers(chars()) * 10; LetterRepairDetection { detected, sequences, @@ -111,20 +93,53 @@ pub fn detect_letter_substitution(bytes: &[u8], encoding: TextEncoding) -> Lette } } -fn sequence_markers(chars: &[char]) -> usize { +/// The letters of `bytes` in a single-byte `encoding`, decoded a piece at a time (a +/// byte is a letter: any place splits the text). +fn source_chars(bytes: &[u8], encoding: TextEncoding) -> impl Iterator + '_ { + bytes.chunks(1 << 20).flat_map(move |piece| { + let (text, _) = encoding.decode(piece); + text.chars().collect::>() + }) +} + +/// The sequences of the table next to a Cyrillic letter (a pair taken is not looked at +/// again). +fn sequences(chars: impl Iterator) -> usize { + let is_cyr = + |c: Option| c.is_some_and(|c| matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё')); + let mut chars = chars.peekable(); let mut n = 0; - let mut i = 0; - while i + 1 < chars.len() { - match (chars[i], chars[i + 1]) { + let mut before = None; + while let Some(a) = chars.next() { + let Some(&b) = chars.peek() else { break }; + if TABLE.iter().any(|(s, _)| s.chars().eq([a, b])) { + chars.next(); + if is_cyr(before) || is_cyr(chars.peek().copied()) { + n += 1; + } + before = Some(b); + } else { + before = Some(a); + } + } + n +} + +fn sequence_markers(chars: impl Iterator) -> usize { + let mut chars = chars.peekable(); + let mut n = 0; + while let Some(a) = chars.next() { + let Some(&b) = chars.peek() else { break }; + match (a, b) { ('~', '~') => { n += 2; - i += 2; + chars.next(); } ('o' | 'о' | 'O' | 'О', '^') => { n += 1; - i += 2; + chars.next(); } - _ => i += 1, + _ => {} } } n diff --git a/crates/chess-import/src/chessbase/booster.rs b/crates/chess-import/src/chessbase/booster.rs index ce843ce..a08b3ea 100644 --- a/crates/chess-import/src/chessbase/booster.rs +++ b/crates/chess-import/src/chessbase/booster.rs @@ -143,6 +143,15 @@ fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> { } Ok(()) } + // Elsewhere (WebAssembly) through the cursor: such a target has no threads to + // share it with. + #[cfg(not(any(unix, windows)))] + { + use std::io::{Seek, SeekFrom, Write}; + let mut f = f; + f.seek(SeekFrom::Start(at))?; + f.write_all(buf) + } } /// One pass over the main lines of `base`, in parallel, writing the booster to @@ -171,75 +180,70 @@ pub(super) fn build( None => None, }; let next = AtomicUsize::new(0); - let threads = std::thread::available_parallelism() - .map_or(4, |n| n.get()) + let threads = crate::parallel::threads(4) .min(total.div_ceil(BLOCK)) .max(1); let failure: Mutex> = Mutex::new(None); - std::thread::scope(|s| { - for _ in 0..threads { - s.spawn(|| { - let run = || -> io::Result<()> { - let cbg = File::open(base.cbg_path())?; - let file = part - .as_ref() - .map(|p| File::options().write(true).open(p)) - .transpose()?; - let mut games: Vec<(u32, u32)> = Vec::new(); - let (mut span, mut single) = (Vec::new(), Vec::new()); - let mut block = vec![0u8; BLOCK * CBB_RECORD]; - let mut entries: Vec = Vec::new(); - let mut set_up: Vec = Vec::new(); - loop { - if cancel.load(Ordering::Relaxed) { - return Ok(()); - } - let from = next.fetch_add(BLOCK, Ordering::Relaxed); - if from >= total { - return Ok(()); - } - let to = (from + BLOCK).min(total); - let bytes = &mut block[..(to - from) * CBB_RECORD]; - bytes.fill(0); - entries.clear(); - set_up.clear(); - games.clear(); - for i in from..to { - // Texts and Chess960 games (ECO field ≥ 64576) have no - // record, like in ChessBase's own file. - if base.kind(i) == RecordKind::Game - && be(base.record(i), 0x23, 2).is_some_and(|eco| eco < 64576) - { - games.push((i as u32, base.moves_offset(i))); - } - } - read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| { - let opening = sink.is_some().then_some(index); - if let Some(d) = game_data(data, rel, opening) { - let at = (index as usize - from) * CBB_RECORD; - bytes[at..at + CBB_RECORD].copy_from_slice(&d.record); - entries.extend(d.opening); - if d.set_up { - set_up.push(index); - } - } - }); - if let Some(f) = &file { - write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?; - } - if let Some(sink) = &sink { - sink.add(&entries, &set_up)?; - } - progress.fetch_add(to - from, Ordering::Relaxed); - } - }; - if let Err(e) = run() { - cancel.store(true, Ordering::Relaxed); - if let Ok(mut f) = failure.lock() { - f.get_or_insert(e); + crate::parallel::map(vec![(); threads], |()| { + let run = || -> io::Result<()> { + let cbg = File::open(base.cbg_path())?; + let file = part + .as_ref() + .map(|p| File::options().write(true).open(p)) + .transpose()?; + let mut games: Vec<(u32, u32)> = Vec::new(); + let (mut span, mut single) = (Vec::new(), Vec::new()); + let mut block = vec![0u8; BLOCK * CBB_RECORD]; + let mut entries: Vec = Vec::new(); + let mut set_up: Vec = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return Ok(()); + } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Ok(()); + } + let to = (from + BLOCK).min(total); + let bytes = &mut block[..(to - from) * CBB_RECORD]; + bytes.fill(0); + entries.clear(); + set_up.clear(); + games.clear(); + for i in from..to { + // Texts and Chess960 games (ECO field ≥ 64576) have no + // record, like in ChessBase's own file. + if base.kind(i) == RecordKind::Game + && be(base.record(i), 0x23, 2).is_some_and(|eco| eco < 64576) + { + games.push((i as u32, base.moves_offset(i))); } } - }); + read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| { + let opening = sink.is_some().then_some(index); + if let Some(d) = game_data(data, rel, opening) { + let at = (index as usize - from) * CBB_RECORD; + bytes[at..at + CBB_RECORD].copy_from_slice(&d.record); + entries.extend(d.opening); + if d.set_up { + set_up.push(index); + } + } + }); + if let Some(f) = &file { + write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?; + } + if let Some(sink) = &sink { + sink.add(&entries, &set_up)?; + } + progress.fetch_add(to - from, Ordering::Relaxed); + } + }; + if let Err(e) = run() { + cancel.store(true, Ordering::Relaxed); + if let Ok(mut f) = failure.lock() { + f.get_or_insert(e); + } } }); let clean = || { @@ -265,10 +269,11 @@ pub(super) fn build( // The header last: a file without the count is never taken for a booster. let mut header = [0u8; CBB_RECORD]; header[..4].copy_from_slice(&(count as u32).to_be_bytes()); - let file = File::options().write(true).open(part)?; - write_all_at(&file, &header, 0)?; - file.sync_all()?; - drop(file); + { + let file = File::options().write(true).open(part)?; + write_all_at(&file, &header, 0)?; + file.sync_all()?; + } // Closed before the rename. std::fs::rename(part, out)?; } if let (Some(out), Some(sink)) = (openings, sink) { diff --git a/crates/chess-import/src/chessbase/mod.rs b/crates/chess-import/src/chessbase/mod.rs index cf2298b..8bdf4de 100644 --- a/crates/chess-import/src/chessbase/mod.rs +++ b/crates/chess-import/src/chessbase/mod.rs @@ -62,6 +62,22 @@ impl Files { Ok(files) } + /// The database whose `.cbh` file is `cbh_name` from files given as (name, content), + /// taking the contents (others are left out). + pub fn from_owned(cbh_name: &str, members: Vec<(String, Vec)>) -> Files { + let stem = stem_of(cbh_name).to_owned(); + let mut files = Files { + name: stem.rsplit('/').next().unwrap_or(&stem).to_owned(), + files: HashMap::new(), + }; + for (name, data) in members { + if let Some(ext) = part_of(&name, &stem) { + files.files.insert(ext, data); + } + } + files + } + /// Picks the files of the database whose `.cbh` member is `cbh_name` from archive /// members (`name`, bytes). pub fn from_members<'a>( @@ -74,11 +90,7 @@ impl Files { files: HashMap::new(), }; for (name, data) in members { - // Names differ in case in sets copied from Windows ("Base.CBH", "base.cbg"). - if let Some(ext) = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()) - && stem_of(name).to_lowercase() == stem.to_lowercase() - && USED.contains(&ext.as_str()) - { + if let Some(ext) = part_of(name, &stem) { files.files.insert(ext, data.to_vec()); } } @@ -100,7 +112,18 @@ impl Files { } /// Files the reader uses; the others (search boosters, settings, media) are ignored. -const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"]; +pub const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"]; + +/// The files a database cannot be read without (the others hold names and comments). +pub const REQUIRED: [&str; 2] = ["cbh", "cbg"]; + +/// The extension of `name` when it is a file of the database `stem` the reader uses +/// (names differ in case in sets copied from Windows: "Base.CBH", "base.cbg"). +fn part_of(name: &str, stem: &str) -> Option { + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())?; + (stem_of(name).to_lowercase() == stem.to_lowercase() && USED.contains(&ext.as_str())) + .then_some(ext) +} fn stem_of(name: &str) -> &str { name.rsplit_once('.').map_or(name, |(s, _)| s) diff --git a/crates/chess-import/src/chessbase/openings.rs b/crates/chess-import/src/chessbase/openings.rs index 78375c1..d4911a3 100644 --- a/crates/chess-import/src/chessbase/openings.rs +++ b/crates/chess-import/src/chessbase/openings.rs @@ -314,13 +314,12 @@ impl Sink { let keys_len = keys.len() as u64; file.write_all(&keys)?; drop(keys); - let mut games = games.into_inner().map_err(|e| e.into_error())?; { use std::io::Seek; + let mut games = games.into_inner().map_err(|e| e.into_error())?; games.seek(io::SeekFrom::Start(0))?; io::copy(&mut games, &mut file)?; - } - drop(games); + } // Closed before it is removed. let _ = std::fs::remove_file(&games_path); // The games from a set-up position, ascending. let mut set_up = @@ -330,17 +329,16 @@ impl Sink { file.write_all(&g.to_le_bytes())?; } let set_up_len = set_up.len() as u64 * 4; - let mut file = file.into_inner().map_err(|e| e.into_error())?; { use std::io::Seek; + let mut file = file.into_inner().map_err(|e| e.into_error())?; file.seek(io::SeekFrom::Start(16))?; file.write_all(&prefix_len.to_le_bytes())?; file.write_all(&keys_len.to_le_bytes())?; file.write_all(&games_len.to_le_bytes())?; file.write_all(&set_up_len.to_le_bytes())?; - } - file.sync_all()?; - drop(file); + file.sync_all()?; + } // Closed before the rename. std::fs::rename(&part, out)?; Ok(true) } @@ -578,22 +576,17 @@ impl Index { } // Millions of games for an early position: tallied in parallel, each part // keeping its order. - let threads = std::thread::available_parallelism() - .map_or(1, |n| n.get()) + let threads = crate::parallel::threads(1) .min(games.len().div_ceil(1 << 16)) .max(1); let chunk = games.len().div_ceil(threads).max(1); let line = &line; - let parts: Vec = std::thread::scope(|s| { - let handles: Vec<_> = games - .chunks(chunk) - .map(|part| s.spawn(move || self.tally(base, part, line))) - .collect(); - handles - .into_iter() - .map(|h| h.join().unwrap_or_default()) - .collect() - }); + let parts: Vec = crate::parallel::map(games.chunks(chunk).collect(), |part| { + self.tally(base, part, line) + }) + .into_iter() + .map(Option::unwrap_or_default) + .collect(); let mut out = Collector::default(); for part in parts { out.merge(part); diff --git a/crates/chess-import/src/chessbase/search.rs b/crates/chess-import/src/chessbase/search.rs index a8c5dfa..e3fb296 100644 --- a/crates/chess-import/src/chessbase/search.rs +++ b/crates/chess-import/src/chessbase/search.rs @@ -78,51 +78,43 @@ fn collect( .cbb_path() .filter(|p| booster_helps(p, &target.signature)); let next = AtomicUsize::new(0); - let threads = std::thread::available_parallelism() - .map_or(4, |n| n.get()) + let threads = crate::parallel::threads(4) .min(total.div_ceil(BLOCK)) .max(1); // Per thread: its collector and, per block, (first candidate, first match). type Part = (Collector, Vec<(usize, usize)>); - let parts: Vec> = std::thread::scope(|s| { - let handles: Vec<_> = (0..threads) - .map(|_| { - s.spawn(|| { - let mut worker = Worker { - base, - target: &target, - cbg: File::open(base.cbg_path()).ok()?, - cbb: cbb.and_then(|p| File::open(p).ok()), - games: Vec::new(), - span: Vec::new(), - single: Vec::new(), - out: Collector::default(), - }; - let mut blocks = Vec::new(); - loop { - if cancel.load(Ordering::Relaxed) { - return None; - } - let from = next.fetch_add(BLOCK, Ordering::Relaxed); - if from >= total { - return Some((worker.out, blocks)); - } - let to = (from + BLOCK).min(total); - blocks.push((from, worker.out.matches.len())); - match candidates { - Some(c) => worker.block(c[from..to].iter().copied()), - None => worker.block(from as u32..to as u32), - } - scanned.fetch_add(to - from, Ordering::Relaxed); - } - }) - }) - .collect(); - handles - .into_iter() - .map(|h| h.join().ok().flatten()) - .collect() - }); + let parts: Vec> = crate::parallel::map(vec![(); threads], |()| { + let mut worker = Worker { + base, + target: &target, + cbg: File::open(base.cbg_path()).ok()?, + cbb: cbb.and_then(|p| File::open(p).ok()), + games: Vec::new(), + span: Vec::new(), + single: Vec::new(), + out: Collector::default(), + }; + let mut blocks = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return None; + } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Some((worker.out, blocks)); + } + let to = (from + BLOCK).min(total); + blocks.push((from, worker.out.matches.len())); + match candidates { + Some(c) => worker.block(c[from..to].iter().copied()), + None => worker.block(from as u32..to as u32), + } + scanned.fetch_add(to - from, Ordering::Relaxed); + } + }) + .into_iter() + .map(Option::flatten) + .collect(); if cancel.load(Ordering::Relaxed) { return None; } @@ -492,6 +484,15 @@ fn read_at(f: &File, buf: &mut [u8], at: u64) -> std::io::Result { { std::os::windows::fs::FileExt::seek_read(f, buf, at) } + // Elsewhere (WebAssembly) through the cursor: such a target has no threads to + // share it with. + #[cfg(not(any(unix, windows)))] + { + use std::io::{Read, Seek, SeekFrom}; + let mut f = f; + f.seek(SeekFrom::Start(at))?; + f.read(buf) + } } fn read_exact_at(f: &File, mut buf: &mut [u8], mut at: u64) -> std::io::Result<()> { diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index efa18b4..fd7d0c0 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -8,10 +8,13 @@ //! records and a game is converted to PGN when it is opened. Sources are only read. mod archive; +// Timings of a database on disk: a command of the desktop program. +#[cfg(not(target_family = "wasm"))] pub mod bench; pub mod cbv; pub mod chessbase; pub mod memory; +mod parallel; pub mod pgn_catalog; pub mod pgn_positions; pub mod position; @@ -63,6 +66,9 @@ pub enum Unsupported { Encrypted, #[error("the ChessBase 2CBH format is not supported; export the database as CBH or PGN")] ChessBase2, + /// A ChessBase database's `.cbh` given alone: its other files are needed too. + #[error("a ChessBase database is several files: open its folder")] + ChessBaseFiles, } /// What a database was read from. @@ -76,6 +82,14 @@ pub enum Format { } impl Format { + pub const ALL: [Format; 5] = [ + Format::Pgn, + Format::ChessBase, + Format::ChessBaseArchive, + Format::Zip, + Format::SevenZip, + ]; + pub fn label(self) -> &'static str { match self { Format::Pgn => "PGN", @@ -561,11 +575,7 @@ pub fn open_bytes( match ext.as_str() { "cbz" => return Err(ImportError::Unsupported(Unsupported::Encrypted)), "2cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBase2)), - "cbh" => { - return Err(ImportError::Corrupt( - "a ChessBase database is several files: open its folder".into(), - )); - } + "cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBaseFiles)), _ => {} } if let Some(kind) = archive::sniff(&bytes) { @@ -611,6 +621,93 @@ pub fn open_chessbase_files( finish(part.pgn, Format::ChessBase, part.notes, progress, cancel) } +/// [`open_chessbase_files`] taking the contents: each file's bytes are let go once +/// the database is converted (the browser reads databases near its memory's limit). +pub fn open_chessbase_owned( + cbh_name: &str, + files: Vec<(String, Vec)>, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let members = chessbase::Files::from_owned(cbh_name, files); + let part = convert_chessbase(&members)?; + drop(members); + finish(part.pgn, Format::ChessBase, part.notes, progress, cancel) +} + +/// What files the user chose (or found in a chosen folder) make: databases, each its +/// files' places in the list (the database's own file first: its `.cbh` for a +/// ChessBase one, with the files the reader uses after it), and ChessBase databases +/// some files of which are not among them. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Chosen { + pub databases: Vec>, + /// The database's name (the `.cbh` file's, or a part's when it is not there). + pub incomplete: Vec, +} + +/// Groups the files `names` into databases (see [`Chosen`]). A ChessBase database is +/// its `.cbh` and the files of the same name beside it; files of other kinds are +/// databases of their own — in a folder only those of [`EXTENSIONS`], when the user +/// chose them, any (the content decides, as in [`open`]). +pub fn group_chosen(names: &[&str], folder: bool) -> Chosen { + let lower: Vec = names.iter().map(|n| n.to_lowercase()).collect(); + let ext = |i: usize| { + lower[i] + .rsplit_once('.') + .map(|(_, e)| e.to_owned()) + .unwrap_or_default() + }; + let stem = |i: usize| { + lower[i] + .rsplit_once('.') + .map_or(lower[i].as_str(), |(s, _)| s) + .to_owned() + }; + let bases: Vec = (0..names.len()).filter(|&i| ext(i) == "cbh").collect(); + let mut chosen = Chosen::default(); + let mut taken = vec![false; names.len()]; + for &cbh in &bases { + let parts: Vec = (0..names.len()) + .filter(|&j| j != cbh && stem(j) == stem(cbh)) + .collect(); + for &j in &parts { + taken[j] = true; + } + taken[cbh] = true; + let has = |e: &str| e == "cbh" || parts.iter().any(|&j| ext(j) == e); + if chessbase::REQUIRED.iter().all(|e| has(e)) { + let mut db = vec![cbh]; + db.extend( + parts + .into_iter() + .filter(|&j| chessbase::USED.contains(&ext(j).as_str())), + ); + chosen.databases.push(db); + } else { + chosen.incomplete.push(names[cbh].to_owned()); + } + } + for i in 0..names.len() { + if taken[i] { + continue; + } + let e = ext(i); + if chessbase::USED.contains(&e.as_str()) { + // A part of a ChessBase database without its .cbh: one note per database. + taken[i] = true; + let own = names[i].rsplit_once('.').map_or(names[i], |(s, _)| s); + let name = format!("{own}.cbh"); + if !chosen.incomplete.contains(&name) { + chosen.incomplete.push(name); + } + } else if !folder || EXTENSIONS.contains(&e.as_str()) { + chosen.databases.push(vec![i]); + } + } + chosen +} + /// A converted part of a database: UTF-8 PGN and notes. struct Part { pgn: String, @@ -745,3 +842,39 @@ fn finish( notes, }) } + +#[cfg(test)] +mod chosen_tests { + use super::*; + + #[test] + fn files_chosen_make_databases() { + // A whole ChessBase set (case of Windows copies), a PGN, a text file. + let names = [ + "Base.CBH", + "base.cbg", + "Base.cba", + "Base.cbj", + "Base.ini", + "games.pgn", + "x.txt", + ]; + let c = group_chosen(&names, false); + // The settings file is the database's (ignored); a file chosen opens by content. + assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5], vec![6]]); + assert!(c.incomplete.is_empty()); + // In a folder only databases: no text files. + let c = group_chosen(&names, true); + assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5]]); + } + + #[test] + fn a_cbh_alone_or_parts_alone_are_incomplete() { + let c = group_chosen(&["Mega Database 2026.cbh"], false); + assert!(c.databases.is_empty()); + assert_eq!(c.incomplete, vec!["Mega Database 2026.cbh".to_owned()]); + let c = group_chosen(&["Mega.cbg", "Mega.cba"], false); + assert!(c.databases.is_empty()); + assert_eq!(c.incomplete, vec!["Mega.cbh".to_owned()]); + } +} diff --git a/crates/chess-import/src/parallel.rs b/crates/chess-import/src/parallel.rs new file mode 100644 index 0000000..99c0c30 --- /dev/null +++ b/crates/chess-import/src/parallel.rs @@ -0,0 +1,58 @@ +//! Worker threads of the parallel passes (booster, position search, opening tallies). +//! +//! A target without threads (WebAssembly in a browser: `std::thread::spawn` panics +//! there) runs every pass on the calling thread; so does a pass with one worker. + +/// Workers for a parallel pass: the threads the system offers, `fallback` when it +/// cannot tell; always one where there are no threads. +pub(crate) fn threads(fallback: usize) -> usize { + if cfg!(target_family = "wasm") { + return 1; + } + std::thread::available_parallelism().map_or(fallback, |n| n.get()) +} + +/// `work` for every item, each on its own scoped thread, results in the items' order +/// (`None`: that worker panicked). One item runs on the calling thread. +pub(crate) fn map(items: Vec, work: F) -> Vec> +where + I: Send, + T: Send, + F: Fn(I) -> T + Sync, +{ + if items.len() <= 1 { + return items.into_iter().map(|i| Some(work(i))).collect(); + } + let work = &work; + std::thread::scope(|s| { + let handles: Vec<_> = items + .into_iter() + .map(|i| s.spawn(move || work(i))) + .collect(); + handles.into_iter().map(|h| h.join().ok()).collect() + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_order_and_runs_one_inline() { + let out = map(vec![3, 1, 2], |n| n * 10); + assert_eq!(out, vec![Some(30), Some(10), Some(20)]); + let here = std::thread::current().id(); + let one = map(vec![()], |()| std::thread::current().id()); + assert_eq!(one, vec![Some(here)]); + assert!(map(Vec::::new(), |n| n).is_empty()); + } + + #[test] + fn a_panicking_worker_gives_none() { + let out = map(vec![0, 1], |n| { + assert!(n == 0, "worker {n}"); + n + }); + assert_eq!(out, vec![Some(0), None]); + } +} diff --git a/crates/chess-import/tests/formats.rs b/crates/chess-import/tests/formats.rs index cad488c..3903e43 100644 --- a/crates/chess-import/tests/formats.rs +++ b/crates/chess-import/tests/formats.rs @@ -61,10 +61,12 @@ fn pgn_and_archives_open_from_bytes() { let z = chess_import::open_bytes("games.zip", bytes, &mut |_| {}, &never).expect("opens"); assert_eq!(z.format, Format::Zip); assert_eq!(z.db.raw_text(0), pgn.db.raw_text(0)); - // A .cbh alone is not a database. + // A .cbh alone is not a database: its other files are needed. assert!(matches!( chess_import::open_bytes("base.cbh", vec![0; 46], &mut |_| {}, &never), - Err(ImportError::Corrupt(_)) + Err(ImportError::Unsupported( + chess_import::Unsupported::ChessBaseFiles + )) )); } diff --git a/crates/game-review/Cargo.toml b/crates/game-review/Cargo.toml index 568aa81..97583ee 100644 --- a/crates/game-review/Cargo.toml +++ b/crates/game-review/Cargo.toml @@ -15,3 +15,4 @@ uci.workspace = true chess-openings.workspace = true serde.workspace = true serde_json.workspace = true +web-time.workspace = true diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs index 88ec2fa..6ac3834 100644 --- a/crates/game-review/src/job.rs +++ b/crates/game-review/src/job.rs @@ -10,14 +10,23 @@ //! gets the same evaluations, and the same marks. Speed comes from several engine //! processes, each taking the next position; their number changes nothing but the time. -use std::collections::HashSet; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::mpsc::channel; -use std::time::{Duration, Instant}; +use uci::{EnginePosition, Side}; -use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; +use crate::PosEval; -use crate::{Eval, PosEval, Second, Shallow}; +// 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). @@ -54,9 +63,6 @@ const SHARED_MB: u64 = 200; /// in MB. const PROCESS_MB: u64 = 70; -/// A node-limited search should never take this long; stop it if it does. -const SEARCH_GUARD: Duration = Duration::from_secs(300); - /// Engine processes for a job on this machine: one per logical CPU, at most `limit` /// (and [`MAX_PROCESSES`]), and no more than the free memory holds. pub fn processes(limit: usize) -> usize { @@ -151,277 +157,12 @@ pub enum JobFailure { Terminated(uci::TerminationReason), } -enum WorkerMsg { - Event(JobEvent), - Failed(JobFailure), -} - -/// Evaluates `targets` in `settings.processes` engine processes; `on_event` gets every -/// result, on the caller's thread, in the order they come. Returns when all are done, -/// or soon after `cancel` is set (then with `Ok`). When an engine fails, the others -/// stop too and the first failure is returned; what came before it was reported. -pub fn run( - config: uci::EngineConfig, - settings: &JobSettings, - targets: Vec, - cancel: &AtomicBool, - on_event: &mut dyn FnMut(JobEvent), -) -> Result<(), JobFailure> { - if targets.is_empty() { - return Ok(()); - } - let workers = settings - .processes - .clamp(1, MAX_PROCESSES) - .min(targets.len()); - let next = AtomicUsize::new(0); - let failed = AtomicBool::new(false); - let halted = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed); - let (tx, rx) = channel(); - let mut failure = None; - std::thread::scope(|s| { - for _ in 0..workers { - let tx = tx.clone(); - let (config, targets, next, halted) = (config.clone(), &targets, &next, &halted); - s.spawn(move || { - let mut send = |e| { - let _ = tx.send(WorkerMsg::Event(e)); - }; - if let Err(e) = worker(config, settings, targets, next, halted, &mut send) { - let _ = tx.send(WorkerMsg::Failed(e)); - } - }); - } - drop(tx); - let mut names = HashSet::new(); - for msg in rx { - match msg { - WorkerMsg::Event(JobEvent::Engine(name)) => { - if names.insert(name.clone()) { - on_event(JobEvent::Engine(name)); - } - } - WorkerMsg::Event(e) => on_event(e), - WorkerMsg::Failed(e) => { - failed.store(true, Ordering::Relaxed); - failure.get_or_insert(e); - } - } - } - }); - match failure { - Some(e) if !cancel.load(Ordering::Relaxed) => Err(e), - _ => Ok(()), - } -} - -/// One engine process: takes the next target until there is none or `halted`. -fn worker( - config: uci::EngineConfig, - settings: &JobSettings, - targets: &[Target], - next: &AtomicUsize, - halted: &dyn Fn() -> bool, - on_event: &mut dyn FnMut(JobEvent), -) -> Result<(), JobFailure> { - let handle = uci::Engine::spawn_with(config, Box::new(|| {})) - .map_err(|e| JobFailure::Start(e.to_string()))?; - if let Some(name) = &handle.info().name { - on_event(JobEvent::Engine(name.clone())); - } - if let Some(file) = &settings.eval_file { - handle - .set_option("EvalFile", Some(file)) - .map_err(|e| JobFailure::Start(e.to_string()))?; - } - // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. - let _ = handle.set_threads(1); - let _ = handle.set_hash_mb(SEARCH_HASH_MB); - let _ = handle.set_multipv(1); - let mut next_id = 0; - // Every search starts from a clear hash, so that it depends on its position alone. - let mut search = |pos: &EnginePosition, among: Vec, nodes: u64| { - next_id += 1; - 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)) { - 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 = 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(t.turn).eval), - pv, - depth: info.depth.unwrap_or(0), - second: None, - shallow: None, - }; - (eval, info.nps.unwrap_or(0)) - } - }; - // 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), - }); - } - } - 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)>, 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, u64) -> SearchResult, - t: &Target, - played: &str, - nodes: u64, -) -> Result, 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( - handle: &uci::EngineHandle, - pos: &EnginePosition, - id: SearchId, - among: Vec, - nodes: u64, - halted: &dyn Fn() -> bool, -) -> SearchResult { - handle - .search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among) - .map_err(|e| JobFailure::Engine(e.to_string()))?; - let started = Instant::now(); - let mut stopping = false; - let mut last: Option = None; - loop { - if halted() { - return Ok(None); - } - if !stopping && started.elapsed() > SEARCH_GUARD { - let _ = handle.stop(); - stopping = true; - } - match handle.recv_timeout(Duration::from_millis(100)) { - Some(EngineEvent::Info { search_id, info }) if search_id == id => { - if info.multipv_index() == 1 && info.score.is_some() { - let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); - if exact || last.is_none() { - last = Some(info); - } - } - } - Some(EngineEvent::BestMove { - search_id, best, .. - }) if search_id == id => { - return Ok(last.map(|info| (info, best.map(|b| b.to_string())))); - } - Some(EngineEvent::Terminated(reason)) => { - return Err(JobFailure::Terminated(reason)); - } - _ => {} - } - } -} - #[cfg(test)] mod tests { use super::*; + use crate::Eval; use crate::GameAnalysis; + use std::sync::atomic::{AtomicBool, Ordering}; /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). fn fake() -> &'static str { diff --git a/crates/game-review/src/job/engines.rs b/crates/game-review/src/job/engines.rs new file mode 100644 index 0000000..eaf585e --- /dev/null +++ b/crates/game-review/src/job/engines.rs @@ -0,0 +1,181 @@ +//! The engine job in engine processes, each driven from a thread of its own. + +use std::collections::HashSet; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::channel; +use std::time::{Duration, Instant}; + +use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits}; + +use super::work::{Answer, 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); + +enum WorkerMsg { + Event(JobEvent), + Failed(JobFailure), +} + +/// Evaluates `targets` in `settings.processes` engine processes; `on_event` gets every +/// result, on the caller's thread, in the order they come. Returns when all are done, +/// or soon after `cancel` is set (then with `Ok`). When an engine fails, the others +/// stop too and the first failure is returned; what came before it was reported. +pub fn run( + config: uci::EngineConfig, + settings: &JobSettings, + targets: Vec, + cancel: &AtomicBool, + on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + if targets.is_empty() { + return Ok(()); + } + let workers = settings + .processes + .clamp(1, MAX_PROCESSES) + .min(targets.len()); + let next = AtomicUsize::new(0); + let failed = AtomicBool::new(false); + let halted = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed); + let (tx, rx) = channel(); + let mut failure = None; + std::thread::scope(|s| { + for _ in 0..workers { + let tx = tx.clone(); + let (config, targets, next, halted) = (config.clone(), &targets, &next, &halted); + s.spawn(move || { + let mut send = |e| { + let _ = tx.send(WorkerMsg::Event(e)); + }; + if let Err(e) = worker(config, settings, targets, next, halted, &mut send) { + let _ = tx.send(WorkerMsg::Failed(e)); + } + }); + } + drop(tx); + let mut names = HashSet::new(); + for msg in rx { + match msg { + WorkerMsg::Event(JobEvent::Engine(name)) => { + if names.insert(name.clone()) { + on_event(JobEvent::Engine(name)); + } + } + WorkerMsg::Event(e) => on_event(e), + WorkerMsg::Failed(e) => { + failed.store(true, Ordering::Relaxed); + failure.get_or_insert(e); + } + } + } + }); + match failure { + Some(e) if !cancel.load(Ordering::Relaxed) => Err(e), + _ => Ok(()), + } +} + +/// One engine process: takes the next target until there is none or `halted`. +fn worker( + config: uci::EngineConfig, + settings: &JobSettings, + targets: &[Target], + next: &AtomicUsize, + halted: &dyn Fn() -> bool, + on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + let handle = uci::Engine::spawn_with(config, Box::new(|| {})) + .map_err(|e| JobFailure::Start(e.to_string()))?; + if let Some(name) = &handle.info().name { + on_event(JobEvent::Engine(name.clone())); + } + if let Some(file) = &settings.eval_file { + handle + .set_option("EvalFile", Some(file)) + .map_err(|e| JobFailure::Start(e.to_string()))?; + } + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = handle.set_threads(1); + let _ = handle.set_hash_mb(SEARCH_HASH_MB); + let _ = handle.set_multipv(1); + let mut next_id = 0; + // Every search starts from a clear hash, so that it depends on its position alone. + let mut search = |pos: &EnginePosition, among: Vec, nodes: u64| { + next_id += 1; + let _ = handle.new_game(); + search_once(&handle, pos, SearchId(next_id), among, nodes, halted) + }; + 'targets: while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) { + if halted() { + break; + } + 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; + } + work.answer(answer); + } + Next::Done(event) => { + if let Some(e) = event { + on_event(e); + } + break; + } + } + } + } + handle.quit(); + Ok(()) +} + +/// 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( + handle: &uci::EngineHandle, + pos: &EnginePosition, + id: SearchId, + among: Vec, + nodes: u64, + halted: &dyn Fn() -> bool, +) -> Result { + handle + .search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among) + .map_err(|e| JobFailure::Engine(e.to_string()))?; + let started = Instant::now(); + let mut stopping = false; + let mut last: Option = None; + loop { + if halted() { + return Ok(None); + } + if !stopping && started.elapsed() > SEARCH_GUARD { + let _ = handle.stop(); + stopping = true; + } + match handle.recv_timeout(Duration::from_millis(100)) { + Some(EngineEvent::Info { search_id, info }) if search_id == id => { + if info.multipv_index() == 1 && info.score.is_some() { + let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); + if exact || last.is_none() { + last = Some(info); + } + } + } + Some(EngineEvent::BestMove { + search_id, best, .. + }) if search_id == id => { + return Ok(last.map(|info| (info, best.map(|b| b.to_string())))); + } + Some(EngineEvent::Terminated(reason)) => { + return Err(JobFailure::Terminated(reason)); + } + _ => {} + } + } +} diff --git a/crates/game-review/src/job/work.rs b/crates/game-review/src/job/work.rs new file mode 100644 index 0000000..bb1fb1a --- /dev/null +++ b/crates/game-review/src/job/work.rs @@ -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)>; + +/// 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, + nodes: u64, + }, + /// The target is done: its evaluation (`None`: the engine gave nothing to use). + Done(Option), +} + +enum Stage { + Full, + Second, + ShallowBest, + ShallowPlayed { best: String, best_eval: Eval }, + Finish, +} + +pub(crate) struct Work { + t: Target, + nodes: u64, + stage: Stage, + eval: Option, + nps: u64, + /// The move played, when it is the engine's best and worth a second search. + played: Option, +} + +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 { + 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 = 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, + }); + } + } +} diff --git a/crates/game-review/src/job/workers.rs b/crates/game-review/src/job/workers.rs new file mode 100644 index 0000000..cb099f9 --- /dev/null +++ b/crates/game-review/src/job/workers.rs @@ -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, + started: Instant, + stopping: bool, +} + +struct Slot { + engine: Engine, + work: Option, + search: Option, + next_id: u64, +} + +/// The job: started by [`Dispatcher::start`], driven by [`Dispatcher::poll`]. +pub struct Dispatcher { + slots: Vec, + targets: std::vec::IntoIter, + nodes: u64, + names: HashSet, + events: Vec, + failure: Option, + 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, + wake: Arc, + ) -> Result { + 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, Option>) { + 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; + } + } + } + } +} diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs index cc75bbf..107415f 100644 --- a/crates/game-review/src/lib.rs +++ b/crates/game-review/src/lib.rs @@ -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,9 +22,13 @@ 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::{ JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB, - SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes, run, + SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes, }; pub use report::{ Eval, Hardness, Judgement, Measure, Phase, Phases, Ply, Report, SideStats, judge, @@ -155,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>; + 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> { + 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, @@ -179,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 @@ -554,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')) { @@ -563,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(()); }; @@ -586,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::(&bytes) else { @@ -835,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 = diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index 3153958..a470468 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -71,6 +71,11 @@ impl From for ApiError { E::Io { source, .. } => ApiError::Io { detail: source.to_string(), }, + // A .cbh alone: reported as before (the app opens a ChessBase database + // by all its files, `open_chessbase`). + E::Unsupported(u @ chess_import::Unsupported::ChessBaseFiles) => ApiError::Corrupt { + detail: u.to_string(), + }, E::Unsupported(u) => ApiError::Unsupported { detail: u.to_string(), }, diff --git a/crates/online-games/Cargo.toml b/crates/online-games/Cargo.toml index 2443f57..da2d8d7 100644 --- a/crates/online-games/Cargo.toml +++ b/crates/online-games/Cargo.toml @@ -11,6 +11,9 @@ publish = false [dependencies] serde.workspace = true serde_json.workspace = true + +# Requests that block a thread: not in a browser (net.rs). +[target.'cfg(not(target_family = "wasm"))'.dependencies] ureq = "3.4" [dev-dependencies] diff --git a/crates/online-games/src/lib.rs b/crates/online-games/src/lib.rs index 8fb77e7..a287ab2 100644 --- a/crates/online-games/src/lib.rs +++ b/crates/online-games/src/lib.rs @@ -8,14 +8,14 @@ //! `since`; anonymous requests are throttled to 20 games a second. Chess.com: the list of //! monthly archives, then each month's games as JSON (their PGN inside), from the last //! month already fetched. Only standard chess is kept (variants are not supported). +//! +//! The network part (`net.rs`: lookups, downloads) is built where requests can block +//! a thread: not in a browser. -use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::time::Duration; +use std::sync::atomic::AtomicUsize; use serde::{Deserialize, Serialize}; -use serde_json::Value; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Platform { @@ -44,24 +44,10 @@ impl Platform { /// Lichess's anonymous export rate (games per second), for the time estimate. pub const LICHESS_RATE: u64 = 20; -fn agent(stream: bool) -> ureq::Agent { - let config = ureq::Agent::config_builder() - .user_agent(format!( - "ChessPenguin/{} (+https://chess.vrubel.xyz)", - env!("CARGO_PKG_VERSION") - )) - .http_status_as_error(false) - .timeout_connect(Some(Duration::from_secs(10))) - .timeout_recv_response(Some(Duration::from_secs(30))) - // A long export is one response: hours for the body (a stalled one ends). - .timeout_recv_body(if stream { - Some(Duration::from_secs(4 * 3600)) - } else { - Some(Duration::from_secs(60)) - }) - .build(); - ureq::Agent::new_with_config(config) -} +#[cfg(not(target_family = "wasm"))] +mod net; +#[cfg(not(target_family = "wasm"))] +pub use net::{download, lookup, probe, probe_all}; /// What went wrong talking to a platform. #[derive(Debug, Clone, PartialEq, Eq)] @@ -90,104 +76,6 @@ impl std::fmt::Display for Failure { } } -/// Makes a request again when the connection broke (Lichess drops connections for a -/// minute or so after an export was cut short), waiting `waits` seconds in between; -/// stops waiting when cancelled. -fn retrying( - waits: &[u64], - cancel: &AtomicBool, - mut request: impl FnMut() -> Result, -) -> Result { - let mut waits = waits.iter(); - loop { - match request() { - Ok(r) => return Ok(r), - Err(e) => { - let Some(&secs) = waits.next() else { - return Err(Failure::Network(e.to_string())); - }; - for _ in 0..secs * 10 { - if cancel.load(Ordering::Relaxed) { - return Err(Failure::Network(e.to_string())); - } - std::thread::sleep(Duration::from_millis(100)); - } - } - } - } -} - -/// Waits before the attempts of a download request: about a minute in all. -const DOWNLOAD_WAITS: &[u64] = &[3, 10, 20, 30]; - -/// GET returning (status, body); the body of an error status is not read. -fn get(url: &str) -> Result<(u16, String), Failure> { - let never = AtomicBool::new(false); - // The whole exchange is repeated: a connection may also break in the body. - retrying(&[2, 5], &never, || { - let mut resp = agent(false) - .get(url) - .header("Accept", "application/json") - .call()?; - let status = resp.status().as_u16(); - if status != 200 { - return Ok((status, String::new())); - } - let body = resp - .body_mut() - .with_config() - .limit(64 << 20) - .read_to_string()?; - Ok((status, body)) - }) - .and_then(|(status, body)| { - if status == 429 { - Err(Failure::RateLimited) - } else { - Ok((status, body)) - } - }) -} - -fn json(url: &str) -> Result, Failure> { - match get(url)? { - (200, body) => serde_json::from_str(&body) - .map(Some) - .map_err(|e| Failure::Unexpected(e.to_string())), - (404, _) => Ok(None), - (code, _) => Err(Failure::Unexpected(format!("HTTP {code}"))), - } -} - -/// Whether the platform answers the way this code expects: the profile of an account -/// that has always existed (Lichess's own, Chess.com's founder's). -pub fn probe(p: Platform) -> bool { - let url = match p { - Platform::Lichess => "https://lichess.org/api/user/lichess", - Platform::ChessCom => "https://api.chess.com/pub/player/erik", - }; - matches!(json(url), Ok(Some(v)) if probe_answer_ok(p, &v)) -} - -/// The probe's answer has the fields this code relies on. -fn probe_answer_ok(p: Platform, v: &Value) -> bool { - match p { - Platform::Lichess => { - v["id"] == "lichess" && v["username"].is_string() && v["count"]["all"].is_u64() - } - Platform::ChessCom => v["player_id"].is_u64() && v["username"] == "erik", - } -} - -/// Both platforms probed (in parallel); `[lichess, chess.com]`. -pub fn probe_all() -> [bool; 2] { - std::thread::scope(|s| { - let l = s.spawn(|| probe(Platform::Lichess)); - let c = s.spawn(|| probe(Platform::ChessCom)); - [l.join().unwrap_or(false), c.join().unwrap_or(false)] - }) -} - /// A nickname both platforms could have: 2–30 letters, digits, `_` or `-`. pub fn valid_nick(nick: &str) -> bool { (2..=30).contains(&nick.len()) @@ -215,68 +103,6 @@ pub enum Lookup { Failed(Failure), } -/// Looks the nickname up on the platform. -pub fn lookup(p: Platform, nick: &str) -> Lookup { - let nick = nick.trim(); - if !valid_nick(nick) { - return Lookup::NotFound; - } - let result = match p { - Platform::Lichess => json(&format!("https://lichess.org/api/user/{nick}")).map(|v| { - v.filter(|v| v["disabled"] != true).and_then(|v| { - Some(Account { - platform: p, - username: v["username"].as_str()?.to_owned(), - games: v["count"]["all"].as_u64(), - months: None, - }) - }) - }), - Platform::ChessCom => { - let lower = nick.to_ascii_lowercase(); - json(&format!("https://api.chess.com/pub/player/{lower}")).and_then(|v| { - let Some(username) = v.and_then(|v| v["username"].as_str().map(str::to_owned)) - else { - return Ok(None); - }; - // Chess.com answers in lower case; the user's spelling reads better. - let username = if username.eq_ignore_ascii_case(nick) { - nick.to_owned() - } else { - username - }; - let months = archives(&lower)?.len(); - Ok(Some(Account { - platform: p, - username, - games: None, - months: Some(months), - })) - }) - } - }; - match result { - Ok(Some(a)) => Lookup::Found(a), - Ok(None) => Lookup::NotFound, - Err(e) => Lookup::Failed(e), - } -} - -/// Chess.com's monthly archive URLs of a player, oldest first. -fn archives(lower: &str) -> Result, Failure> { - let v = json(&format!( - "https://api.chess.com/pub/player/{lower}/games/archives" - ))? - .ok_or_else(|| Failure::Unexpected("no archives".into()))?; - let list = v["archives"] - .as_array() - .ok_or_else(|| Failure::Unexpected("archives".into()))?; - Ok(list - .iter() - .filter_map(|u| u.as_str().map(str::to_owned)) - .collect()) -} - /// The database file of one account in `dir`: "Name (Lichess).pgn". pub fn database_path(dir: &Path, p: Platform, username: &str) -> PathBuf { dir.join(format!("{username} ({}).pgn", p.name())) @@ -370,9 +196,6 @@ pub struct State { pub tail: Vec, } -/// How many last bytes of the file the state remembers. -const TAIL: usize = 64; - impl State { pub fn load(pgn: &Path) -> Option { let text = std::fs::read_to_string(state_path(pgn)).ok()?; @@ -381,15 +204,6 @@ impl State { .filter(|s| !s.accounts.is_empty() && s.accounts.iter().all(|a| a.platform.is_some())) } - fn save(&self, pgn: &Path) -> Result<(), Failure> { - let text = serde_json::to_string_pretty(self).map_err(|e| Failure::Disk(e.to_string()))?; - let path = state_path(pgn); - let tmp = path.with_extension("tmp"); - std::fs::write(&tmp, text) - .and_then(|_| std::fs::rename(&tmp, &path)) - .map_err(|e| Failure::Disk(e.to_string())) - } - fn holds(&self, a: &Account) -> bool { self.accounts.iter().any(|s| s.is(a)) } @@ -483,778 +297,3 @@ pub struct Done { /// Stopped by the user; what was fetched is kept and the next update continues. pub cancelled: bool, } - -/// The databases being written now: one download per file at a time. -static WRITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - -/// Holds a database for one download; released when dropped. -struct Claim(PathBuf); - -impl Claim { - fn take(path: &Path) -> Option { - let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); - if w.iter().any(|p| p == path) { - return None; - } - w.push(path.to_owned()); - Some(Claim(path.to_owned())) - } -} - -impl Drop for Claim { - fn drop(&mut self) { - let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); - w.retain(|p| *p != self.0); - } -} - -/// Appends games to the database file and keeps the state in step. -struct Writer { - path: PathBuf, - file: std::io::BufWriter, - state: State, - added: u64, - /// The file's length and last bytes as written (flushed or not). - len: u64, - tail: Vec, -} - -impl Writer { - /// Opens the database for appending; a state that does not match the file (the file - /// is gone, or a crash left games after the state) is put right first. - fn open(path: &Path, mut state: State) -> Result { - let disk = |e: std::io::Error| Failure::Disk(e.to_string()); - if let Some(d) = path.parent() { - std::fs::create_dir_all(d).map_err(disk)?; - } - let file = std::fs::OpenOptions::new() - .create(true) - .read(true) - .append(true) - .open(path) - .map_err(disk)?; - let mut len = file.metadata().map_err(disk)?.len(); - if let Some(b) = state.bytes - && len > b - && b as usize >= state.tail.len() - { - let mut end = vec![0; state.tail.len()]; - use std::io::{Read, Seek, SeekFrom}; - let mut f = &file; - f.seek(SeekFrom::Start(b - state.tail.len() as u64)) - .and_then(|_| f.read_exact(&mut end)) - .map_err(disk)?; - if end == state.tail { - file.set_len(b).map_err(disk)?; - len = b; - } - } - let tail = if len == state.bytes.unwrap_or(u64::MAX) { - std::mem::take(&mut state.tail) - } else { - Vec::new() - }; - Ok(Writer { - path: path.to_owned(), - file: std::io::BufWriter::new(file), - state, - added: 0, - len, - tail, - }) - } - - fn game(&mut self, pgn: &str) -> Result<(), Failure> { - let pgn = pgn.trim(); - if pgn.is_empty() { - return Ok(()); - } - for part in [pgn.as_bytes(), b"\n\n"] { - self.file - .write_all(part) - .map_err(|e| Failure::Disk(e.to_string()))?; - self.len += part.len() as u64; - self.tail.extend_from_slice(part); - } - if self.tail.len() > TAIL { - self.tail.drain(..self.tail.len() - TAIL); - } - self.added += 1; - self.state.games += 1; - Ok(()) - } - - /// Makes what was written durable, the state last (it never runs ahead of the file). - fn commit(&mut self) -> Result<(), Failure> { - self.file - .flush() - .map_err(|e| Failure::Disk(e.to_string()))?; - self.state.bytes = Some(self.len); - self.state.tail = self.tail.clone(); - self.state.save(&self.path) - } - - fn done(mut self, cancelled: bool) -> Result { - if !cancelled { - self.state.updated = Some(now_secs()); - } - self.commit()?; - Ok(Done { - path: self.path, - added: self.added, - total: self.state.games, - cancelled, - }) - } -} - -/// Fetches the games of `accounts` new since the last run into the database at `path` -/// (one database for all of them); `progress` counts the games added, `status` tells -/// what is being fetched. Cancelling keeps what was fetched. One download per database -/// at a time ([`Failure::Busy`] otherwise). -pub fn download( - accounts: &[Account], - path: &Path, - progress: &AtomicUsize, - cancel: &AtomicBool, - status: &Progress, -) -> Result { - let _claim = Claim::take(path).ok_or(Failure::Busy)?; - // Another ChessPenguin running may download into the same database: a file lock - // (released when the file closes, also if the process dies). - if let Some(d) = path.parent() { - std::fs::create_dir_all(d).map_err(|e| Failure::Disk(e.to_string()))?; - } - let lock = std::fs::File::create(path.with_extension("online.lock")) - .map_err(|e| Failure::Disk(e.to_string()))?; - if let Err(e) = lock.try_lock() { - return Err(match e { - std::fs::TryLockError::WouldBlock => Failure::Busy, - std::fs::TryLockError::Error(e) => Failure::Disk(e.to_string()), - }); - } - let path = path.to_owned(); - let mut state = State::load(&path) - // The games are gone (the file was deleted): fetch them again. - .filter(|s| path.exists() || s.games == 0) - .unwrap_or_else(|| { - // A database without its state: start it anew rather than append duplicates. - let _ = std::fs::remove_file(&path); - State::default() - }); - // Accounts not in the database yet start from their first game. - for a in accounts { - if !state.holds(a) { - state.accounts.push(AccountState { - platform: Some(a.platform), - username: a.username.clone(), - ..AccountState::default() - }); - } - } - let mut w = Writer::open(&path, state)?; - let mut result = Ok(false); - for i in 0..w.state.accounts.len() { - let Some(k) = accounts.iter().position(|a| w.state.accounts[i].is(a)) else { - continue; - }; - status.account.store(k, Ordering::Relaxed); - status.games.store(0, Ordering::Relaxed); - result = match w.state.accounts[i].platform { - Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel, status), - Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status), - None => Ok(false), - }; - if !matches!(result, Ok(false)) { - break; - } - } - match result { - Ok(c) => w.done(c), - Err(e) => { - // Keep what arrived before the failure; the next update continues. - let _ = w.commit(); - Err(e) - } - } -} - -#[cfg(test)] -fn download_to( - accounts: &[Account], - path: &Path, - progress: &AtomicUsize, - cancel: &AtomicBool, -) -> Result { - download(accounts, path, progress, cancel, &Progress::default()) -} - -/// Lichess's answer for one game, as far as the download cares. -struct LichessGame<'a> { - id: &'a str, - created: i64, - /// Still being played (not exported as a game yet). - playing: bool, - standard: bool, - /// Present for finished games (an unfinished one may come without it). - pgn: Option<&'a str>, -} - -fn lichess_game(v: &Value) -> Option> { - let g = LichessGame { - id: v["id"].as_str()?, - created: v["createdAt"].as_i64()?, - playing: matches!(v["status"].as_str(), Some("created" | "started")), - standard: v["variant"] - .as_str() - .is_none_or(|x| x == "standard" || x == "fromPosition"), - pgn: v["pgn"].as_str(), - }; - (g.playing || g.pgn.is_some()).then_some(g) -} - -/// Whether to write a game of the Lichess export; an unfinished one is remembered as -/// pending instead (asked about by id next time), a pending one that ended is written. -fn lichess_keep(a: &mut AccountState, g: &LichessGame) -> bool { - let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id); - if g.playing { - if pending.is_none() && g.standard { - a.lichess_pending.push((g.id.to_owned(), g.created)); - } - return false; - } - if let Some(k) = pending { - a.lichess_pending.remove(k); - } - g.standard -} - -/// A pending game Lichess no longer returns is given up after a year. -const PENDING_DAYS: i64 = 365; - -/// Reads a Lichess NDJSON answer line by line. `Ok(true)` when cancelled. -fn lichess_lines( - resp: ureq::http::Response, - cancel: &AtomicBool, - mut each: impl FnMut(usize, &Value) -> Result<(), Failure>, -) -> Result { - match resp.status().as_u16() { - 200 => {} - 429 => return Err(Failure::RateLimited), - code => return Err(Failure::Unexpected(format!("HTTP {code}"))), - } - let reader = BufReader::new(resp.into_body().into_reader()); - for (n, line) in reader.lines().enumerate() { - if cancel.load(Ordering::Relaxed) { - return Ok(true); - } - let line = line.map_err(|e| Failure::Network(e.to_string()))?; - if line.trim().is_empty() { - continue; - } - let v: Value = - serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; - each(n, &v)?; - } - Ok(false) -} - -const LICHESS_PARAMS: &str = "pgnInJson=true&clocks=false&evals=false&opening=true"; - -/// The games of account `i` of the writer's database from Lichess: first the pending -/// (unfinished last time) ones by id, then the new ones. `Ok(true)` when cancelled. -fn lichess( - w: &mut Writer, - i: usize, - progress: &AtomicUsize, - cancel: &AtomicBool, - status: &Progress, -) -> Result { - let write = |w: &mut Writer, v: &Value| -> Result { - let g = lichess_game(v) - .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; - if lichess_keep(&mut w.state.accounts[i], &g) - && let Some(pgn) = g.pgn - { - let pgn = pgn.to_owned(); - w.game(&pgn)?; - progress.fetch_add(1, Ordering::Relaxed); - status.games.fetch_add(1, Ordering::Relaxed); - } - Ok(g.created) - }; - let pending: Vec = w.state.accounts[i] - .lichess_pending - .iter() - .map(|(id, _)| id.clone()) - .collect(); - for chunk in pending.chunks(300) { - let resp = retrying(DOWNLOAD_WAITS, cancel, || { - agent(true) - .post(&format!( - "https://lichess.org/api/games/export/_ids?{LICHESS_PARAMS}" - )) - .header("Accept", "application/x-ndjson") - .send(chunk.join(",")) - })?; - if lichess_lines(resp, cancel, |_, v| write(w, v).map(|_| ()))? { - return Ok(true); - } - } - let year_ago = now_secs() * 1000 - PENDING_DAYS * 86_400_000; - w.state.accounts[i] - .lichess_pending - .retain(|(_, created)| *created > year_ago); - w.commit()?; - - let a = &w.state.accounts[i]; - let mut url = format!( - "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false\ - &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&{LICHESS_PARAMS}", - a.username - ); - if let Some(last) = a.lichess_last { - url.push_str(&format!("&since={}", last + 1)); - } - let resp = retrying(DOWNLOAD_WAITS, cancel, || { - agent(true) - .get(&url) - .header("Accept", "application/x-ndjson") - .call() - })?; - lichess_lines(resp, cancel, |n, v| { - let created = write(w, v)?; - let a = &mut w.state.accounts[i]; - a.lichess_last = Some(a.lichess_last.map_or(created, |l| l.max(created))); - if n % 100 == 99 { - w.commit()?; - } - Ok(()) - }) -} - -/// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when -/// cancelled. -fn chesscom( - w: &mut Writer, - i: usize, - progress: &AtomicUsize, - cancel: &AtomicBool, - status: &Progress, -) -> Result { - let lower = w.state.accounts[i].username.to_ascii_lowercase(); - let months = archives(&lower)?; - status.months_total.store(months.len(), Ordering::Relaxed); - status.months_done.store(0, Ordering::Relaxed); - for url in months { - status.months_done.fetch_add(1, Ordering::Relaxed); - // ".../games/2026/10" → "2026/10"; months before the last fetched are done. - let month = url.rsplitn(3, '/').take(2).collect::>(); - let month = format!( - "{}/{}", - month.get(1).unwrap_or(&""), - month.first().unwrap_or(&"") - ); - let a = &w.state.accounts[i]; - if a.chesscom_month.as_ref().is_some_and(|m| month < *m) { - continue; - } - if cancel.load(Ordering::Relaxed) { - return Ok(true); - } - let v = json(&url)?.ok_or_else(|| Failure::Unexpected(format!("{month}: not found")))?; - let games = v["games"] - .as_array() - .ok_or_else(|| Failure::Unexpected(format!("{month}: no games")))?; - let mut list: Vec<(i64, &str)> = games - .iter() - .filter(|g| g["rules"] == "chess") - .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) - .collect(); - list.sort_by_key(|(t, _)| *t); - let a = &w.state.accounts[i]; - let same_month = a.chesscom_month.as_deref() == Some(month.as_str()); - let last = if same_month { - a.chesscom_last_end - } else { - None - }; - for (end, pgn) in list { - if last.is_some_and(|l| end <= l) { - continue; - } - w.game(pgn)?; - progress.fetch_add(1, Ordering::Relaxed); - status.games.fetch_add(1, Ordering::Relaxed); - w.state.accounts[i].chesscom_last_end = Some(end); - } - // The mark moves to this month even when it had no standard games (the end - // time then still belongs to an earlier month and is not compared). - w.state.accounts[i].chesscom_month = Some(month); - w.commit()?; - } - Ok(false) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn temp_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("cp-online-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d - } - - fn account(p: Platform, name: &str) -> Account { - Account { - platform: p, - username: name.into(), - games: None, - months: None, - } - } - - const GAME: &str = "[Event \"x\"]\n\n1. e4 e5 1-0"; - - #[test] - fn a_crash_leaves_no_duplicates() { - let dir = temp_dir("crash"); - let path = dir.join("db.pgn"); - let state = State { - accounts: vec![AccountState { - platform: Some(Platform::Lichess), - username: "a".into(), - ..AccountState::default() - }], - ..State::default() - }; - let mut w = Writer::open(&path, state).unwrap(); - w.game(GAME).unwrap(); - w.game(GAME).unwrap(); - w.commit().unwrap(); - let good = std::fs::read(&path).unwrap(); - // Games written after the last commit, then the process died. - w.game(GAME).unwrap(); - w.file.flush().unwrap(); - drop(w); - assert!(std::fs::read(&path).unwrap().len() > good.len()); - let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); - assert_eq!(w.state.games, 2); - drop(w); - assert_eq!(std::fs::read(&path).unwrap(), good, "cut back to the state"); - - // Somebody else changed the file: it is left alone. - let mut other = good.clone(); - other[0] = b' '; - other.extend_from_slice(GAME.as_bytes()); - std::fs::write(&path, &other).unwrap(); - let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); - drop(w); - assert_eq!(std::fs::read(&path).unwrap(), other); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn a_deleted_database_is_downloaded_again() { - let dir = temp_dir("deleted"); - let path = dir.join("db.pgn"); - let state = State { - accounts: vec![AccountState { - platform: Some(Platform::Lichess), - username: "a".into(), - lichess_last: Some(5), - ..AccountState::default() - }], - games: 7, - ..State::default() - }; - state.save(&path).unwrap(); - let never = AtomicBool::new(false); - // No account asked for: nothing fetched, only the state put right. - let d = download_to(&[], &path, &AtomicUsize::new(0), &never).unwrap(); - assert_eq!(d.total, 0); - let s = State::load(&path).unwrap_or_default(); - assert!(s.accounts.iter().all(|a| a.lichess_last.is_none())); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn one_download_per_database() { - let path = PathBuf::from("/nonexistent/cp-claim.pgn"); - let first = Claim::take(&path).expect("free"); - assert!(Claim::take(&path).is_none()); - let never = AtomicBool::new(false); - assert_eq!( - download_to(&[], &path, &AtomicUsize::new(0), &never), - Err(Failure::Busy) - ); - drop(first); - assert!(Claim::take(&path).is_some()); - } - - #[test] - fn names_of_merged_databases() { - let name = |a: &[Account]| { - combined_path(Path::new("/online"), a) - .unwrap() - .file_name() - .unwrap() - .to_string_lossy() - .into_owned() - }; - let li = account(Platform::Lichess, "Magnus"); - assert_eq!(name(std::slice::from_ref(&li)), "Magnus (Lichess).pgn"); - let cc = account(Platform::ChessCom, "magnus"); - assert_eq!(name(&[li.clone(), cc]), "Magnus (Lichess + Chess.com).pgn"); - let other = account(Platform::ChessCom, "MagnusCarlsen"); - assert_eq!( - name(&[li, other]), - "Magnus (Lichess) + MagnusCarlsen (Chess.com).pgn" - ); - } - - #[test] - fn unfinished_lichess_games_come_later() { - let mut a = AccountState::default(); - let g = |id: &'static str, playing: bool| LichessGame { - id, - created: 10, - playing, - standard: true, - pgn: (!playing).then_some("1. e4 *"), - }; - // First run: a correspondence game is still on, another one is over. - assert!(!lichess_keep(&mut a, &g("corr", true))); - assert!(lichess_keep(&mut a, &g("blitz", false))); - assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); - // Asked about by id: still on, then over. - assert!(!lichess_keep(&mut a, &g("corr", true))); - assert_eq!(a.lichess_pending.len(), 1); - assert!(lichess_keep(&mut a, &g("corr", false))); - assert!(a.lichess_pending.is_empty()); - // A variant game is neither kept nor waited for. - let mut v = g("960", true); - v.standard = false; - assert!(!lichess_keep(&mut a, &v)); - assert!(a.lichess_pending.is_empty()); - // An unfinished game may come without its PGN, a finished one may not. - let json = |s: &str| serde_json::from_str::(s).unwrap(); - let on = json(r#"{"id":"a","createdAt":1,"status":"started"}"#); - assert!(lichess_game(&on).is_some_and(|g| g.playing)); - let over = json(r#"{"id":"a","createdAt":1,"status":"mate"}"#); - assert!(lichess_game(&over).is_none()); - } - - /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of - /// the repository): lookup, an interrupted Lichess download continued without gaps - /// or duplicates, a full Chess.com download, and an update that adds nothing. Run - /// with `CP_ONLINE_NICK= cargo test -p online-games online_live -- --ignored --nocapture`. - #[test] - #[ignore] - fn online_live() { - let Ok(nick) = std::env::var("CP_ONLINE_NICK") else { - eprintln!("skipped: no CP_ONLINE_NICK"); - return; - }; - assert_eq!(probe_all(), [true, true], "both platforms answer"); - assert_eq!( - lookup(Platform::Lichess, "no-such-player-cp-x9"), - Lookup::NotFound - ); - let dir = std::env::temp_dir().join(format!("cp-online-live-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let read_db = |path: &Path| { - let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) - .expect("opens"); - let mut sites = Vec::new(); - let mut problems = 0; - for i in 0..db.len() { - let g = db.load_game(i).expect("game"); - problems += usize::from(!g.diagnostics.is_empty()); - let e = &db.entries()[i]; - let site = e.tag("Link").or_else(|| e.tag("Site")).unwrap_or_default(); - sites.push(site.to_owned()); - } - (db.len(), sites, problems) - }; - - // Lichess: stop after about 150 games, twice, then compare with what the - // site says about those games: no gaps, no duplicates. - let Lookup::Found(li) = lookup(Platform::Lichess, &nick) else { - panic!("not on Lichess"); - }; - let path = dir.join("li.pgn"); - for round in 1..=2 { - let progress = AtomicUsize::new(0); - let cancel = AtomicBool::new(false); - let over = AtomicBool::new(false); - let done = std::thread::scope(|s| { - s.spawn(|| { - while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) { - std::thread::sleep(Duration::from_millis(50)); - } - cancel.store(true, Ordering::Relaxed); - }); - let r = download_to(std::slice::from_ref(&li), &path, &progress, &cancel); - over.store(true, Ordering::Relaxed); - r.expect("downloads") - }); - eprintln!("lichess round {round}: {done:?}"); - assert!(done.cancelled && done.added >= 150); - } - let (n, sites, problems) = read_db(&path); - let unique: std::collections::HashSet<_> = sites.iter().collect(); - assert_eq!(unique.len(), n, "no duplicates"); - assert_eq!(State::load(&path).unwrap().games as usize, n); - eprintln!("lichess: {n} games after two interrupted runs, {problems} with diagnostics"); - // The same games as one uninterrupted request for that many. - let (code, body) = get(&format!( - "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&max={n}\ - &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&moves=false", - li.username - )) - .expect("answers"); - assert_eq!(code, 200); - // Asked for JSON, Lichess answers one game per line. - let expected: Vec = body - .lines() - .filter_map(|l| serde_json::from_str::(l).ok()) - .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) - .collect(); - // Ours are the reference's first games, in its order (the reference may hold a - // few more: Lichess does not count `max` exactly as we count games). - if expected.len() < sites.len() || sites[..] != expected[..sites.len()] { - let only_ours: Vec<_> = sites.iter().filter(|x| !expected.contains(x)).collect(); - let only_ref: Vec<_> = expected.iter().filter(|x| !sites.contains(x)).collect(); - let first = sites.iter().zip(&expected).position(|(a, b)| a != b); - panic!( - "differ: first at {first:?}, ours {} ref {}, only ours {only_ours:?}, only in the reference {only_ref:?}", - sites.len(), - expected.len() - ); - } - - // Chess.com: everything, then an update that finds nothing new. - let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { - panic!("not on Chess.com"); - }; - let path = dir.join("cc.pgn"); - let never = AtomicBool::new(false); - let done = download_to( - std::slice::from_ref(&cc), - &path, - &AtomicUsize::new(0), - &never, - ) - .expect("downloads"); - eprintln!("chess.com: {done:?}"); - assert!(!done.cancelled && done.total > 0); - let again = download_to( - std::slice::from_ref(&cc), - &path, - &AtomicUsize::new(0), - &never, - ) - .expect("updates"); - assert_eq!((again.added, again.total), (0, done.total)); - let (n, sites, problems) = read_db(&path); - assert_eq!(n as u64, done.total); - let unique: std::collections::HashSet<_> = sites.iter().collect(); - assert_eq!(unique.len(), n, "no duplicates"); - eprintln!("chess.com: {n} games, {problems} with diagnostics"); - - // Both into one database: Chess.com whole, then Lichess stopped twice; the - // second run adds Lichess games only, without duplicates. - let path = dir.join("both.pgn"); - let accounts = [cc.clone(), li.clone()]; - let mut totals = Vec::new(); - for round in 1..=2 { - let progress = AtomicUsize::new(0); - let cancel = AtomicBool::new(false); - let over = AtomicBool::new(false); - let goal = if round == 1 { - done.total as usize + 100 - } else { - 100 - }; - let d = std::thread::scope(|s| { - s.spawn(|| { - while progress.load(Ordering::Relaxed) < goal && !over.load(Ordering::Relaxed) { - std::thread::sleep(Duration::from_millis(50)); - } - cancel.store(true, Ordering::Relaxed); - }); - let r = download_to(&accounts, &path, &progress, &cancel); - over.store(true, Ordering::Relaxed); - r.expect("downloads") - }); - eprintln!("both, round {round}: {d:?}"); - assert!(d.cancelled); - totals.push(d.total); - } - let state = State::load(&path).unwrap(); - assert_eq!(state.accounts.len(), 2); - assert_eq!(state.accounts[0].platform, Some(Platform::ChessCom)); - assert!(state.accounts[0].chesscom_month.is_some()); - assert!(state.accounts[1].lichess_last.is_some()); - let (n, sites, problems) = read_db(&path); - assert_eq!(n as u64, totals[1]); - let unique: std::collections::HashSet<_> = sites.iter().collect(); - assert_eq!(unique.len(), n, "no duplicates"); - let chesscom = sites.iter().filter(|s| s.contains("chess.com")).count() as u64; - assert_eq!(chesscom, done.total, "all of Chess.com, once"); - eprintln!("both: {n} games ({chesscom} from Chess.com), {problems} with diagnostics"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn probe_answers() { - let li: Value = serde_json::from_str( - r#"{"id":"lichess","username":"Lichess","count":{"all":0,"rated":0}}"#, - ) - .unwrap(); - assert!(probe_answer_ok(Platform::Lichess, &li)); - // A changed API (renamed or missing fields) is not offered. - let changed: Value = - serde_json::from_str(r#"{"id":"lichess","username":"Lichess","games":0}"#).unwrap(); - assert!(!probe_answer_ok(Platform::Lichess, &changed)); - let cc: Value = - serde_json::from_str(r#"{"player_id":41,"username":"erik","status":"staff"}"#).unwrap(); - assert!(probe_answer_ok(Platform::ChessCom, &cc)); - let html = Value::String("maintenance".into()); - assert!(!probe_answer_ok(Platform::ChessCom, &html)); - assert!(!probe_answer_ok(Platform::Lichess, &html)); - } - - #[test] - fn nicknames() { - assert!(valid_nick("Magnus_C-1")); - assert!(!valid_nick("a")); - assert!(!valid_nick("bad nick")); - assert!(!valid_nick("../etc")); - assert!(!valid_nick(&"x".repeat(31))); - } - - #[test] - fn state_round_trip() { - let dir = std::env::temp_dir().join(format!("cp-online-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let pgn = dir.join("Someone (Lichess).pgn"); - let s = State { - accounts: vec![AccountState { - platform: Some(Platform::Lichess), - username: "Someone".into(), - lichess_last: Some(1_700_000_000_000), - ..AccountState::default() - }], - games: 3, - ..State::default() - }; - s.save(&pgn).unwrap(); - assert_eq!(State::load(&pgn), Some(s)); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/crates/online-games/src/net.rs b/crates/online-games/src/net.rs new file mode 100644 index 0000000..d20cfff --- /dev/null +++ b/crates/online-games/src/net.rs @@ -0,0 +1,978 @@ +//! Talking to Lichess and Chess.com: lookups, probes, downloads into the database. + +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use serde_json::Value; + +use super::*; + +/// How many last bytes of the file the state remembers. +const TAIL: usize = 64; + +impl State { + fn save(&self, pgn: &Path) -> Result<(), Failure> { + let text = serde_json::to_string_pretty(self).map_err(|e| Failure::Disk(e.to_string()))?; + let path = state_path(pgn); + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, text) + .and_then(|_| std::fs::rename(&tmp, &path)) + .map_err(|e| Failure::Disk(e.to_string())) + } +} + +fn agent(stream: bool) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .user_agent(format!( + "ChessPenguin/{} (+https://chess.vrubel.xyz)", + env!("CARGO_PKG_VERSION") + )) + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(30))) + // A long export is one response: hours for the body (a stalled one ends). + .timeout_recv_body(if stream { + Some(Duration::from_secs(4 * 3600)) + } else { + Some(Duration::from_secs(60)) + }) + .build(); + ureq::Agent::new_with_config(config) +} + +/// Makes a request again when the connection broke (Lichess drops connections for a +/// minute or so after an export was cut short), waiting `waits` seconds in between; +/// stops waiting when cancelled. +fn retrying( + waits: &[u64], + cancel: &AtomicBool, + mut request: impl FnMut() -> Result, +) -> Result { + let mut waits = waits.iter(); + loop { + match request() { + Ok(r) => return Ok(r), + Err(e) => { + let Some(&secs) = waits.next() else { + return Err(Failure::Network(e.to_string())); + }; + for _ in 0..secs * 10 { + if cancel.load(Ordering::Relaxed) { + return Err(Failure::Network(e.to_string())); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + } + } +} + +/// Waits before the attempts of a download request: about a minute in all. +const DOWNLOAD_WAITS: &[u64] = &[3, 10, 20, 30]; + +/// GET returning (status, body); the body of an error status is not read. +fn get(url: &str) -> Result<(u16, String), Failure> { + let never = AtomicBool::new(false); + // The whole exchange is repeated: a connection may also break in the body. + retrying(&[2, 5], &never, || { + let mut resp = agent(false) + .get(url) + .header("Accept", "application/json") + .call()?; + let status = resp.status().as_u16(); + if status != 200 { + return Ok((status, String::new())); + } + let body = resp + .body_mut() + .with_config() + .limit(64 << 20) + .read_to_string()?; + Ok((status, body)) + }) + .and_then(|(status, body)| { + if status == 429 { + Err(Failure::RateLimited) + } else { + Ok((status, body)) + } + }) +} + +fn json(url: &str) -> Result, Failure> { + match get(url)? { + (200, body) => serde_json::from_str(&body) + .map(Some) + .map_err(|e| Failure::Unexpected(e.to_string())), + (404, _) => Ok(None), + (code, _) => Err(Failure::Unexpected(format!("HTTP {code}"))), + } +} + +/// Whether the platform answers the way this code expects: the profile of an account +/// that has always existed (Lichess's own, Chess.com's founder's). +pub fn probe(p: Platform) -> bool { + let url = match p { + Platform::Lichess => "https://lichess.org/api/user/lichess", + Platform::ChessCom => "https://api.chess.com/pub/player/erik", + }; + matches!(json(url), Ok(Some(v)) if probe_answer_ok(p, &v)) +} + +/// The probe's answer has the fields this code relies on. +fn probe_answer_ok(p: Platform, v: &Value) -> bool { + match p { + Platform::Lichess => { + v["id"] == "lichess" && v["username"].is_string() && v["count"]["all"].is_u64() + } + Platform::ChessCom => v["player_id"].is_u64() && v["username"] == "erik", + } +} + +/// Both platforms probed (in parallel); `[lichess, chess.com]`. +pub fn probe_all() -> [bool; 2] { + std::thread::scope(|s| { + let l = s.spawn(|| probe(Platform::Lichess)); + let c = s.spawn(|| probe(Platform::ChessCom)); + [l.join().unwrap_or(false), c.join().unwrap_or(false)] + }) +} + +/// Looks the nickname up on the platform. +pub fn lookup(p: Platform, nick: &str) -> Lookup { + let nick = nick.trim(); + if !valid_nick(nick) { + return Lookup::NotFound; + } + let result = match p { + Platform::Lichess => json(&format!("https://lichess.org/api/user/{nick}")).map(|v| { + v.filter(|v| v["disabled"] != true).and_then(|v| { + Some(Account { + platform: p, + username: v["username"].as_str()?.to_owned(), + games: v["count"]["all"].as_u64(), + months: None, + }) + }) + }), + Platform::ChessCom => { + let lower = nick.to_ascii_lowercase(); + json(&format!("https://api.chess.com/pub/player/{lower}")).and_then(|v| { + let Some(username) = v.and_then(|v| v["username"].as_str().map(str::to_owned)) + else { + return Ok(None); + }; + // Chess.com answers in lower case; the user's spelling reads better. + let username = if username.eq_ignore_ascii_case(nick) { + nick.to_owned() + } else { + username + }; + let months = archives(&lower)?.len(); + Ok(Some(Account { + platform: p, + username, + games: None, + months: Some(months), + })) + }) + } + }; + match result { + Ok(Some(a)) => Lookup::Found(a), + Ok(None) => Lookup::NotFound, + Err(e) => Lookup::Failed(e), + } +} + +/// Chess.com's monthly archive URLs of a player, oldest first. +fn archives(lower: &str) -> Result, Failure> { + let v = json(&format!( + "https://api.chess.com/pub/player/{lower}/games/archives" + ))? + .ok_or_else(|| Failure::Unexpected("no archives".into()))?; + let list = v["archives"] + .as_array() + .ok_or_else(|| Failure::Unexpected("archives".into()))?; + Ok(list + .iter() + .filter_map(|u| u.as_str().map(str::to_owned)) + .collect()) +} + +/// The databases being written now: one download per file at a time. +static WRITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Holds a database for one download; released when dropped. +struct Claim(PathBuf); + +impl Claim { + fn take(path: &Path) -> Option { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + if w.iter().any(|p| p == path) { + return None; + } + w.push(path.to_owned()); + Some(Claim(path.to_owned())) + } +} + +impl Drop for Claim { + fn drop(&mut self) { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + w.retain(|p| *p != self.0); + } +} + +/// Appends games to the database file and keeps the state in step. +struct Writer { + path: PathBuf, + file: std::io::BufWriter, + state: State, + added: u64, + /// The file's length and last bytes as written (flushed or not). + len: u64, + tail: Vec, +} + +impl Writer { + /// Opens the database for appending; a state that does not match the file (the file + /// is gone, or a crash left games after the state) is put right first. + fn open(path: &Path, mut state: State) -> Result { + let disk = |e: std::io::Error| Failure::Disk(e.to_string()); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(disk)?; + } + let file = std::fs::OpenOptions::new() + .create(true) + .read(true) + .append(true) + .open(path) + .map_err(disk)?; + let mut len = file.metadata().map_err(disk)?.len(); + if let Some(b) = state.bytes + && len > b + && b as usize >= state.tail.len() + { + let mut end = vec![0; state.tail.len()]; + use std::io::{Read, Seek, SeekFrom}; + let mut f = &file; + f.seek(SeekFrom::Start(b - state.tail.len() as u64)) + .and_then(|_| f.read_exact(&mut end)) + .map_err(disk)?; + if end == state.tail { + file.set_len(b).map_err(disk)?; + len = b; + } + } + let tail = if len == state.bytes.unwrap_or(u64::MAX) { + std::mem::take(&mut state.tail) + } else { + Vec::new() + }; + Ok(Writer { + path: path.to_owned(), + file: std::io::BufWriter::new(file), + state, + added: 0, + len, + tail, + }) + } + + fn game(&mut self, pgn: &str) -> Result<(), Failure> { + let pgn = pgn.trim(); + if pgn.is_empty() { + return Ok(()); + } + for part in [pgn.as_bytes(), b"\n\n"] { + self.file + .write_all(part) + .map_err(|e| Failure::Disk(e.to_string()))?; + self.len += part.len() as u64; + self.tail.extend_from_slice(part); + } + if self.tail.len() > TAIL { + self.tail.drain(..self.tail.len() - TAIL); + } + self.added += 1; + self.state.games += 1; + Ok(()) + } + + /// Makes what was written durable, the state last (it never runs ahead of the file). + fn commit(&mut self) -> Result<(), Failure> { + self.file + .flush() + .map_err(|e| Failure::Disk(e.to_string()))?; + self.state.bytes = Some(self.len); + self.state.tail = self.tail.clone(); + self.state.save(&self.path) + } + + fn done(mut self, cancelled: bool) -> Result { + if !cancelled { + self.state.updated = Some(now_secs()); + } + self.commit()?; + Ok(Done { + path: self.path, + added: self.added, + total: self.state.games, + cancelled, + }) + } +} + +/// Fetches the games of `accounts` new since the last run into the database at `path` +/// (one database for all of them); `progress` counts the games added, `status` tells +/// what is being fetched. Cancelling keeps what was fetched. One download per database +/// at a time ([`Failure::Busy`] otherwise). +pub fn download( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let _claim = Claim::take(path).ok_or(Failure::Busy)?; + // Another ChessPenguin running may download into the same database: a file lock + // (released when the file closes, also if the process dies). + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(|e| Failure::Disk(e.to_string()))?; + } + let lock = std::fs::File::create(path.with_extension("online.lock")) + .map_err(|e| Failure::Disk(e.to_string()))?; + if let Err(e) = lock.try_lock() { + return Err(match e { + std::fs::TryLockError::WouldBlock => Failure::Busy, + std::fs::TryLockError::Error(e) => Failure::Disk(e.to_string()), + }); + } + let path = path.to_owned(); + let mut state = State::load(&path) + // The games are gone (the file was deleted): fetch them again. + .filter(|s| path.exists() || s.games == 0) + .unwrap_or_else(|| { + // A database without its state: start it anew rather than append duplicates. + let _ = std::fs::remove_file(&path); + State::default() + }); + // Accounts not in the database yet start from their first game. + for a in accounts { + if !state.holds(a) { + state.accounts.push(AccountState { + platform: Some(a.platform), + username: a.username.clone(), + ..AccountState::default() + }); + } + } + let mut w = Writer::open(&path, state)?; + let mut result = Ok(false); + for i in 0..w.state.accounts.len() { + let Some(k) = accounts.iter().position(|a| w.state.accounts[i].is(a)) else { + continue; + }; + status.account.store(k, Ordering::Relaxed); + status.games.store(0, Ordering::Relaxed); + result = match w.state.accounts[i].platform { + Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel, status), + Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status), + None => Ok(false), + }; + if !matches!(result, Ok(false)) { + break; + } + } + match result { + Ok(c) => w.done(c), + Err(e) => { + // Keep what arrived before the failure; the next update continues. + let _ = w.commit(); + Err(e) + } + } +} + +#[cfg(test)] +fn download_to( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + download(accounts, path, progress, cancel, &Progress::default()) +} + +/// Lichess's answer for one game, as far as the download cares. +struct LichessGame<'a> { + id: &'a str, + created: i64, + /// Still being played (not exported as a game yet). + playing: bool, + standard: bool, + /// Present for finished games (an unfinished one may come without it). + pgn: Option<&'a str>, +} + +fn lichess_game(v: &Value) -> Option> { + let g = LichessGame { + id: v["id"].as_str()?, + created: v["createdAt"].as_i64()?, + playing: matches!(v["status"].as_str(), Some("created" | "started")), + standard: v["variant"] + .as_str() + .is_none_or(|x| x == "standard" || x == "fromPosition"), + pgn: v["pgn"].as_str(), + }; + (g.playing || g.pgn.is_some()).then_some(g) +} + +/// Whether to write a game of the Lichess export; an unfinished one is remembered as +/// pending instead (asked about by id next time), a pending one that ended is written. +fn lichess_keep(a: &mut AccountState, g: &LichessGame) -> bool { + let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id); + if g.playing { + if pending.is_none() && g.standard { + a.lichess_pending.push((g.id.to_owned(), g.created)); + } + return false; + } + if let Some(k) = pending { + a.lichess_pending.remove(k); + } + g.standard +} + +/// A pending game Lichess no longer returns is given up after a year. +const PENDING_DAYS: i64 = 365; + +/// Reads a Lichess NDJSON answer line by line. `Ok(true)` when cancelled. +fn lichess_lines( + resp: ureq::http::Response, + cancel: &AtomicBool, + mut each: impl FnMut(usize, &Value) -> Result<(), Failure>, +) -> Result { + match resp.status().as_u16() { + 200 => {} + 429 => return Err(Failure::RateLimited), + code => return Err(Failure::Unexpected(format!("HTTP {code}"))), + } + let reader = BufReader::new(resp.into_body().into_reader()); + for (n, line) in reader.lines().enumerate() { + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let line = line.map_err(|e| Failure::Network(e.to_string()))?; + if line.trim().is_empty() { + continue; + } + let v: Value = + serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; + each(n, &v)?; + } + Ok(false) +} + +const LICHESS_PARAMS: &str = "pgnInJson=true&clocks=false&evals=false&opening=true"; + +/// The games of account `i` of the writer's database from Lichess: first the pending +/// (unfinished last time) ones by id, then the new ones. `Ok(true)` when cancelled. +fn lichess( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let write = |w: &mut Writer, v: &Value| -> Result { + let g = lichess_game(v) + .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; + if lichess_keep(&mut w.state.accounts[i], &g) + && let Some(pgn) = g.pgn + { + let pgn = pgn.to_owned(); + w.game(&pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + } + Ok(g.created) + }; + let pending: Vec = w.state.accounts[i] + .lichess_pending + .iter() + .map(|(id, _)| id.clone()) + .collect(); + for chunk in pending.chunks(300) { + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .post(&format!( + "https://lichess.org/api/games/export/_ids?{LICHESS_PARAMS}" + )) + .header("Accept", "application/x-ndjson") + .send(chunk.join(",")) + })?; + if lichess_lines(resp, cancel, |_, v| write(w, v).map(|_| ()))? { + return Ok(true); + } + } + let year_ago = now_secs() * 1000 - PENDING_DAYS * 86_400_000; + w.state.accounts[i] + .lichess_pending + .retain(|(_, created)| *created > year_ago); + w.commit()?; + + let a = &w.state.accounts[i]; + let mut url = format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&{LICHESS_PARAMS}", + a.username + ); + if let Some(last) = a.lichess_last { + url.push_str(&format!("&since={}", last + 1)); + } + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .get(&url) + .header("Accept", "application/x-ndjson") + .call() + })?; + lichess_lines(resp, cancel, |n, v| { + let created = write(w, v)?; + let a = &mut w.state.accounts[i]; + a.lichess_last = Some(a.lichess_last.map_or(created, |l| l.max(created))); + if n % 100 == 99 { + w.commit()?; + } + Ok(()) + }) +} + +/// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when +/// cancelled. +fn chesscom( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let lower = w.state.accounts[i].username.to_ascii_lowercase(); + let months = archives(&lower)?; + status.months_total.store(months.len(), Ordering::Relaxed); + status.months_done.store(0, Ordering::Relaxed); + for url in months { + status.months_done.fetch_add(1, Ordering::Relaxed); + // ".../games/2026/10" → "2026/10"; months before the last fetched are done. + let month = url.rsplitn(3, '/').take(2).collect::>(); + let month = format!( + "{}/{}", + month.get(1).unwrap_or(&""), + month.first().unwrap_or(&"") + ); + let a = &w.state.accounts[i]; + if a.chesscom_month.as_ref().is_some_and(|m| month < *m) { + continue; + } + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let v = json(&url)?.ok_or_else(|| Failure::Unexpected(format!("{month}: not found")))?; + let games = v["games"] + .as_array() + .ok_or_else(|| Failure::Unexpected(format!("{month}: no games")))?; + let mut list: Vec<(i64, &str)> = games + .iter() + .filter(|g| g["rules"] == "chess") + .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) + .collect(); + list.sort_by_key(|(t, _)| *t); + let a = &w.state.accounts[i]; + let same_month = a.chesscom_month.as_deref() == Some(month.as_str()); + let last = if same_month { + a.chesscom_last_end + } else { + None + }; + for (end, pgn) in list { + if last.is_some_and(|l| end <= l) { + continue; + } + w.game(pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + w.state.accounts[i].chesscom_last_end = Some(end); + } + // The mark moves to this month even when it had no standard games (the end + // time then still belongs to an earlier month and is not compared). + w.state.accounts[i].chesscom_month = Some(month); + w.commit()?; + } + Ok(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("cp-online-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn account(p: Platform, name: &str) -> Account { + Account { + platform: p, + username: name.into(), + games: None, + months: None, + } + } + + const GAME: &str = "[Event \"x\"]\n\n1. e4 e5 1-0"; + + #[test] + fn a_crash_leaves_no_duplicates() { + let dir = temp_dir("crash"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + ..AccountState::default() + }], + ..State::default() + }; + let mut w = Writer::open(&path, state).unwrap(); + w.game(GAME).unwrap(); + w.game(GAME).unwrap(); + w.commit().unwrap(); + let good = std::fs::read(&path).unwrap(); + // Games written after the last commit, then the process died. + w.game(GAME).unwrap(); + w.file.flush().unwrap(); + drop(w); + assert!(std::fs::read(&path).unwrap().len() > good.len()); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + assert_eq!(w.state.games, 2); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), good, "cut back to the state"); + + // Somebody else changed the file: it is left alone. + let mut other = good.clone(); + other[0] = b' '; + other.extend_from_slice(GAME.as_bytes()); + std::fs::write(&path, &other).unwrap(); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), other); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_deleted_database_is_downloaded_again() { + let dir = temp_dir("deleted"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + lichess_last: Some(5), + ..AccountState::default() + }], + games: 7, + ..State::default() + }; + state.save(&path).unwrap(); + let never = AtomicBool::new(false); + // No account asked for: nothing fetched, only the state put right. + let d = download_to(&[], &path, &AtomicUsize::new(0), &never).unwrap(); + assert_eq!(d.total, 0); + let s = State::load(&path).unwrap_or_default(); + assert!(s.accounts.iter().all(|a| a.lichess_last.is_none())); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn one_download_per_database() { + let path = PathBuf::from("/nonexistent/cp-claim.pgn"); + let first = Claim::take(&path).expect("free"); + assert!(Claim::take(&path).is_none()); + let never = AtomicBool::new(false); + assert_eq!( + download_to(&[], &path, &AtomicUsize::new(0), &never), + Err(Failure::Busy) + ); + drop(first); + assert!(Claim::take(&path).is_some()); + } + + #[test] + fn names_of_merged_databases() { + let name = |a: &[Account]| { + combined_path(Path::new("/online"), a) + .unwrap() + .file_name() + .unwrap() + .to_string_lossy() + .into_owned() + }; + let li = account(Platform::Lichess, "Magnus"); + assert_eq!(name(std::slice::from_ref(&li)), "Magnus (Lichess).pgn"); + let cc = account(Platform::ChessCom, "magnus"); + assert_eq!(name(&[li.clone(), cc]), "Magnus (Lichess + Chess.com).pgn"); + let other = account(Platform::ChessCom, "MagnusCarlsen"); + assert_eq!( + name(&[li, other]), + "Magnus (Lichess) + MagnusCarlsen (Chess.com).pgn" + ); + } + + #[test] + fn unfinished_lichess_games_come_later() { + let mut a = AccountState::default(); + let g = |id: &'static str, playing: bool| LichessGame { + id, + created: 10, + playing, + standard: true, + pgn: (!playing).then_some("1. e4 *"), + }; + // First run: a correspondence game is still on, another one is over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert!(lichess_keep(&mut a, &g("blitz", false))); + assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); + // Asked about by id: still on, then over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert_eq!(a.lichess_pending.len(), 1); + assert!(lichess_keep(&mut a, &g("corr", false))); + assert!(a.lichess_pending.is_empty()); + // A variant game is neither kept nor waited for. + let mut v = g("960", true); + v.standard = false; + assert!(!lichess_keep(&mut a, &v)); + assert!(a.lichess_pending.is_empty()); + // An unfinished game may come without its PGN, a finished one may not. + let json = |s: &str| serde_json::from_str::(s).unwrap(); + let on = json(r#"{"id":"a","createdAt":1,"status":"started"}"#); + assert!(lichess_game(&on).is_some_and(|g| g.playing)); + let over = json(r#"{"id":"a","createdAt":1,"status":"mate"}"#); + assert!(lichess_game(&over).is_none()); + } + + /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of + /// the repository): lookup, an interrupted Lichess download continued without gaps + /// or duplicates, a full Chess.com download, and an update that adds nothing. Run + /// with `CP_ONLINE_NICK= cargo test -p online-games online_live -- --ignored --nocapture`. + #[test] + #[ignore] + fn online_live() { + let Ok(nick) = std::env::var("CP_ONLINE_NICK") else { + eprintln!("skipped: no CP_ONLINE_NICK"); + return; + }; + assert_eq!(probe_all(), [true, true], "both platforms answer"); + assert_eq!( + lookup(Platform::Lichess, "no-such-player-cp-x9"), + Lookup::NotFound + ); + let dir = std::env::temp_dir().join(format!("cp-online-live-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let read_db = |path: &Path| { + let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) + .expect("opens"); + let mut sites = Vec::new(); + let mut problems = 0; + for i in 0..db.len() { + let g = db.load_game(i).expect("game"); + problems += usize::from(!g.diagnostics.is_empty()); + let e = &db.entries()[i]; + let site = e.tag("Link").or_else(|| e.tag("Site")).unwrap_or_default(); + sites.push(site.to_owned()); + } + (db.len(), sites, problems) + }; + + // Lichess: stop after about 150 games, twice, then compare with what the + // site says about those games: no gaps, no duplicates. + let Lookup::Found(li) = lookup(Platform::Lichess, &nick) else { + panic!("not on Lichess"); + }; + let path = dir.join("li.pgn"); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let done = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(std::slice::from_ref(&li), &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("lichess round {round}: {done:?}"); + assert!(done.cancelled && done.added >= 150); + } + let (n, sites, problems) = read_db(&path); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + assert_eq!(State::load(&path).unwrap().games as usize, n); + eprintln!("lichess: {n} games after two interrupted runs, {problems} with diagnostics"); + // The same games as one uninterrupted request for that many. + let (code, body) = get(&format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&max={n}\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&moves=false", + li.username + )) + .expect("answers"); + assert_eq!(code, 200); + // Asked for JSON, Lichess answers one game per line. + let expected: Vec = body + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) + .collect(); + // Ours are the reference's first games, in its order (the reference may hold a + // few more: Lichess does not count `max` exactly as we count games). + if expected.len() < sites.len() || sites[..] != expected[..sites.len()] { + let only_ours: Vec<_> = sites.iter().filter(|x| !expected.contains(x)).collect(); + let only_ref: Vec<_> = expected.iter().filter(|x| !sites.contains(x)).collect(); + let first = sites.iter().zip(&expected).position(|(a, b)| a != b); + panic!( + "differ: first at {first:?}, ours {} ref {}, only ours {only_ours:?}, only in the reference {only_ref:?}", + sites.len(), + expected.len() + ); + } + + // Chess.com: everything, then an update that finds nothing new. + let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { + panic!("not on Chess.com"); + }; + let path = dir.join("cc.pgn"); + let never = AtomicBool::new(false); + let done = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("downloads"); + eprintln!("chess.com: {done:?}"); + assert!(!done.cancelled && done.total > 0); + let again = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("updates"); + assert_eq!((again.added, again.total), (0, done.total)); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, done.total); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + eprintln!("chess.com: {n} games, {problems} with diagnostics"); + + // Both into one database: Chess.com whole, then Lichess stopped twice; the + // second run adds Lichess games only, without duplicates. + let path = dir.join("both.pgn"); + let accounts = [cc.clone(), li.clone()]; + let mut totals = Vec::new(); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let goal = if round == 1 { + done.total as usize + 100 + } else { + 100 + }; + let d = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < goal && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(&accounts, &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("both, round {round}: {d:?}"); + assert!(d.cancelled); + totals.push(d.total); + } + let state = State::load(&path).unwrap(); + assert_eq!(state.accounts.len(), 2); + assert_eq!(state.accounts[0].platform, Some(Platform::ChessCom)); + assert!(state.accounts[0].chesscom_month.is_some()); + assert!(state.accounts[1].lichess_last.is_some()); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, totals[1]); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + let chesscom = sites.iter().filter(|s| s.contains("chess.com")).count() as u64; + assert_eq!(chesscom, done.total, "all of Chess.com, once"); + eprintln!("both: {n} games ({chesscom} from Chess.com), {problems} with diagnostics"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn probe_answers() { + let li: Value = serde_json::from_str( + r#"{"id":"lichess","username":"Lichess","count":{"all":0,"rated":0}}"#, + ) + .unwrap(); + assert!(probe_answer_ok(Platform::Lichess, &li)); + // A changed API (renamed or missing fields) is not offered. + let changed: Value = + serde_json::from_str(r#"{"id":"lichess","username":"Lichess","games":0}"#).unwrap(); + assert!(!probe_answer_ok(Platform::Lichess, &changed)); + let cc: Value = + serde_json::from_str(r#"{"player_id":41,"username":"erik","status":"staff"}"#).unwrap(); + assert!(probe_answer_ok(Platform::ChessCom, &cc)); + let html = Value::String("maintenance".into()); + assert!(!probe_answer_ok(Platform::ChessCom, &html)); + assert!(!probe_answer_ok(Platform::Lichess, &html)); + } + + #[test] + fn nicknames() { + assert!(valid_nick("Magnus_C-1")); + assert!(!valid_nick("a")); + assert!(!valid_nick("bad nick")); + assert!(!valid_nick("../etc")); + assert!(!valid_nick(&"x".repeat(31))); + } + + #[test] + fn state_round_trip() { + let dir = std::env::temp_dir().join(format!("cp-online-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let pgn = dir.join("Someone (Lichess).pgn"); + let s = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "Someone".into(), + lichess_last: Some(1_700_000_000_000), + ..AccountState::default() + }], + games: 3, + ..State::default() + }; + s.save(&pgn).unwrap(); + assert_eq!(State::load(&pgn), Some(s)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/play/Cargo.toml b/crates/play/Cargo.toml index 4713787..9764312 100644 --- a/crates/play/Cargo.toml +++ b/crates/play/Cargo.toml @@ -13,3 +13,7 @@ chess-core.workspace = true shakmaty.workspace = true uci.workspace = true getrandom = "0.3" + +# Random numbers in a browser (crypto.getRandomValues). +[target.'cfg(target_family = "wasm")'.dependencies] +getrandom = { version = "0.3", features = ["wasm_js"] } diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs index f4b9f39..dd344bb 100644 --- a/crates/play/src/lib.rs +++ b/crates/play/src/lib.rs @@ -1,12 +1,16 @@ //! A game against the computer (docs/design/play-mode.md, android-play.md §31): how it //! ends, how long the opponent "thinks", its resignation judged by an engine, and Rodent -//! (`rodent`). Shared by the desktop and the Android apps; nothing here draws. +//! (`rodent`). Shared by the desktop and the Android apps; nothing here draws. The +//! engines that play or judge run as processes, each driven from a thread: a browser +//! cannot start them. pub mod rodent; mod rodent4_files; -use std::sync::mpsc::{Receiver, Sender, channel}; -use std::time::{Duration, Instant}; +use std::sync::mpsc::{Receiver, Sender}; +use std::time::Duration; +#[cfg(not(target_family = "wasm"))] +use std::{sync::mpsc::channel, time::Instant}; use shakmaty::zobrist::Zobrist64; use shakmaty::{Chess, Color, EnPassantMode, Position}; @@ -259,6 +263,8 @@ pub struct Judge { impl Judge { /// The engine of `config` with `options` set (an Android Stockfish: its `EvalFile`); /// `wake` is called when an answer comes (the app draws again). + /// (A process driven from a thread: not in a browser.) + #[cfg(not(target_family = "wasm"))] pub fn start( config: uci::EngineConfig, options: Vec<(String, String)>, diff --git a/crates/play/src/rodent.rs b/crates/play/src/rodent.rs index 6865562..9341a24 100644 --- a/crates/play/src/rodent.rs +++ b/crates/play/src/rodent.rs @@ -4,11 +4,15 @@ //! thread of its own. Shared by the desktop and the Android apps; nothing here draws. use std::collections::BTreeMap; -use std::sync::mpsc::{Sender, channel}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard}; -use std::time::{Duration, Instant}; +use std::time::Duration; +#[cfg(not(target_family = "wasm"))] +use std::{ + sync::mpsc::{Sender, channel}, + sync::{Arc, Condvar, Mutex, MutexGuard}, + time::Instant, +}; -use shakmaty::{Chess, Move}; +use shakmaty::Move; pub use crate::rodent4_files::{COMMIT, FILES, PERSONALITY_BOOKS}; @@ -556,17 +560,19 @@ pub enum Failure { Search(String), } +#[cfg(not(target_family = "wasm"))] /// A move asked for: the game for the engine, its position now, the pause. struct Request { generation: u64, pos: uci::EnginePosition, - now: Chess, + now: shakmaty::Chess, pause: Duration, } /// Rodent's move, or none (no legal move it gave), and the time it took. pub type Answer = (Option, Duration); +#[cfg(not(target_family = "wasm"))] #[derive(Default)] struct State { /// The request asked last (bumped by `forget`). @@ -577,12 +583,14 @@ struct State { failure: Option, } +#[cfg(not(target_family = "wasm"))] #[derive(Default)] struct Shared { state: Mutex, changed: Condvar, } +#[cfg(not(target_family = "wasm"))] impl Shared { fn lock(&self) -> MutexGuard<'_, State> { self.state.lock().unwrap_or_else(|e| e.into_inner()) @@ -594,6 +602,7 @@ impl Shared { } } +#[cfg(not(target_family = "wasm"))] /// Rodent playing one game, in its own thread (a UCI child process): it thinks during /// the pause a move should take (a game's own clock is not its business: Maia's pause /// rule paces it) and answers after it. Only the newest request counts; the answer to @@ -603,6 +612,7 @@ pub struct RodentPlayer { shared: Arc, } +#[cfg(not(target_family = "wasm"))] impl RodentPlayer { /// The engine of `config` (its folder, or its home in the environment: Android) /// playing `style_id` at `uci_elo` (none: full strength), with its opening book when @@ -709,7 +719,7 @@ impl RodentPlayer { /// Asks for a move in `now` (`pos`: the game to it for the engine) after `pause`; /// the request's number, for [`RodentPlayer::wait`]. - pub fn ask(&self, pos: uci::EnginePosition, now: Chess, pause: Duration) -> u64 { + pub fn ask(&self, pos: uci::EnginePosition, now: shakmaty::Chess, pause: Duration) -> u64 { let generation = { let mut s = self.shared.lock(); s.generation += 1; @@ -842,14 +852,14 @@ mod tests { let start = || uci::EnginePosition::startpos(Vec::::new()); let pause = Duration::from_millis(400); // Asked twice: the first is passed over, the second answered with a legal move. - let first = player.ask(start(), Chess::default(), pause); - let second = player.ask(start(), Chess::default(), pause); + let first = player.ask(start(), shakmaty::Chess::default(), pause); + let second = player.ask(start(), shakmaty::Chess::default(), pause); assert_eq!(player.wait(first), None); let (m, spent) = player.wait(second).expect("an answer"); assert!(m.is_some(), "{:?}", player.failure()); assert!(spent >= pause); // A request forgotten ends its wait at once. - let third = player.ask(start(), Chess::default(), pause); + let third = player.ask(start(), shakmaty::Chess::default(), pause); player.forget(); assert_eq!(player.wait(third), None); assert_eq!(player.failure(), None); diff --git a/crates/prep/src/lib.rs b/crates/prep/src/lib.rs index 04cdcac..950169d 100644 --- a/crates/prep/src/lib.rs +++ b/crates/prep/src/lib.rs @@ -21,7 +21,9 @@ use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::time::SystemTime; use chess_import::Database; -use game_review::{JobEvent, JobFailure, JobSettings, SEARCH_NODES, SEARCH_VERSION, Target}; +use game_review::{JobEvent, SEARCH_NODES, SEARCH_VERSION, Target}; +#[cfg(not(target_family = "wasm"))] +use game_review::{JobFailure, JobSettings}; use serde::{Deserialize, Serialize}; use uci::EnginePosition; @@ -617,6 +619,8 @@ pub struct Progress { pub nps: u64, } +// The engines run as processes, each driven from a thread: not in a browser. +#[cfg(not(target_family = "wasm"))] /// Runs the engine over the positions `report` lacks (the cache /// is consulted first and fed as results come; `cache_dir` saves it every few /// hundred positions and at the end), updating the report as results come in. diff --git a/crates/trainer/Cargo.toml b/crates/trainer/Cargo.toml index 132ca15..419cdce 100644 --- a/crates/trainer/Cargo.toml +++ b/crates/trainer/Cargo.toml @@ -12,4 +12,5 @@ publish = false chess-core.workspace = true serde.workspace = true serde_json.workspace = true +web-time.workspace = true chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } diff --git a/crates/trainer/src/lib.rs b/crates/trainer/src/lib.rs index 0b4f12d..2ba57e7 100644 --- a/crates/trainer/src/lib.rs +++ b/crates/trainer/src/lib.rs @@ -11,7 +11,8 @@ use std::path::PathBuf; use std::sync::Mutex; -use std::time::{Duration, Instant}; +use std::time::Duration; +use web_time::Instant; use chess_core::shakmaty::fen::Fen; use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Move, Square}; diff --git a/crates/uci/Cargo.toml b/crates/uci/Cargo.toml index 9c9253f..277b87b 100644 --- a/crates/uci/Cargo.toml +++ b/crates/uci/Cargo.toml @@ -4,10 +4,17 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true -description = "UCI chess engine process supervisor (no UI dependencies)" +description = "UCI chess engine supervisor: a process, or a Web Worker in a browser (no UI dependencies)" [dependencies] thiserror.workspace = true +web-time.workspace = true + +# The engine as a Web Worker in a browser. +[target.'cfg(target_family = "wasm")'.dependencies] +wasm-bindgen = "0.2.129" +js-sys = "0.3" +web-sys = { version = "0.3", features = ["Worker", "MessageEvent", "ErrorEvent"] } [target.'cfg(unix)'.dependencies] # nice(2) for EngineConfig::nice (std has no way to lower a child's priority). @@ -19,3 +26,9 @@ name = "fake_uci" path = "src/bin/fake_uci.rs" test = false doc = false + +# tests/worker.rs: the worker transport in a browser (docs/dev/web.md). +[target.'cfg(target_family = "wasm")'.dev-dependencies] +wasm-bindgen-test = "0.3" +wasm-bindgen-futures = "0.4" +web-sys = { version = "0.3", features = ["Window", "Blob", "BlobPropertyBag", "Url"] } diff --git a/crates/uci/src/events.rs b/crates/uci/src/events.rs new file mode 100644 index 0000000..16a1460 --- /dev/null +++ b/crates/uci/src/events.rs @@ -0,0 +1,52 @@ +//! What a running engine tells the UI, whatever carries it. + +use crate::types::{SearchId, SearchInfo}; + +/// Callback invoked after every new event (from the transport's thread on a +/// computer); the UI passes `ctx.request_repaint()` here. +pub type Waker = Box; + +/// Event delivered to the UI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EngineEvent { + /// `position` + `go` for this id were sent to the engine. + SearchStarted { search_id: SearchId }, + /// The request was replaced by a newer one (or cancelled by `stop`) + /// before it was sent to the engine; no events will follow for this id. + Superseded { search_id: SearchId }, + /// Search output. Only lines with a score or a PV are forwarded. + Info { + search_id: SearchId, + info: SearchInfo, + }, + /// Final `bestmove` of a started search. Exactly one per `SearchStarted` + /// unless the engine terminates first. + BestMove { + search_id: SearchId, + best: Option, + ponder: Option, + }, + /// `info string`, attributed to the running search if any. + InfoString { + search_id: Option, + text: String, + }, + /// Malformed or unexpected engine output; the line was skipped. + Warning(String), + /// The supervisor has stopped; the handle is no longer usable. + Terminated(TerminationReason), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TerminationReason { + /// `quit()` or drop of the handle. + Quit { + status: Option, + }, + /// The engine exited on its own (crash, end of its output, write failure). + Exited { + status: Option, + }, + /// The engine did not answer `stop` or `isready` in time and was killed. + Hung { waiting_for: &'static str }, +} diff --git a/crates/uci/src/lib.rs b/crates/uci/src/lib.rs index b8c8a06..db125eb 100644 --- a/crates/uci/src/lib.rs +++ b/crates/uci/src/lib.rs @@ -1,10 +1,13 @@ -//! UCI engine process supervisor. +//! UCI engine supervisor. //! -//! The engine runs as a separate child process started without a shell. -//! stdout and stderr are read by two dedicated threads; a supervisor thread -//! owns the protocol state machine. The UI talks to it through the -//! non-blocking [`EngineHandle`] and polls [`EngineEvent`]s every frame; the -//! [`Waker`] callback is invoked after each new event. +//! The protocol is a state machine without I/O ([`protocol`]); a transport drives +//! it. On a computer the engine is a child process started without a shell: +//! stdout and stderr are read by two dedicated threads, a supervisor thread +//! feeds the machine. The UI talks to it through the non-blocking +//! [`EngineHandle`] and polls [`EngineEvent`]s every frame; the [`Waker`] +//! callback is invoked after each new event. WebAssembly in a browser has no +//! processes: there the engine is a Web Worker, its handle the same, its start +//! not blocking ([`Engine::start_worker`]). //! //! Search boundary: UCI has no request ids. A new `position`/`go` is written //! only after the previous search ended with `bestmove` and a subsequent @@ -14,14 +17,23 @@ //! [`EngineEvent::Superseded`]. No dependency on egui or chess-core: //! positions are strings (FEN / UCI moves). -mod engine; mod error; +mod events; pub mod parse; +#[cfg(not(target_family = "wasm"))] +mod process; +mod protocol; mod types; +#[cfg(target_family = "wasm")] +mod worker; -pub use engine::{Engine, EngineConfig, EngineEvent, EngineHandle, TerminationReason, Waker}; pub use error::EngineError; +pub use events::{EngineEvent, TerminationReason, Waker}; +#[cfg(not(target_family = "wasm"))] +pub use process::{Engine, EngineConfig, EngineHandle}; pub use types::{ EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score, ScoreBound, SearchId, SearchInfo, SearchLimits, Side, Timeouts, WhiteEval, WhiteScore, }; +#[cfg(target_family = "wasm")] +pub use worker::{Engine, EngineHandle, Starting, WorkerConfig}; diff --git a/crates/uci/src/engine.rs b/crates/uci/src/process.rs similarity index 54% rename from crates/uci/src/engine.rs rename to crates/uci/src/process.rs index 6a4b726..97b92a6 100644 --- a/crates/uci/src/engine.rs +++ b/crates/uci/src/process.rs @@ -1,4 +1,6 @@ -//! Engine process, handshake and the supervisor thread. +//! The engine as a child process: started without a shell, its stdout and stderr +//! read by two threads, the protocol ([`crate::protocol`]) driven by a supervisor +//! thread that waits for input with the session's deadline. use std::collections::VecDeque; use std::ffi::{OsStr, OsString}; @@ -12,62 +14,14 @@ use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use crate::error::EngineError; -use crate::parse::{EngineLine, parse_line}; -use crate::types::{ - EngineInfo, EnginePosition, OptionKind, SearchId, SearchInfo, SearchLimits, Timeouts, -}; - -/// Callback invoked (from the supervisor thread) after every new event; the -/// UI passes `ctx.request_repaint()` here. -pub type Waker = Box; +use crate::events::{EngineEvent, TerminationReason, Waker}; +use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line}; +use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts}; /// Maximum stored length of one output line; longer lines are truncated. const MAX_LINE_BYTES: usize = 64 * 1024; /// Number of stderr lines kept for diagnostics. const STDERR_TAIL_LINES: usize = 256; -/// Maximum number of `Warning` events emitted per engine (flood protection). -const MAX_WARNINGS: usize = 100; - -/// Event delivered to the UI. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum EngineEvent { - /// `position` + `go` for this id were sent to the engine. - SearchStarted { search_id: SearchId }, - /// The request was replaced by a newer one (or cancelled by `stop`) - /// before it was sent to the engine; no events will follow for this id. - Superseded { search_id: SearchId }, - /// Search output. Only lines with a score or a PV are forwarded. - Info { - search_id: SearchId, - info: SearchInfo, - }, - /// Final `bestmove` of a started search. Exactly one per `SearchStarted` - /// unless the engine terminates first. - BestMove { - search_id: SearchId, - best: Option, - ponder: Option, - }, - /// `info string`, attributed to the running search if any. - InfoString { - search_id: Option, - text: String, - }, - /// Malformed or unexpected engine output; the line was skipped. - Warning(String), - /// The supervisor has stopped; the handle is no longer usable. - Terminated(TerminationReason), -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum TerminationReason { - /// `quit()` or drop of the handle. - Quit { status: Option }, - /// The process exited on its own (crash, EOF on stdout, write failure). - Exited { status: Option }, - /// The engine did not answer `stop` or `isready` in time and was killed. - Hung { waiting_for: &'static str }, -} /// Spawn configuration. #[derive(Debug, Clone)] @@ -128,23 +82,11 @@ impl Engine { enum Input { Cmd(Cmd), + Quit, Stdout(String), StdoutClosed, } -enum Cmd { - Search { - position: EnginePosition, - id: SearchId, - limits: SearchLimits, - among: Vec, - }, - Stop, - /// A complete `setoption ...` / `ucinewgame` line, applied while idle. - Setup(String), - Quit, -} - /// Handle owned by the UI. Dropping it quits (and if needed kills) the engine. pub struct EngineHandle { info: EngineInfo, @@ -233,16 +175,7 @@ impl EngineHandle { limits: SearchLimits, among: Vec, ) -> Result<(), EngineError> { - position.validate()?; - if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) { - return Err(EngineError::InvalidInput(format!("not a move: {bad:?}"))); - } - self.send(Cmd::Search { - position, - id: search_id, - limits, - among, - }) + self.send(Cmd::search(position, search_id, limits, among)?) } /// Stops the running search (its `BestMove` still arrives) and cancels a @@ -256,51 +189,7 @@ impl EngineHandle { /// search boundary (UCI forbids `setoption` during a search) — to see the /// effect on the current analysis, call [`Self::analyze`] again. pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> { - let opt = self - .info - .option(name) - .ok_or_else(|| EngineError::UnknownOption(name.to_string()))?; - let bad = |reason: String| EngineError::InvalidOptionValue { - name: opt.name.clone(), - reason, - }; - if let Some(v) = value - && v.chars().any(char::is_control) - { - return Err(bad("control characters in value".into())); - } - let value = match (&opt.kind, value) { - (OptionKind::Button, None) => None, - (OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())), - (_, None) => return Err(bad("value required".into())), - (OptionKind::Check { .. }, Some(v)) => match v { - "true" | "false" => Some(v.to_string()), - _ => return Err(bad(format!("expected true/false, got {v:?}"))), - }, - (OptionKind::Spin { min, max, .. }, Some(v)) => { - let n: i64 = v - .trim() - .parse() - .map_err(|_| bad(format!("not an integer: {v:?}")))?; - if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) { - return Err(bad(format!("{n} outside {min:?}..={max:?}"))); - } - Some(n.to_string()) - } - (OptionKind::Combo { vars, .. }, Some(v)) => { - let var = vars - .iter() - .find(|x| x.eq_ignore_ascii_case(v)) - .ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?; - Some(var.clone()) - } - (OptionKind::String { .. }, Some(v)) => Some(v.to_string()), - }; - let line = match value { - Some(v) => format!("setoption name {} value {}", opt.name, v), - None => format!("setoption name {}", opt.name), - }; - self.send(Cmd::Setup(line)) + self.send(Cmd::Setup(option_line(&self.info, name, value)?)) } pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { @@ -337,7 +226,7 @@ impl EngineHandle { fn shutdown(&mut self) -> Option { if let Some(join) = self.supervisor.take() { - let _ = self.tx.send(Input::Cmd(Cmd::Quit)); + let _ = self.tx.send(Input::Quit); // The supervisor bounds its own shutdown by stop+quit timeouts; // the margin covers scheduling. If it is still stuck (e.g. a // blocked write), kill the process from here. @@ -492,10 +381,8 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result info, + let (info, warnings) = match handshake(&mut stdin, &rx, &cfg.timeouts) { + Ok(done) => done, Err(mut e) => { let _ = child.kill(); let status = child.wait().ok(); @@ -518,19 +405,18 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result(); let mut sup = Supervisor { - stdin, + pipes: Pipes { + stdin, + events: ev_tx, + waker, + }, + session: Session::new(cfg.timeouts), child: Arc::clone(&child), - events: ev_tx, - waker, alive: Arc::clone(&alive), timeouts: cfg.timeouts, - state: State::Idle, - pending: None, - pending_setup: Vec::new(), - warnings: 0, }; for w in warnings { - sup.warn(w); + sup.session.warn(w, &mut sup.pipes); } let supervisor = thread::Builder::new() .name(format!("uci-supervisor-{pid}")) @@ -562,12 +448,13 @@ fn write_line(stdin: &mut ChildStdin, line: &str) -> std::io::Result<()> { stdin.flush() } +/// The handshake over the pipes: every line read goes to [`Handshake`], until it is +/// complete or its deadline passes. fn handshake( stdin: &mut ChildStdin, rx: &Receiver, t: &Timeouts, - warnings: &mut Vec, -) -> Result { +) -> Result<(EngineInfo, Vec), EngineError> { let exited = || EngineError::ProcessExited { status: None, stderr: Vec::new(), @@ -579,68 +466,20 @@ fn handshake( EngineError::Io(e) } }; - write_line(stdin, "uci").map_err(io)?; - let mut info = EngineInfo::default(); - let mut seen_uci = false; - let mut output = Vec::new(); - let deadline = Instant::now() + t.uciok; + let mut hs = Handshake::new(t, Instant::now()); + write_line(stdin, Handshake::FIRST_LINE).map_err(io)?; loop { - let line = match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + let wait = hs.deadline().saturating_duration_since(Instant::now()); + let line = match rx.recv_timeout(wait) { Ok(Input::Stdout(l)) => l, Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), - Ok(Input::Cmd(_)) => continue, - Err(RecvTimeoutError::Timeout) => { - return Err(if seen_uci { - EngineError::HandshakeTimeout { - waiting_for: "uciok", - } - } else { - EngineError::NotUci { output } - }); - } + Ok(Input::Cmd(_) | Input::Quit) => continue, + Err(RecvTimeoutError::Timeout) => return Err(hs.timed_out()), }; - if output.len() < 20 { - output.push(line.clone()); - } - match parse_line(&line) { - Ok(EngineLine::IdName(n)) => { - seen_uci = true; - info.name = Some(n); - } - Ok(EngineLine::IdAuthor(a)) => { - seen_uci = true; - info.author = Some(a); - } - Ok(EngineLine::Option(o)) => { - seen_uci = true; - info.options.push(o); - } - Ok(EngineLine::UciOk) => break, - Ok(_) => {} - Err(e) => { - if line.starts_with("option") { - seen_uci = true; - } - warnings.push(format!("handshake: {e}")); - } - } - } - write_line(stdin, "isready").map_err(io)?; - let deadline = Instant::now() + t.readyok; - loop { - match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { - Ok(Input::Stdout(l)) => { - if matches!(parse_line(&l), Ok(EngineLine::ReadyOk)) { - return Ok(info); - } - } - Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), - Ok(Input::Cmd(_)) => {} - Err(RecvTimeoutError::Timeout) => { - return Err(EngineError::HandshakeTimeout { - waiting_for: "readyok", - }); - } + match hs.on_line(line, Instant::now()) { + HandshakeStep::Continue => {} + HandshakeStep::Write(l) => write_line(stdin, l).map_err(io)?, + HandshakeStep::Done(info, warnings) => return Ok((info, warnings)), } } } @@ -688,109 +527,50 @@ fn read_lines(mut r: BufReader, mut f: impl FnMut(String) -> bool) { } } -/// Supervisor state. Invariant: `position`/`go` is only written in -/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a -/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` -/// belongs to the current search, and `info` read while `Idle`/`Syncing` is -/// stale and dropped. -#[derive(Debug, Clone, Copy)] -enum State { - /// No search running, nothing pending. - Idle, - /// `isready` sent before starting the pending search; waiting `readyok`. - Syncing { - deadline: Instant, - }, - Searching { - id: SearchId, - }, - /// `stop` sent; waiting for the final `bestmove` of `id`. - Stopping { - id: SearchId, - deadline: Instant, - }, -} - -impl State { - fn deadline(self) -> Option { - match self { - State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), - _ => None, - } - } -} - -struct PendingSearch { - position: EnginePosition, - id: SearchId, - limits: SearchLimits, - among: Vec, -} - -struct Supervisor { +/// The process side of the session: the engine's stdin and the events' channel. +struct Pipes { stdin: ChildStdin, - child: Arc>, events: Sender, waker: Waker, - alive: Arc, - timeouts: Timeouts, - state: State, - pending: Option, - pending_setup: Vec, - warnings: usize, } -/// Why the loop must end. -enum Exit { - ProcessGone, - Hung(&'static str), -} +impl Link for Pipes { + fn write(&mut self, line: &str) -> Result<(), Gone> { + write_line(&mut self.stdin, line).map_err(|_| Gone) + } -impl Supervisor { - fn emit(&self, ev: EngineEvent) { + fn emit(&mut self, ev: EngineEvent) { if self.events.send(ev).is_ok() { (self.waker)(); } } +} - fn warn(&mut self, msg: String) { - self.warnings += 1; - if self.warnings < MAX_WARNINGS { - self.emit(EngineEvent::Warning(msg)); - } else if self.warnings == MAX_WARNINGS { - self.emit(EngineEvent::Warning( - "too many warnings; further warnings suppressed".into(), - )); - } - } - - fn write(&mut self, line: &str) -> Result<(), Exit> { - write_line(&mut self.stdin, line).map_err(|_| Exit::ProcessGone) - } +struct Supervisor { + pipes: Pipes, + session: Session, + child: Arc>, + alive: Arc, + timeouts: Timeouts, +} +impl Supervisor { fn run(mut self, rx: Receiver) { let result = loop { - let msg = match self.state.deadline() { + let msg = match self.session.deadline() { Some(d) => rx.recv_timeout(d.saturating_duration_since(Instant::now())), None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected), }; + let now = Instant::now(); let step = match msg { - Ok(Input::Cmd(Cmd::Quit)) | Err(RecvTimeoutError::Disconnected) => { + Ok(Input::Quit) | Err(RecvTimeoutError::Disconnected) => { self.quit(); return; } - Ok(Input::Cmd(cmd)) => self.on_cmd(cmd), - Ok(Input::Stdout(line)) => self.on_line(&line), - Ok(Input::StdoutClosed) => Err(Exit::ProcessGone), - Err(RecvTimeoutError::Timeout) => match self.state { - State::Syncing { deadline } if Instant::now() >= deadline => { - Err(Exit::Hung("readyok")) - } - State::Stopping { deadline, .. } if Instant::now() >= deadline => { - Err(Exit::Hung("bestmove")) - } - _ => Ok(()), - }, + Ok(Input::Cmd(cmd)) => self.session.on_cmd(cmd, now, &mut self.pipes), + Ok(Input::Stdout(line)) => self.session.on_line(&line, now, &mut self.pipes), + Ok(Input::StdoutClosed) => Err(Exit::Gone), + Err(RecvTimeoutError::Timeout) => self.session.on_time(now), }; if let Err(e) = step { break e; @@ -804,11 +584,11 @@ impl Supervisor { let _ = child.wait(); TerminationReason::Hung { waiting_for } } - Exit::ProcessGone => TerminationReason::Exited { + Exit::Gone => TerminationReason::Exited { status: self.reap(Duration::from_millis(500)), }, }; - self.emit(EngineEvent::Terminated(reason)); + self.pipes.emit(EngineEvent::Terminated(reason)); } /// Waits up to `grace` for the process to exit, then kills it. Always reaps. @@ -832,150 +612,9 @@ impl Supervisor { fn quit(&mut self) { self.alive.store(false, Ordering::Release); - if matches!(self.state, State::Searching { .. }) { - let _ = self.write("stop"); - } - let _ = self.write("quit"); + self.session.quit(&mut self.pipes); let status = self.reap(self.timeouts.quit); - self.emit(EngineEvent::Terminated(TerminationReason::Quit { status })); - } - - fn on_cmd(&mut self, cmd: Cmd) -> Result<(), Exit> { - match cmd { - Cmd::Search { - position, - id, - limits, - among, - } => { - if let Some(old) = self.pending.replace(PendingSearch { - position, - id, - limits, - among, - }) { - self.emit(EngineEvent::Superseded { search_id: old.id }); - } - match self.state { - State::Idle => self.begin_sync()?, - State::Searching { id } => self.send_stop(id)?, - State::Syncing { .. } | State::Stopping { .. } => {} - } - } - Cmd::Stop => { - if let Some(old) = self.pending.take() { - self.emit(EngineEvent::Superseded { search_id: old.id }); - } - if let State::Searching { id } = self.state { - self.send_stop(id)?; - } - } - Cmd::Setup(line) => match self.state { - // The engine is not searching: safe to send right away; the - // `isready` before the next `go` fences it. - State::Idle | State::Syncing { .. } => self.write(&line)?, - State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), - }, - Cmd::Quit => unreachable!("handled in run"), - } - Ok(()) - } - - fn send_stop(&mut self, id: SearchId) -> Result<(), Exit> { - self.write("stop")?; - self.state = State::Stopping { - id, - deadline: Instant::now() + self.timeouts.stop, - }; - Ok(()) - } - - /// Engine is idle: flush queued setup, then `isready` if a search waits. - fn begin_sync(&mut self) -> Result<(), Exit> { - for line in std::mem::take(&mut self.pending_setup) { - self.write(&line)?; - } - if self.pending.is_some() { - self.write("isready")?; - self.state = State::Syncing { - deadline: Instant::now() + self.timeouts.readyok, - }; - } else { - self.state = State::Idle; - } - Ok(()) - } - - fn current_search(&self) -> Option { - match self.state { - State::Searching { id } | State::Stopping { id, .. } => Some(id), - _ => None, - } - } - - fn on_line(&mut self, line: &str) -> Result<(), Exit> { - let parsed = match parse_line(line) { - Ok(p) => p, - Err(e) => { - self.warn(e.to_string()); - return Ok(()); - } - }; - match parsed { - EngineLine::Info(info) => { - if let Some(id) = self.current_search() - && (info.score.is_some() || !info.pv.is_empty()) - { - self.emit(EngineEvent::Info { - search_id: id, - info, - }); - } - // Otherwise: stale output of a finished search, dropped. - } - EngineLine::InfoString(text) => { - let search_id = self.current_search(); - self.emit(EngineEvent::InfoString { search_id, text }); - } - EngineLine::BestMove { best, ponder } => match self.current_search() { - Some(id) => { - self.emit(EngineEvent::BestMove { - search_id: id, - best, - ponder, - }); - self.state = State::Idle; - self.begin_sync()?; - } - None => self.warn(format!("unexpected bestmove ignored: {line:?}")), - }, - EngineLine::ReadyOk => { - if let State::Syncing { .. } = self.state { - match self.pending.take() { - Some(p) => { - self.write(&p.position.to_command())?; - let mut go = p.limits.to_command(); - if !p.among.is_empty() { - go += " searchmoves "; - go += &p.among.join(" "); - } - self.write(&go)?; - self.state = State::Searching { id: p.id }; - self.emit(EngineEvent::SearchStarted { search_id: p.id }); - } - None => self.state = State::Idle, - } - } - } - EngineLine::Empty => {} - EngineLine::UciOk - | EngineLine::IdName(_) - | EngineLine::IdAuthor(_) - | EngineLine::Option(_) - | EngineLine::Unknown(_) => { - self.warn(format!("unexpected engine output: {line:?}")); - } - } - Ok(()) + self.pipes + .emit(EngineEvent::Terminated(TerminationReason::Quit { status })); } } diff --git a/crates/uci/src/protocol.rs b/crates/uci/src/protocol.rs new file mode 100644 index 0000000..a48af09 --- /dev/null +++ b/crates/uci/src/protocol.rs @@ -0,0 +1,619 @@ +//! The UCI protocol as a state machine without I/O: the handshake and the session +//! after it. A transport (a child process on a computer, a Web Worker in a browser) +//! feeds it the engine's lines, the user's commands and the time, and carries out +//! what it asks: lines to write, events to deliver. Waiting is the transport's +//! business — the machine never blocks, it only names its next deadline. + +use web_time::Instant; + +use crate::error::EngineError; +use crate::events::EngineEvent; +use crate::parse::{EngineLine, parse_line}; +use crate::types::{EngineInfo, EnginePosition, OptionKind, SearchId, SearchLimits, Timeouts}; + +/// Maximum number of `Warning` events emitted per engine (flood protection). +const MAX_WARNINGS: usize = 100; + +/// A command from the handle to the session. +pub(crate) enum Cmd { + Search { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, + }, + Stop, + /// A complete `setoption ...` / `ucinewgame` line, applied while idle. + Setup(String), +} + +impl Cmd { + /// A search request, checked: a valid position, UCI moves to search among. + pub(crate) fn search( + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, + ) -> Result { + position.validate()?; + if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) { + return Err(EngineError::InvalidInput(format!("not a move: {bad:?}"))); + } + Ok(Cmd::Search { + position, + id, + limits, + among, + }) + } +} + +/// The `setoption` line for `name` = `value` (`None` for buttons), checked against +/// the options the engine declared. +pub(crate) fn option_line( + info: &EngineInfo, + name: &str, + value: Option<&str>, +) -> Result { + let opt = info + .option(name) + .ok_or_else(|| EngineError::UnknownOption(name.to_string()))?; + let bad = |reason: String| EngineError::InvalidOptionValue { + name: opt.name.clone(), + reason, + }; + if let Some(v) = value + && v.chars().any(char::is_control) + { + return Err(bad("control characters in value".into())); + } + let value = match (&opt.kind, value) { + (OptionKind::Button, None) => None, + (OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())), + (_, None) => return Err(bad("value required".into())), + (OptionKind::Check { .. }, Some(v)) => match v { + "true" | "false" => Some(v.to_string()), + _ => return Err(bad(format!("expected true/false, got {v:?}"))), + }, + (OptionKind::Spin { min, max, .. }, Some(v)) => { + let n: i64 = v + .trim() + .parse() + .map_err(|_| bad(format!("not an integer: {v:?}")))?; + if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) { + return Err(bad(format!("{n} outside {min:?}..={max:?}"))); + } + Some(n.to_string()) + } + (OptionKind::Combo { vars, .. }, Some(v)) => { + let var = vars + .iter() + .find(|x| x.eq_ignore_ascii_case(v)) + .ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?; + Some(var.clone()) + } + (OptionKind::String { .. }, Some(v)) => Some(v.to_string()), + }; + let line = match value { + Some(v) => format!("setoption name {} value {}", opt.name, v), + None => format!("setoption name {}", opt.name), + }; + Ok(line) +} + +/// The engine could not be written to: it is gone. +#[derive(Debug)] +pub(crate) struct Gone; + +/// What the session does to the outside world. +pub(crate) trait Link { + /// Writes one line (without its `\n`) to the engine. + fn write(&mut self, line: &str) -> Result<(), Gone>; + /// Delivers an event to the handle (and wakes the UI). + fn emit(&mut self, ev: EngineEvent); +} + +/// The step of the handshake: `uci` → `uciok`, then `isready` → `readyok`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Phase { + Uci, + Ready, +} + +/// `uci`/`uciok` and `isready`/`readyok`: the engine's name, author and options. +pub(crate) struct Handshake { + phase: Phase, + deadline: Instant, + readyok: std::time::Duration, + info: EngineInfo, + seen_uci: bool, + /// First lines of output, for [`EngineError::NotUci`]. + output: Vec, + /// Malformed lines, reported once the session runs. + warnings: Vec, +} + +/// How a line moved the handshake on. +pub(crate) enum HandshakeStep { + /// Keep feeding lines. + Continue, + /// Write this line, then keep feeding lines. + Write(&'static str), + /// Complete: the engine is ready for the session. + Done(EngineInfo, Vec), +} + +impl Handshake { + /// Starts the handshake at `now`; the caller writes [`Self::FIRST_LINE`]. + pub(crate) fn new(t: &Timeouts, now: Instant) -> Self { + Handshake { + phase: Phase::Uci, + deadline: now + t.uciok, + readyok: t.readyok, + info: EngineInfo::default(), + seen_uci: false, + output: Vec::new(), + warnings: Vec::new(), + } + } + + pub(crate) const FIRST_LINE: &'static str = "uci"; + + pub(crate) fn deadline(&self) -> Instant { + self.deadline + } + + /// One line of the engine's output, read at `now`. + pub(crate) fn on_line(&mut self, line: String, now: Instant) -> HandshakeStep { + match self.phase { + Phase::Uci => { + if self.output.len() < 20 { + self.output.push(line.clone()); + } + match parse_line(&line) { + Ok(EngineLine::IdName(n)) => { + self.seen_uci = true; + self.info.name = Some(n); + } + Ok(EngineLine::IdAuthor(a)) => { + self.seen_uci = true; + self.info.author = Some(a); + } + Ok(EngineLine::Option(o)) => { + self.seen_uci = true; + self.info.options.push(o); + } + Ok(EngineLine::UciOk) => { + self.phase = Phase::Ready; + self.deadline = now + self.readyok; + return HandshakeStep::Write("isready"); + } + Ok(_) => {} + Err(e) => { + if line.starts_with("option") { + self.seen_uci = true; + } + self.warnings.push(format!("handshake: {e}")); + } + } + HandshakeStep::Continue + } + Phase::Ready => { + if matches!(parse_line(&line), Ok(EngineLine::ReadyOk)) { + HandshakeStep::Done( + std::mem::take(&mut self.info), + std::mem::take(&mut self.warnings), + ) + } else { + HandshakeStep::Continue + } + } + } + } + + /// The error once [`Self::deadline`] has passed. + pub(crate) fn timed_out(self) -> EngineError { + match self.phase { + Phase::Uci if self.seen_uci => EngineError::HandshakeTimeout { + waiting_for: "uciok", + }, + Phase::Uci => EngineError::NotUci { + output: self.output, + }, + Phase::Ready => EngineError::HandshakeTimeout { + waiting_for: "readyok", + }, + } + } +} + +/// Session state. Invariant: `position`/`go` is only written in +/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a +/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` +/// belongs to the current search, and `info` read while `Idle`/`Syncing` is +/// stale and dropped. +#[derive(Debug, Clone, Copy)] +enum State { + /// No search running, nothing pending. + Idle, + /// `isready` sent before starting the pending search; waiting `readyok`. + Syncing { + deadline: Instant, + }, + Searching { + id: SearchId, + }, + /// `stop` sent; waiting for the final `bestmove` of `id`. + Stopping { + id: SearchId, + deadline: Instant, + }, +} + +struct PendingSearch { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, +} + +/// Why the session must end. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Exit { + /// The engine stopped reading or writing. + Gone, + /// The engine did not answer this in time; the transport kills it. + Hung(&'static str), +} + +impl From for Exit { + fn from(_: Gone) -> Self { + Exit::Gone + } +} + +/// The session after the handshake: searches, their boundaries, setup lines. +pub(crate) struct Session { + timeouts: Timeouts, + state: State, + pending: Option, + pending_setup: Vec, + warnings: usize, +} + +impl Session { + pub(crate) fn new(timeouts: Timeouts) -> Self { + Session { + timeouts, + state: State::Idle, + pending: None, + pending_setup: Vec::new(), + warnings: 0, + } + } + + /// When [`Self::on_time`] must be called next (`None`: nothing to wait for). + pub(crate) fn deadline(&self) -> Option { + match self.state { + State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), + _ => None, + } + } + + /// The time is `now`: an engine past its deadline is hung. + pub(crate) fn on_time(&mut self, now: Instant) -> Result<(), Exit> { + match self.state { + State::Syncing { deadline } if now >= deadline => Err(Exit::Hung("readyok")), + State::Stopping { deadline, .. } if now >= deadline => Err(Exit::Hung("bestmove")), + _ => Ok(()), + } + } + + pub(crate) fn warn(&mut self, msg: String, link: &mut impl Link) { + self.warnings += 1; + if self.warnings < MAX_WARNINGS { + link.emit(EngineEvent::Warning(msg)); + } else if self.warnings == MAX_WARNINGS { + link.emit(EngineEvent::Warning( + "too many warnings; further warnings suppressed".into(), + )); + } + } + + /// The last words before `quit`: a running search is stopped. + pub(crate) fn quit(&mut self, link: &mut impl Link) { + if matches!(self.state, State::Searching { .. }) { + let _ = link.write("stop"); + } + let _ = link.write("quit"); + } + + pub(crate) fn on_cmd( + &mut self, + cmd: Cmd, + now: Instant, + link: &mut impl Link, + ) -> Result<(), Exit> { + match cmd { + Cmd::Search { + position, + id, + limits, + among, + } => { + if let Some(old) = self.pending.replace(PendingSearch { + position, + id, + limits, + among, + }) { + link.emit(EngineEvent::Superseded { search_id: old.id }); + } + match self.state { + State::Idle => self.begin_sync(now, link)?, + State::Searching { id } => self.send_stop(id, now, link)?, + State::Syncing { .. } | State::Stopping { .. } => {} + } + } + Cmd::Stop => { + if let Some(old) = self.pending.take() { + link.emit(EngineEvent::Superseded { search_id: old.id }); + } + if let State::Searching { id } = self.state { + self.send_stop(id, now, link)?; + } + } + Cmd::Setup(line) => match self.state { + // The engine is not searching: safe to send right away; the + // `isready` before the next `go` fences it. + State::Idle | State::Syncing { .. } => link.write(&line)?, + State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), + }, + } + Ok(()) + } + + fn send_stop(&mut self, id: SearchId, now: Instant, link: &mut impl Link) -> Result<(), Exit> { + link.write("stop")?; + self.state = State::Stopping { + id, + deadline: now + self.timeouts.stop, + }; + Ok(()) + } + + /// Engine is idle: flush queued setup, then `isready` if a search waits. + fn begin_sync(&mut self, now: Instant, link: &mut impl Link) -> Result<(), Exit> { + for line in std::mem::take(&mut self.pending_setup) { + link.write(&line)?; + } + if self.pending.is_some() { + link.write("isready")?; + self.state = State::Syncing { + deadline: now + self.timeouts.readyok, + }; + } else { + self.state = State::Idle; + } + Ok(()) + } + + fn current_search(&self) -> Option { + match self.state { + State::Searching { id } | State::Stopping { id, .. } => Some(id), + _ => None, + } + } + + /// One line of the engine's output, read at `now`. + pub(crate) fn on_line( + &mut self, + line: &str, + now: Instant, + link: &mut impl Link, + ) -> Result<(), Exit> { + let parsed = match parse_line(line) { + Ok(p) => p, + Err(e) => { + self.warn(e.to_string(), link); + return Ok(()); + } + }; + match parsed { + EngineLine::Info(info) => { + if let Some(id) = self.current_search() + && (info.score.is_some() || !info.pv.is_empty()) + { + link.emit(EngineEvent::Info { + search_id: id, + info, + }); + } + // Otherwise: stale output of a finished search, dropped. + } + EngineLine::InfoString(text) => { + let search_id = self.current_search(); + link.emit(EngineEvent::InfoString { search_id, text }); + } + EngineLine::BestMove { best, ponder } => match self.current_search() { + Some(id) => { + link.emit(EngineEvent::BestMove { + search_id: id, + best, + ponder, + }); + self.state = State::Idle; + self.begin_sync(now, link)?; + } + None => self.warn(format!("unexpected bestmove ignored: {line:?}"), link), + }, + EngineLine::ReadyOk => { + if let State::Syncing { .. } = self.state { + match self.pending.take() { + Some(p) => { + link.write(&p.position.to_command())?; + let mut go = p.limits.to_command(); + if !p.among.is_empty() { + go += " searchmoves "; + go += &p.among.join(" "); + } + link.write(&go)?; + self.state = State::Searching { id: p.id }; + link.emit(EngineEvent::SearchStarted { search_id: p.id }); + } + None => self.state = State::Idle, + } + } + } + EngineLine::Empty => {} + EngineLine::UciOk + | EngineLine::IdName(_) + | EngineLine::IdAuthor(_) + | EngineLine::Option(_) + | EngineLine::Unknown(_) => { + self.warn(format!("unexpected engine output: {line:?}"), link); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + /// A link that records what the session did. + #[derive(Default)] + struct Record { + written: Vec, + events: Vec, + broken: bool, + } + + impl Link for Record { + fn write(&mut self, line: &str) -> Result<(), Gone> { + if self.broken { + return Err(Gone); + } + self.written.push(line.to_owned()); + Ok(()) + } + fn emit(&mut self, ev: EngineEvent) { + self.events.push(ev); + } + } + + fn search(id: u64) -> Cmd { + Cmd::Search { + position: EnginePosition::startpos(Vec::::new()), + id: SearchId(id), + limits: SearchLimits::Infinite, + among: Vec::new(), + } + } + + #[test] + fn handshake_collects_info_and_asks_ready() { + let t0 = Instant::now(); + let mut h = Handshake::new(&Timeouts::default(), t0); + assert!(matches!( + h.on_line("id name Fake".into(), t0), + HandshakeStep::Continue + )); + assert!(matches!( + h.on_line( + "option name Hash type spin default 16 min 1 max 1024".into(), + t0 + ), + HandshakeStep::Continue + )); + let later = t0 + Duration::from_secs(1); + assert!(matches!( + h.on_line("uciok".into(), later), + HandshakeStep::Write("isready") + )); + assert_eq!(h.deadline(), later + Timeouts::default().readyok); + // Output before `readyok` is not taken for the engine's description. + assert!(matches!( + h.on_line("id name Other".into(), later), + HandshakeStep::Continue + )); + match h.on_line("readyok".into(), later) { + HandshakeStep::Done(info, warnings) => { + assert_eq!(info.name.as_deref(), Some("Fake")); + assert_eq!(info.options.len(), 1); + assert!(warnings.is_empty()); + } + _ => panic!("handshake not done"), + } + } + + #[test] + fn handshake_timeouts_name_what_was_missing() { + let t0 = Instant::now(); + let silent = Handshake::new(&Timeouts::default(), t0); + assert!(matches!(silent.timed_out(), EngineError::NotUci { .. })); + let mut uci = Handshake::new(&Timeouts::default(), t0); + let _ = uci.on_line("id name Fake".into(), t0); + assert!(matches!( + uci.timed_out(), + EngineError::HandshakeTimeout { + waiting_for: "uciok" + } + )); + let mut ready = Handshake::new(&Timeouts::default(), t0); + let _ = ready.on_line("uciok".into(), t0); + assert!(matches!( + ready.timed_out(), + EngineError::HandshakeTimeout { + waiting_for: "readyok" + } + )); + } + + #[test] + fn a_search_waits_for_readyok_and_stale_info_is_dropped() { + let now = Instant::now(); + let mut s = Session::new(Timeouts::default()); + let mut link = Record::default(); + s.on_cmd(search(1), now, &mut link).unwrap(); + assert_eq!(link.written, ["isready"]); + // Info before the search starts belongs to nobody. + s.on_line("info depth 1 score cp 5 pv e2e4", now, &mut link) + .unwrap(); + assert!(link.events.is_empty()); + s.on_line("readyok", now, &mut link).unwrap(); + assert_eq!(link.written[1], "position startpos"); + assert_eq!(link.written[2], "go infinite"); + assert_eq!( + link.events, + [EngineEvent::SearchStarted { + search_id: SearchId(1) + }] + ); + // A newer request stops the running search; the old `bestmove` ends it. + s.on_cmd(search(2), now, &mut link).unwrap(); + assert_eq!(link.written[3], "stop"); + s.on_line("bestmove e2e4", now, &mut link).unwrap(); + assert_eq!(link.written[4], "isready"); + s.on_line("readyok", now, &mut link).unwrap(); + assert!(link.events.contains(&EngineEvent::SearchStarted { + search_id: SearchId(2) + })); + } + + #[test] + fn deadlines_and_a_broken_link_end_the_session() { + let now = Instant::now(); + let mut s = Session::new(Timeouts::default()); + let mut link = Record::default(); + assert_eq!(s.deadline(), None); + s.on_cmd(search(1), now, &mut link).unwrap(); + let d = s.deadline().expect("waiting for readyok"); + assert_eq!(s.on_time(now), Ok(())); + assert_eq!(s.on_time(d), Err(Exit::Hung("readyok"))); + link.broken = true; + assert_eq!(s.on_line("readyok", now, &mut link), Err(Exit::Gone)); + } +} diff --git a/crates/uci/src/types.rs b/crates/uci/src/types.rs index 148354f..7b57cca 100644 --- a/crates/uci/src/types.rs +++ b/crates/uci/src/types.rs @@ -253,7 +253,8 @@ impl EnginePosition { Ok(()) } - pub(crate) fn to_command(&self) -> String { + /// The `position …` line for this position. + pub fn to_command(&self) -> String { let mut s = match &self.base { PositionBase::StartPos => "position startpos".to_string(), PositionBase::Fen(fen) => format!("position fen {}", fen.trim()), @@ -290,7 +291,8 @@ pub enum SearchLimits { } impl SearchLimits { - pub(crate) fn to_command(self) -> String { + /// The `go …` line for these limits. + pub fn to_command(self) -> String { match self { SearchLimits::Infinite => "go infinite".into(), SearchLimits::Depth(d) => format!("go depth {d}"), diff --git a/crates/uci/src/worker.rs b/crates/uci/src/worker.rs new file mode 100644 index 0000000..3ce9cc7 --- /dev/null +++ b/crates/uci/src/worker.rs @@ -0,0 +1,434 @@ +//! The engine as a Web Worker (WebAssembly in a browser, which has no processes): +//! the engine's script runs in the worker, a line of UCI is one message each way, +//! and the protocol ([`crate::protocol`]) is driven by the worker's messages and by +//! timers set for its deadlines. Everything happens on the page's thread, so nothing +//! here blocks: the handshake is finished by the worker's messages and its outcome +//! taken by [`Starting::poll`]. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::{Rc, Weak}; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; +use web_time::Instant; + +use crate::error::EngineError; +use crate::events::{EngineEvent, TerminationReason, Waker}; +use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line}; +use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts}; + +#[wasm_bindgen] +extern "C" { + // The global timer functions: a page's and a worker's alike. + #[wasm_bindgen(js_name = setTimeout)] + fn set_timeout(f: &js_sys::Function, ms: f64) -> JsValue; + #[wasm_bindgen(js_name = clearTimeout)] + fn clear_timeout(id: &JsValue); +} + +/// How to start an engine in a worker. +#[derive(Debug, Clone)] +pub struct WorkerConfig { + /// The URL of the engine's worker script. + pub script: String, + pub timeouts: Timeouts, +} + +impl WorkerConfig { + pub fn new(script: impl Into) -> Self { + WorkerConfig { + script: script.into(), + timeouts: Timeouts::default(), + } + } +} + +/// The worker side of the session: the worker itself and the events' queue. +struct Port { + worker: web_sys::Worker, + events: VecDeque, + waker: Waker, +} + +impl Link for Port { + fn write(&mut self, line: &str) -> Result<(), Gone> { + self.worker + .post_message(&JsValue::from_str(line)) + .map_err(|_| Gone) + } + + fn emit(&mut self, ev: EngineEvent) { + self.events.push_back(ev); + (self.waker)(); + } +} + +enum Phase { + Handshake(Handshake), + Running(Session), + Ended, +} + +struct Inner { + port: Port, + phase: Phase, + timeouts: Timeouts, + /// The outcome of the handshake until [`Starting::poll`] takes it. + started: Option>, + /// The timer of the protocol's next deadline. + timer: Option, + /// The worker's handlers and the timer's callback, alive as long as the engine. + callbacks: Vec>, + on_timer: Option>, +} + +impl Inner { + fn deadline(&self) -> Option { + match &self.phase { + Phase::Handshake(h) => Some(h.deadline()), + Phase::Running(s) => s.deadline(), + Phase::Ended => None, + } + } + + /// Sets the timer for the protocol's next deadline (clearing the old one). + fn arm(&mut self) { + if let Some(id) = self.timer.take() { + clear_timeout(&id); + } + let (Some(at), Some(f)) = (self.deadline(), &self.on_timer) else { + return; + }; + let ms = at.saturating_duration_since(Instant::now()).as_secs_f64() * 1000.0; + // A millisecond late rather than early: the deadline must have passed. + self.timer = Some(set_timeout(f.as_ref().unchecked_ref(), ms.ceil() + 1.0)); + } + + fn on_line(&mut self, line: String) { + let now = Instant::now(); + match &mut self.phase { + Phase::Handshake(h) => match h.on_line(line, now) { + HandshakeStep::Continue => {} + HandshakeStep::Write(l) => { + if self.port.write(l).is_err() { + self.fail_start(gone(Vec::new())); + } + } + HandshakeStep::Done(info, warnings) => { + let mut session = Session::new(self.timeouts); + for w in warnings { + session.warn(w, &mut self.port); + } + self.phase = Phase::Running(session); + self.started = Some(Ok(info)); + (self.port.waker)(); + } + }, + Phase::Running(s) => { + if let Err(e) = s.on_line(&line, now, &mut self.port) { + self.end(e); + } + } + Phase::Ended => {} + } + self.arm(); + } + + fn on_cmd(&mut self, cmd: Cmd) -> Result<(), EngineError> { + let Phase::Running(s) = &mut self.phase else { + return Err(EngineError::NotRunning); + }; + if let Err(e) = s.on_cmd(cmd, Instant::now(), &mut self.port) { + self.end(e); + } + self.arm(); + Ok(()) + } + + fn on_timer(&mut self) { + self.timer = None; + let now = Instant::now(); + match &mut self.phase { + Phase::Handshake(h) if now >= h.deadline() => { + let Phase::Handshake(h) = std::mem::replace(&mut self.phase, Phase::Ended) else { + unreachable!("matched above"); + }; + self.port.worker.terminate(); + self.started = Some(Err(h.timed_out())); + (self.port.waker)(); + } + Phase::Running(s) => { + if let Err(e) = s.on_time(now) { + self.end(e); + } + } + Phase::Handshake(_) | Phase::Ended => {} + } + self.arm(); + } + + /// The worker reported an error: its script did not load or the engine failed. + fn on_error(&mut self, message: String) { + match self.phase { + Phase::Handshake(_) => self.fail_start(gone(vec![message])), + Phase::Running(_) => self.end(Exit::Gone), + Phase::Ended => {} + } + self.arm(); + } + + fn fail_start(&mut self, e: EngineError) { + self.port.worker.terminate(); + self.phase = Phase::Ended; + self.started = Some(Err(e)); + (self.port.waker)(); + } + + /// The session ended on its own; the worker is stopped. + fn end(&mut self, exit: Exit) { + self.port.worker.terminate(); + self.phase = Phase::Ended; + let reason = match exit { + Exit::Hung(waiting_for) => TerminationReason::Hung { waiting_for }, + Exit::Gone => TerminationReason::Exited { status: None }, + }; + self.port.emit(EngineEvent::Terminated(reason)); + } + + fn quit(&mut self) { + if let Phase::Running(s) = &mut self.phase { + s.quit(&mut self.port); + self.port.worker.terminate(); + self.phase = Phase::Ended; + self.port + .emit(EngineEvent::Terminated(TerminationReason::Quit { + status: None, + })); + } else { + self.port.worker.terminate(); + self.phase = Phase::Ended; + } + self.arm(); + self.port.worker.set_onmessage(None); + self.port.worker.set_onerror(None); + } +} + +fn gone(stderr: Vec) -> EngineError { + EngineError::ProcessExited { + status: None, + stderr, + } +} + +/// An engine whose handshake is under way. +pub struct Starting { + inner: Option>>, +} + +impl Starting { + /// The engine once its handshake is over (`None`: not yet). After a result it + /// keeps returning `None`. + pub fn poll(&mut self) -> Option> { + let started = self.inner.as_ref()?.borrow_mut().started.take()?; + let inner = self.inner.take()?; + Some(started.map(|info| EngineHandle { info, inner })) + } +} + +impl Drop for Starting { + fn drop(&mut self) { + if let Some(inner) = self.inner.take() { + inner.borrow_mut().quit(); + } + } +} + +/// Namespace for starting engines. +pub struct Engine; + +impl Engine { + /// Starts the engine of `cfg.script` in a new worker, and its handshake. The + /// worker's events wake the UI through `waker`; [`Starting::poll`] gives the + /// engine once it answered `readyok`. + pub fn start_worker(cfg: WorkerConfig, waker: Waker) -> Result { + start(cfg, waker) + } +} + +fn start(cfg: WorkerConfig, waker: Waker) -> Result { + let script_error = |e: JsValue| { + EngineError::Spawn(std::io::Error::other( + e.as_string() + .unwrap_or_else(|| format!("cannot start the worker {}", cfg.script)), + )) + }; + let worker = web_sys::Worker::new(&cfg.script).map_err(script_error)?; + let inner = Rc::new(RefCell::new(Inner { + port: Port { + worker: worker.clone(), + events: VecDeque::new(), + waker, + }, + phase: Phase::Handshake(Handshake::new(&cfg.timeouts, Instant::now())), + timeouts: cfg.timeouts, + started: None, + timer: None, + callbacks: Vec::new(), + on_timer: None, + })); + let weak = Rc::downgrade(&inner); + let with = move |f: &dyn Fn(&mut Inner)| { + if let Some(inner) = Weak::upgrade(&weak) { + f(&mut inner.borrow_mut()); + } + }; + let on_message = { + let with = with.clone(); + Closure::::new(move |ev: JsValue| { + let data = ev.unchecked_into::().data(); + // A message is a line; some builds join several with `\n`. + let text = data.as_string().unwrap_or_default(); + with(&|inner| { + for line in text.lines() { + inner.on_line(line.to_owned()); + } + }); + }) + }; + let on_error = { + let with = with.clone(); + Closure::::new(move |ev: JsValue| { + let message = ev + .dyn_ref::() + .map(web_sys::ErrorEvent::message) + .unwrap_or_else(|| "the engine's worker failed".into()); + with(&|inner| inner.on_error(message.clone())); + }) + }; + let on_timer = Closure::::new(move || with(&|inner| inner.on_timer())); + worker.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + worker.set_onerror(Some(on_error.as_ref().unchecked_ref())); + { + let mut i = inner.borrow_mut(); + i.callbacks = vec![on_message, on_error]; + i.on_timer = Some(on_timer); + if i.port.write(Handshake::FIRST_LINE).is_err() { + i.fail_start(gone(Vec::new())); + } + i.arm(); + } + Ok(Starting { inner: Some(inner) }) +} + +/// Handle owned by the UI. Dropping it quits the engine (its worker is stopped). +pub struct EngineHandle { + info: EngineInfo, + inner: Rc>, +} + +impl std::fmt::Debug for EngineHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EngineHandle") + .field("name", &self.info.name) + .field("alive", &self.is_running()) + .finish() + } +} + +impl EngineHandle { + /// `id name/author` and declared options from the handshake. + pub fn info(&self) -> &EngineInfo { + &self.info + } + + /// `false` after the engine terminated (quit, crash, hung). + pub fn is_running(&self) -> bool { + matches!(self.inner.borrow().phase, Phase::Running(_)) + } + + /// Non-blocking poll for the next event (call every frame). + pub fn try_recv(&self) -> Option { + self.inner.borrow_mut().port.events.pop_front() + } + + /// Drains all currently queued events. + pub fn drain_events(&self) -> impl Iterator + '_ { + std::iter::from_fn(|| self.try_recv()) + } + + /// Infinite analysis (`go infinite`) of `position` under `search_id`. + pub fn analyze( + &self, + position: EnginePosition, + search_id: SearchId, + ) -> Result<(), EngineError> { + self.search(position, search_id, SearchLimits::Infinite) + } + + /// Requests a search: a running search is stopped first and only the latest + /// request is started. + pub fn search( + &self, + position: EnginePosition, + search_id: SearchId, + limits: SearchLimits, + ) -> Result<(), EngineError> { + self.search_among(position, search_id, limits, Vec::new()) + } + + /// A search among these moves only (UCI moves of `position`); empty: all. + pub fn search_among( + &self, + position: EnginePosition, + search_id: SearchId, + limits: SearchLimits, + among: Vec, + ) -> Result<(), EngineError> { + let cmd = Cmd::search(position, search_id, limits, among)?; + self.inner.borrow_mut().on_cmd(cmd) + } + + /// Stops the running search (its `BestMove` still arrives) and cancels a + /// queued one. + pub fn stop(&self) -> Result<(), EngineError> { + self.inner.borrow_mut().on_cmd(Cmd::Stop) + } + + /// `setoption`, checked against the declared options; applied at the next + /// search boundary when a search runs. + pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> { + let line = option_line(&self.info, name, value)?; + self.inner.borrow_mut().on_cmd(Cmd::Setup(line)) + } + + pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { + self.set_option("MultiPV", Some(&lines.to_string())) + } + + pub fn set_threads(&self, threads: u32) -> Result<(), EngineError> { + self.set_option("Threads", Some(&threads.to_string())) + } + + pub fn set_hash_mb(&self, mb: u32) -> Result<(), EngineError> { + self.set_option("Hash", Some(&mb.to_string())) + } + + /// `ucinewgame` (applied at the next idle point, followed by `isready`). + pub fn new_game(&self) -> Result<(), EngineError> { + self.inner + .borrow_mut() + .on_cmd(Cmd::Setup("ucinewgame".into())) + } + + /// Sends `stop`/`quit` and stops the worker at once (a worker needs no grace + /// time: nothing of it outlives `terminate`). + pub fn quit(self) {} +} + +impl Drop for EngineHandle { + fn drop(&mut self) { + self.inner.borrow_mut().quit(); + } +} diff --git a/crates/uci/tests/fake_engine.rs b/crates/uci/tests/fake_engine.rs index e843780..11a1b79 100644 --- a/crates/uci/tests/fake_engine.rs +++ b/crates/uci/tests/fake_engine.rs @@ -1,4 +1,6 @@ //! Supervisor tests against the deterministic fake engine (src/bin/fake_uci.rs). +// The process transport. +#![cfg(not(target_family = "wasm"))] use std::collections::{HashMap, HashSet}; use std::path::Path; diff --git a/crates/uci/tests/stockfish.rs b/crates/uci/tests/stockfish.rs index ba5e068..6c334a1 100644 --- a/crates/uci/tests/stockfish.rs +++ b/crates/uci/tests/stockfish.rs @@ -1,6 +1,8 @@ //! Integration test with a real Stockfish binary. Ignored by default. //! //! Run: UCI_STOCKFISH=/path/to/stockfish cargo test -p uci --test stockfish -- --ignored +// The process transport. +#![cfg(not(target_family = "wasm"))] use std::collections::BTreeMap; use std::time::{Duration, Instant}; diff --git a/crates/uci/tests/worker.rs b/crates/uci/tests/worker.rs new file mode 100644 index 0000000..078acff --- /dev/null +++ b/crates/uci/tests/worker.rs @@ -0,0 +1,287 @@ +//! The worker transport against a fake engine written in JavaScript, in a browser +//! (`docs/dev/web.md`, «Проверки»: wasm-bindgen-test-runner with headless Firefox). +//! +//! The fake engine answers like `src/bin/fake_uci.rs` in the points that matter +//! here: the first PV move of a search is the marker of its position (the first +//! FEN field), info lines come every few milliseconds until `stop`, and flags make +//! it hang, crash or stay silent. +#![cfg(target_family = "wasm")] + +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::Duration; + +use uci::{ + Engine, EngineError, EngineEvent, EngineHandle, EnginePosition, SearchId, SearchLimits, + Starting, TerminationReason, Timeouts, WorkerConfig, +}; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +wasm_bindgen_test_configure!(run_in_browser); + +const FAKE: &str = r#" +let searching = null, timer = null, marker = 'startpos', n = 0; +const send = (l) => postMessage(l); +function stopSearch() { + if (searching === null) return; + clearInterval(timer); timer = null; + const m = searching; searching = null; + if (FLAGS.hangOnStop) return; + send('info depth 9 score cp 1 pv ' + m); + send('bestmove ' + m); +} +onmessage = (e) => { + const line = String(e.data), w = line.split(' '); + switch (w[0]) { + case 'uci': + if (FLAGS.silent) return; + send('id name Fake Worker'); send('id author Test Suite'); + send('option name MultiPV type spin default 1 min 1 max 10'); + send('option name Hash type spin default 16 min 1 max 1024'); + if (!FLAGS.noUciok) send('uciok'); + break; + case 'isready': if (!FLAGS.noReadyok) send('readyok'); break; + case 'position': + if (w[1] === 'fen') marker = w[2]; + else { const i = w.indexOf('moves'); marker = i > 0 && w.length > i + 1 ? w[w.length - 1] : 'startpos'; } + break; + case 'go': + if (FLAGS.crashOnGo) throw new Error('fake engine crashed'); + searching = marker; n = 0; + if (w[1] === 'nodes') { send('info depth 1 score cp 3 nodes ' + w[2] + ' pv ' + marker); stopSearch(); break; } + timer = setInterval(() => { n++; send('info depth ' + n + ' score cp ' + n + ' pv ' + searching); }, 5); + break; + case 'stop': stopSearch(); break; + case 'quit': close(); break; + } +}; +"#; + +/// A worker script of the fake engine with these flags (a `blob:` URL). +fn fake(flags: &str) -> String { + let source = format!("const FLAGS = {{{flags}}};\n{FAKE}"); + let parts = js_sys::Array::of1(&JsValue::from_str(&source)); + let opts = web_sys::BlobPropertyBag::new(); + opts.set_type("text/javascript"); + let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &opts).unwrap(); + web_sys::Url::create_object_url_with_blob(&blob).unwrap() +} + +fn timeouts() -> Timeouts { + Timeouts { + uciok: Duration::from_millis(1500), + readyok: Duration::from_millis(1500), + stop: Duration::from_millis(500), + quit: Duration::from_millis(500), + } +} + +async fn sleep(ms: i32) { + let promise = js_sys::Promise::new(&mut |resolve, _| { + web_sys::window() + .unwrap() + .set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms) + .unwrap(); + }); + wasm_bindgen_futures::JsFuture::from(promise).await.unwrap(); +} + +/// Starts the fake engine and waits for its handshake; also counts the waker's calls. +async fn start(flags: &str) -> (Result, u32) { + let woke = Arc::new(AtomicU32::new(0)); + let w = Arc::clone(&woke); + let mut config = WorkerConfig::new(fake(flags)); + config.timeouts = timeouts(); + let mut starting: Starting = Engine::start_worker( + config, + Box::new(move || { + w.fetch_add(1, Ordering::Relaxed); + }), + ) + .expect("worker created"); + for _ in 0..400 { + if let Some(r) = starting.poll() { + return (r, woke.load(Ordering::Relaxed)); + } + sleep(10).await; + } + panic!("the handshake neither ended nor timed out"); +} + +/// Events until `pred` holds for one (inclusive), or `ms` pass. +async fn until(h: &EngineHandle, ms: u32, pred: impl Fn(&EngineEvent) -> bool) -> Vec { + let mut out = Vec::new(); + for _ in 0..ms / 5 { + while let Some(ev) = h.try_recv() { + let hit = pred(&ev); + out.push(ev); + if hit { + return out; + } + } + sleep(5).await; + } + panic!("no expected event in {ms} ms: {out:?}"); +} + +fn fen(marker: &str) -> EnginePosition { + EnginePosition::fen(format!("{marker} w - - 0 1"), Vec::::new()) +} + +#[wasm_bindgen_test] +async fn handshake_then_analysis_and_stop() { + let (h, woke) = start("").await; + let h = h.expect("started"); + assert_eq!(h.info().name.as_deref(), Some("Fake Worker")); + assert_eq!(h.info().options.len(), 2); + assert!(woke > 0, "the waker was not called"); + h.set_multipv(2).unwrap(); + assert!(matches!( + h.set_multipv(11), + Err(EngineError::InvalidOptionValue { .. }) + )); + h.analyze(fen("m1"), SearchId(1)).unwrap(); + let evs = until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; + assert!(evs.contains(&EngineEvent::SearchStarted { + search_id: SearchId(1) + })); + h.stop().unwrap(); + let evs = until(&h, 2000, |e| matches!(e, EngineEvent::BestMove { .. })).await; + match evs.last() { + Some(EngineEvent::BestMove { + search_id, best, .. + }) => { + assert_eq!(*search_id, SearchId(1)); + assert_eq!(best.as_deref(), Some("m1")); + } + other => panic!("{other:?}"), + } + assert!(h.is_running()); +} + +#[wasm_bindgen_test] +async fn rapid_requests_start_only_the_latest_and_never_mix_output() { + let (h, _) = start("").await; + let h = h.expect("started"); + h.analyze(fen("a"), SearchId(1)).unwrap(); + until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; + for (id, m) in [(2, "b"), (3, "c"), (4, "d")] { + h.analyze(fen(m), SearchId(id)).unwrap(); + } + let evs = until(&h, 3000, |e| { + matches!( + e, + EngineEvent::Info { + search_id: SearchId(4), + .. + } + ) + }) + .await; + for id in [2, 3] { + assert!(evs.contains(&EngineEvent::Superseded { + search_id: SearchId(id) + })); + assert!(!evs.contains(&EngineEvent::SearchStarted { + search_id: SearchId(id) + })); + } + for e in &evs { + if let EngineEvent::Info { search_id, info } = e { + let want = if *search_id == SearchId(1) { "a" } else { "d" }; + assert_eq!(info.pv.first().map(String::as_str), Some(want), "{e:?}"); + } + } + // A node-limited search ends by itself. + h.search(fen("n"), SearchId(5), SearchLimits::Nodes(1000)) + .unwrap(); + let evs = until(&h, 2000, |e| { + matches!( + e, + EngineEvent::BestMove { + search_id: SearchId(5), + .. + } + ) + }) + .await; + assert!(matches!(evs.last(), Some(EngineEvent::BestMove { best: Some(b), .. }) if b == "n")); +} + +#[wasm_bindgen_test] +async fn an_engine_hung_on_stop_is_terminated() { + let (h, _) = start("hangOnStop: true").await; + let h = h.expect("started"); + h.analyze(fen("h"), SearchId(1)).unwrap(); + until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; + h.stop().unwrap(); + let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await; + assert_eq!( + evs.last(), + Some(&EngineEvent::Terminated(TerminationReason::Hung { + waiting_for: "bestmove" + })) + ); + assert!(!h.is_running()); + assert!(matches!(h.stop(), Err(EngineError::NotRunning))); +} + +#[wasm_bindgen_test] +async fn a_crash_ends_the_session() { + let (h, _) = start("crashOnGo: true").await; + let h = h.expect("started"); + h.analyze(fen("x"), SearchId(1)).unwrap(); + let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await; + assert_eq!( + evs.last(), + Some(&EngineEvent::Terminated(TerminationReason::Exited { + status: None + })) + ); +} + +#[wasm_bindgen_test] +async fn handshake_failures_are_named() { + let (silent, _) = start("silent: true").await; + assert!( + matches!(silent, Err(EngineError::NotUci { .. })), + "{silent:?}" + ); + let (no_uciok, _) = start("noUciok: true").await; + assert!( + matches!( + no_uciok, + Err(EngineError::HandshakeTimeout { + waiting_for: "uciok" + }) + ), + "{no_uciok:?}" + ); + let (no_readyok, _) = start("noReadyok: true").await; + assert!( + matches!( + no_readyok, + Err(EngineError::HandshakeTimeout { + waiting_for: "readyok" + }) + ), + "{no_readyok:?}" + ); + // A script that does not load. + let mut config = WorkerConfig::new("/no-such-engine.js"); + config.timeouts = timeouts(); + let mut starting = Engine::start_worker(config, Box::new(|| {})).expect("worker created"); + let mut result = None; + for _ in 0..400 { + result = starting.poll(); + if result.is_some() { + break; + } + sleep(10).await; + } + assert!( + matches!(result, Some(Err(EngineError::ProcessExited { .. }))), + "{result:?}" + ); +} diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index a93057c..fa0d261 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -2,6 +2,11 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `io.github.vrubelroman.chessPenguin`. +С 2026-10-30 интерфейс — библиотека `chesspenguin_app` (`src/lib.rs`), бинарник `src/main.rs` только +запускает её (`run_native`); та же библиотека — веб-версия (`apps/web`, `start_web`). Всё, что зависит от +системы (каталоги, файлы, фоновые задачи, диалоги, буфер обмена, что есть на платформе), — в `src/platform` +(`docs/dev/web.md`). + ## Модули | Файл | Ответственность | diff --git a/docs/dev/uci.md b/docs/dev/uci.md index 847a2b8..c6c0f5f 100644 --- a/docs/dev/uci.md +++ b/docs/dev/uci.md @@ -2,6 +2,22 @@ Статус: реализовано 2026-10-17, `crates/uci`. Без зависимостей от egui и chess-core; единственная зависимость — `thiserror`. +## Автомат и транспорты (2026-10-30, веб-версия) + +Протокол — автомат без ввода-вывода (`protocol.rs`: `Handshake` — `uci`/`uciok`, `isready`/`readyok`; +`Session` — поиски, их границы, отложенные `setoption`; `Link` — «записать строку», «отдать событие»). Ему +передают строки движка, команды и текущее время; он пишет строки, отдаёт события и называет свой следующий +дедлайн, но сам не ждёт. Транспорты: + +- **процесс** (`process.rs`, не для браузера) — как описано ниже: потоки чтения, супервизор ждёт `recv_timeout` + до дедлайна автомата; +- **Web Worker** (`worker.rs`, только для браузера) — строка UCI — одно сообщение `postMessage`; дедлайны — + таймеры `setTimeout`; `quit` — `terminate()`. Рукопожатие не блокирует: `Engine::start_worker(WorkerConfig)` + → `Starting`, `poll()` каждый кадр отдаёт `EngineHandle` после `readyok`. Тесты — `tests/worker.rs` с + поддельным движком на JS в headless Firefox (`apps/web/check/uci-worker.mjs`). + +Граница поисков (`isready`/`readyok` после `bestmove`) — свойство автомата, поэтому одна для обоих транспортов. + ## Выбор реализации - **std, без tokio.** `std::process::Command` (без shell), два потока чтения (stdout, stderr), поток-супервизор с машиной состояний, `std::sync::mpsc`. UI опрашивает события `try_recv`/`drain_events` в каждом кадре, супервизор после каждого события вызывает `Waker` (`ctx.request_repaint`). Tokio не нужен остальному приложению; одному движку достаточно трёх потоков, а ожидания с таймаутом покрываются `recv_timeout`. crossbeam-channel не понадобился: все входы супервизора (команды UI и строки stdout) идут в один канал. diff --git a/docs/dev/web.md b/docs/dev/web.md new file mode 100644 index 0000000..3f8b980 --- /dev/null +++ b/docs/dev/web.md @@ -0,0 +1,334 @@ +# Веб-версия: архитектура (`apps/web`) + +Задача — `docs/dev/tasks.md` §22. Решения владельца — `docs/decisions.md` «Веб-версия (2026-10-30)»; +интерфейс — `docs/design/web-version.md` (раскладки iPad не делаем: планшеты, как телефоны, получают +страницу о приложениях); исследование — `docs/research/web-version-tech.md`. + +Статус: **этап 2** — 2026-10-30, ветка `web-app`. Программа собирается для браузера и работает в +headless Firefox: открыть PGN кнопкой и перетаскиванием, примеры, партия, ходы на доске, скачать PGN +(этап 1); Stockfish 19 по согласию, живой анализ, разбор партии на воркерах с теми же оценками, что на +компьютере, «Мои партии», данные в браузере, файлы прошлого посещения, клавиши (этап 2, §8). + +## 1. Одна программа, две оболочки + +```text +apps/desktop (пакет chesspenguin) apps/web (пакет chesspenguin-web, cdylib) + src/main.rs → run_native() src/lib.rs → start(canvas) → start_web() + src/lib.rs (библиотека chesspenguin_app: весь интерфейс egui) + src/platform/ (что отличается: native.rs | web/) + │ +crates: chess-core, chess-import, uci (протокол + процесс | воркер), game-review, play, prep, … +``` + +- `apps/desktop` — библиотека `chesspenguin_app` (интерфейс) и тонкий бинарник `chesspenguin`. + Настольная программа и сборки пакетов не изменились: имя бинарника, ресурсы, тесты — прежние. +- `apps/web` — точка входа для браузера: `#[wasm_bindgen] start(canvas_id)` → `chesspenguin_app::start_web` + (сначала данные программы из хранилища браузера, затем `eframe::WebRunner`). На других целях крейт пустой. +- `cfg(web)` — WebAssembly в браузере (`wasm32-unknown-unknown`); его ставит `apps/desktop/build.rs`. + В крейтах ядра — `cfg(target_family = "wasm")`. + +Альтернатива — вынести интерфейс в отдельный крейт `crates/app-ui` — отложена: это перемещение 56 000 строк, +которое столкнулось бы с параллельной работой в `main`; библиотека внутри `apps/desktop` даёт то же +разделение без переноса файлов. + +## 2. Слой платформы (`apps/desktop/src/platform`) + +Интерфейс спрашивает у него, а не у системы: + +| Что | Компьютер (`native.rs`) | Браузер (`web/`) | +| --- | --- | --- | +| Каталоги программы: `config_dir`, `data_dir`, `cache_dir`, `examples_dir` | `directories` (`~/.config/chesspenguin` …) | имена в файловом дереве страницы: `/config`, `/data`, `/cache`, `/examples` | +| Файлы `platform::fs` (`read`, `read_head`, `write_atomic`, `meta`, `exists`, `remove_file`) | `std::fs`, запись через временный файл и переименование | `web/vfs.rs`: файлы в памяти; `/config`, `/data`, `/cache` пишутся в IndexedDB (`web/idb.rs`) и читаются оттуда до старта интерфейса; `/examples` (встроенные примеры) и `/opened` (файлы пользователя) живут на сеанс и только читаются | +| Фоновая работа `platform::spawn` | поток с именем | задача на потоке страницы после текущего кадра (`spawn_local`); это одна конечная работа, не цикл с ожиданием | +| Открыть базу `platform::open_database(path, progress, cancel, done)` — вдали от экрана, `done` получает базу | поток с `chess_import::open(path)` | читатель страницы (`web/import.rs`, §9): воркер со вторым экземпляром программы, обратно — текст и индекс | +| Файлы пользователя `platform::files` | `pick_databases` — диалог rfd в потоке; `take_dropped` — ничего (программа файлов не принимает, как и раньше) | Chrome/Edge — `showOpenFilePicker`, файл запоминается (`web/remembered.rs`, §9); остальные — `` (`#cp-open-files`); перетаскивание на окно (`dropped_files` → `File`), подсветка «Отпустите, чтобы открыть»; `download_pgn` — скачивание (Blob + ``) | +| Страница `platform::page` | ничего | партия на экране — запись истории браузера (`pushState`), «Назад» = «← Библиотека»; `beforeunload`, пока есть несохранённое | +| Где движок `engines::EngineLocation` | `Program(PathBuf)` | `Worker(String)` — адрес скрипта воркера | +| Буфер обмена `platform::clipboard::read_text` | arboard, сразу | `navigator.clipboard.readText()`, ответ позже (браузер может спросить пользователя) | +| Звук (`sound.rs`) | rodio в потоке | `HtmlAudioElement` с `blob:`-адресом каждого звука | +| Журнал `platform::log` | `chesspenguin.log` | консоль браузера | +| Что есть вообще `platform::CAPS` | всё | без обновлений, онлайн-партий, игры с компьютером, подготовки, перевода, своих баз, программ-движков, тренажёра; сохранение партии — скачивание | + +Время — `web_time::Instant` / `SystemTime` (на компьютере это `std`, в браузере `performance.now()` / +`Date.now()`); `std::time::Instant::now()` в браузере паникует. Дата новой партии — `chrono` с фичей +`wasmbind`; язык при первом запуске — `sys-locale` с фичей `js` (`navigator.languages`), `?lang=` страницы +важнее выбранного раньше. + +### Чего в браузере нет — того нет и в сборке + +Правило: функция, которой в браузере нет, **не собирается** для него (`#[cfg(not(web))]`), а не «есть и +отвечает ошибкой». Исключения — места, где у функции есть естественный ответ «здесь этого нет», уже +существующий в программе (как на компьютере без опубликованной сборки движка): + +- `update`, `update_ui`, `online_ui`, `graphics` — модули только настольной программы; `online::Probe` тоже. + В `app.rs` они собраны в `Desktop` (одно поле и один метод `desktop_frame`). +- Действия, которых в браузере нет (`LibraryAction::OpenUpdate`, `OnlineGames`, `UpdateOnline`, + `GameAction::OpenUpdate`, `SettingsAction::CheckUpdates/OpenUpdate/AddEngine/PickBaseFolder`, + `OfferEvent::ChooseFile`), не существуют в веб-сборке вместе с кнопками, которые их создают. +- Движки как процессы: `uci::Engine::spawn_with` и `EngineConfig`, `game_review::run` (задание разбора в + процессах), `prep::analyse`, `RodentPlayer`, запуск `Judge` — только на компьютере. +- Загрузки (Stockfish, Maia, Rodent) — блокирующие запросы в потоке: `run`, `fetch`, `unpack` только на + компьютере. В браузере у Stockfish своя загрузка (`platform/web/engine.rs`, §8); Maia и Rodent отвечают + «нет загрузки для этой платформы» (`Failure::Unsupported`), как на компьютере без сборки. Перевод: `list_models`, `chat`, `chatgpt::models/respond` в браузере отвечают + `Failure::Offline` (запросов к сервисам веб-версия не делает), вход в ChatGPT — ошибкой. +- `review::spawn_job` (общий для разбора и подготовки): на компьютере поток с `game_review::run`, в браузере + `game_review::Dispatcher` на воркерах; `JobRunner::pump` каждый кадр передаёт его события (§8). + +Веб-сборка компилирует части интерфейса, которые не показывает (их скрывает `CAPS`), поэтому в ней +выключены предупреждения о неиспользуемом (`#![cfg_attr(web, allow(unused, clippy::drop_non_drop))]` в +`lib.rs`); неиспользуемое ищет настольная сборка. Слой платформы проверяется в обеих +(`#![cfg_attr(web, warn(unused))]`). + +## 3. Изменения в крейтах ядра + +| Крейт | Что | +| --- | --- | +| `uci` | Протокол — автомат без ввода-вывода (`protocol.rs`: `Handshake`, `Session`, `Link`; на вход строки движка, команды и время, на выход строки и события, дедлайны называются, а не ждутся). Транспорты: процесс (`process.rs`, потоки чтения и супервизор, как раньше; только не в браузере) и Web Worker (`worker.rs`, только в браузере: строка UCI — одно сообщение; дедлайны — таймеры `setTimeout`; рукопожатие не блокирует — `Engine::start_worker` → `Starting::poll`). `EngineHandle` в обоих — с теми же методами, кроме блокирующих (`recv_timeout`) и процессных (`pid`, `stderr_tail`). Проверка опций и поиска — общая. | +| `chess-import` | `parallel::map` — рабочие потоки проходов (ускоритель, поиск по позиции, дебютные подсчёты); один рабочий — на вызывающем потоке; в браузере рабочий всегда один (`std::thread::spawn` там паникует). `read_at` / `write_all_at` — переносимая ветка через курсор для целей кроме Unix и Windows. `bench` — только на компьютере. Файлы закрываются концом блока перед переименованием (вместо `drop`). | +| `game-review` | Задание в процессах — `job/engines.rs` (только на компьютере); типы, константы и оценка времени — общие. | +| `online-games` | Сетевая часть (поиск ника, проба, загрузка в базу, их тесты) — `net.rs`, `ureq` только там; имена баз и состояния — для всех. | +| `play` | `Judge::start` и `RodentPlayer` — процессы, только на компьютере; `getrandom` с бэкендом браузера. | +| `prep` | `analyse` — только на компьютере. | +| `trainer` | Срок подсказки — `web_time::Instant`. | + +Поведение настольной программы и Android не менялось; тесты те же (`cargo test --workspace`), добавлены +тесты автомата `uci`, `parallel::map` и воркера. + +## 4. Страница `/app/` + +`apps/web/page/`: `index.html` (холст, строка загрузки, страница для телефонов), `device.js` +(`deviceClass()` — `docs/design/web-version.md` §3.6.1; одна функция для сайта и `/app/`, сайт возьмёт её при +выкладке), `page.js`: + +- до загрузки программы страница решает, что за устройство: **компьютер** — грузит `chesspenguin_web.js` + и `start('cp-canvas')`; **телефон или планшет** (iPhone, iPad, Android, «версия для ПК» на сенсорном + экране без мыши) — страница о приложениях: Android — две загрузки APK (`/download/android-noengine`, + `/download/android`), Android старше 12 — объяснение; iPhone/iPad — «скоро будет», «Отправить ссылку + себе», почта и Telegram; прочие — общий текст. Внизу тихая «Всё равно открыть веб-версию» (запоминается + в `localStorage` `cp.web.phoneAnyway`). Программа на таких устройствах не скачивается. +- `?phone=1` — страница о приложениях на любом устройстве (`?phone=android`, `?phone=ios` — её варианты), + `?phone=0` — программа; `?lang=xx` — язык. +- Тексты — ключи `app_*` в `website/site/i18n/*.json` (9 языков; `uz`, `kk` — проверить носителем) и общие + ключи сайта; `build.sh` кладёт их в страницу (≈ 20 КБ). Сайт сейчас не меняется: `/app/` подключается при + выкладке (этап 2: заголовки COOP/COEP, сжатие). + +## 5. Сборка + +Выбран **wasm-bindgen-cli + свой скрипт** (`apps/web/build.sh`), без trunk: страница `/app/` собирается +из текстов сайта и будет отдаваться сервером сайта, а trunk добавил бы свой конвейер HTML и ещё один +инструмент. Нужно: + +```sh +rustup target add wasm32-unknown-unknown +cargo install wasm-bindgen-cli --version 0.2.129 # версия wasm-bindgen из Cargo.lock; скрипт сверяет +apps/web/build.sh # профиль web (opt-level s, LTO, panic=abort) → target/web/app/ +PROFILE=release apps/web/build.sh # быстрее собирается, больше +``` + +`.cargo/config.toml` задаёт для `wasm32-unknown-unknown` `getrandom_backend="wasm_js"` (getrandom 0.3 из +`ahash`/egui; фича `wasm_js` — в `apps/desktop`). `wasm-opt` (binaryen) используется, если установлен. + +Размер загрузки (замер 2026-10-30, без `wasm-opt`): + +| Профиль | `.wasm` | gzip -9 | brotli -11 | сборка | +| --- | --- | --- | --- | --- | +| `web` (opt-level s, LTO fat, 1 CGU, panic=abort) | 19,1 МБ | 7,8 МБ | 6,3 МБ | ≈ 1 мин | +| `release` | 23,6 МБ | 8,9 МБ | 6,8 МБ | ≈ 0,5 мин | + +Плюс `chesspenguin_web.js` 165 КБ и страница 21 КБ. Движок (`/app/engine/`, только по согласию): +`stockfish-19-single.wasm` 99,2 МБ (77,6 МБ в Brotli) и скрипт 28 КБ. Около 5 МБ — встроенные ресурсы (доски, фигуры, +звуки, шрифты, таблицы дебютов): их можно отдавать отдельными файлами по требованию (не сделано). + +## 6. Проверки (`apps/web/check/`, Node 22+, Firefox и Chromium; окна не открываются) + +```sh +node apps/web/check/device.test.mjs # классы устройств (14 случаев) +node apps/web/check/uci-worker.mjs # транспорт uci в браузере (wasm-bindgen-test-runner в PATH) +node apps/web/check/review.mjs target/web/app <папка> target/chesscom-check/v1 crates/game-review/chesscom/*.pgn + # разбор в браузере = разбор на компьютере (после chesscom_check) +KEEP_X=387 KEEP_Y=133 node apps/web/check/stage2.mjs target/web/app <папка> # «Мои партии», копия, файлы визита +DOWNLOAD_X=1263 DOWNLOAD_Y=24 E2=519,703 E4=519,505 \ + node apps/web/check/app.mjs target/web/app <папка скриншотов> +# те же сценарии в Chromium / Chrome for Testing: +CP_BROWSER=chromium CP_CHROME=target/webresearch/chrome/chrome-linux64/chrome TMPDIR=/tmp/c node apps/web/check/app.mjs … +``` + +`browser.mjs` — один интерфейс вкладки для обоих браузеров: Firefox по WebDriver BiDi, Chromium по +DevTools protocol (`--headless=new`, временный профиль, остановка по PID). `t.choose(files, open)` — +пользователь выбирает файлы в диалоге, который открывает `open()`: в Firefox — `input.setFiles`; в +Chromium диалог `showOpenFilePicker` headless не управляется, поэтому проверка подставляет ручки из +приватной файловой системы сайта (OPFS) — тот же тип `FileSystemFileHandle`, хранится и читается заново +так же. `t.beforeLoad(js)` — скрипт до скриптов страницы (так проверяется ветка «браузер спрашивает»). +Chromium сокет-путь профиля должен быть коротким (`TMPDIR=/tmp/c`), иначе Chrome падает на +`SingletonSocket` («Socket path too long»). + +Chrome for Testing 156.0.8078.80 (linux64) взят с официального хранилища googlechromelabs +(`storage.googleapis.com/chrome-for-testing-public/156.0.8078.80/linux64/chrome-linux64.zip`), MD5 сверен с +`x-goog-hash` хранилища, распакован в `target/webresearch/chrome/` (без root, в репозиторий не входит). + +- `firefox.mjs` — headless Firefox с временным профилем и WebDriver BiDi, останавливается по PID; + `bidi.mjs` — клиент BiDi; `serve.py` — раскладка сайта (`/app/` и `/static/`). +- `app.mjs`: страница для телефона (ru, de; без загрузки `.wasm`), запуск программы, открытие PGN по + Ctrl+O с выбором файла через `input.setFiles`, перетаскивание файла на окно, партия из классики, ходы, + «Скачать PGN» (файл появляется в загрузках и это PGN партии), ход e2–e4 щелчками в новой партии, + перезагрузка (настройки и полка — из IndexedDB). Координаты кнопок — для окна 1400×860. +- `uci-worker.mjs`: `crates/uci/tests/worker.rs` (поддельный движок на JS): рукопожатие, анализ и стоп, + частые запросы без смешивания вывода, зависший на `stop`, падение, все отказы рукопожатия. +- `app.mjs` дальше: «Назад» браузера из партии ведёт в библиотеку; после хода в новой партии браузер + спрашивает при уходе (`onbeforeunload`), черновик в хранилище и после перезагрузки; в Chromium — файл, + выбранный до перезагрузки, прочитан сам, а при «спросить» — карточка «🔒 Разрешить чтение» и чтение после + ответа «Разрешить». +- Прогон 2026-10-30: `app.mjs`, `stage2.mjs`, `review.mjs` — в Firefox 159 и в Chrome for Testing 156, + `device.test.mjs` (без браузера) — всё ok, паник и ошибок в консоли нет. + +## 7. Многопоточный Stockfish и COOP/COEP: не нужны (решение этапа 2) + +Заголовки `Cross-Origin-Opener-Policy`/`Cross-Origin-Embedder-Policy` нужны только многопоточной сборке +(`SharedArrayBuffer`). Веб-версия берёт **только однопоточную** `stockfish-19-single`: + +- разбор партии и так однопоточный по решению 2026-10-28 (Threads 1, Hash 32, чистый хэш — одинаковые + оценки везде); скорость ему дают воркеры (по одному на логический процессор, не больше 8), а не потоки; +- многопоточная сборка — **другой файл** движка (`stockfish-19.wasm`, ещё 78 МБ на загрузку и в кэше): + ради ускорения только живого анализа пришлось бы скачивать два движка или терять детерминизм разбора; +- живой анализ в одном потоке: 0,6–0,7 Музл/с в Firefox (замер), глубина 20+ за несколько секунд — для + просмотра партии достаточно; +- `COEP: require-corp` на `/app/` требует, чтобы каждый ресурс страницы был своим или с CORP-заголовком; + сейчас это так, но любая внешняя картинка или скрипт ломались бы молча; плюс отличия Safari. + +Поэтому в `website/server` заголовки не добавлены, главная страница и скачивания не затронуты. Если позже +понадобится быстрее живой анализ — вторая сборка по отдельному согласию и COOP/COEP только для `/app/`. + +## 8. Этап 2: что сделано + +- **Движок.** `platform/web/engine.rs`: Stockfish.js 19.0.1 (npm `stockfish`, GPL-3.0; THIRD_PARTY_NOTICES), + однопоточная сборка лежит на нашем сайте рядом с программой (`/app/engine/`, `build.sh` проверяет sha512 + пакета). `.wasm` (99 МБ, 78 МБ в Brotli) скачивается только из окна «Для анализа нужен движок» (размер и + свободное место сайта — `navigator.storage.estimate()`), проверяется по SHA-256 и кладётся в Cache Storage; + воркеру движка он отдаётся как `blob:`-адрес после `#` (скрипт берёт адрес wasm оттуда) — повторно не + скачивается. `engine_download` в вебе: `available`, `size_mb`, `installed` (адрес воркера), `remove`, + `Download::start` (fetch с прогрессом и отменой). `EngineConfig::present()` — «движок есть» и для веба. +- **Живой анализ** — `uci::Engine::start_worker` из `analysis.rs`: линии, стрелки, шкала, MultiPV. +- **Разбор партии.** Что задание делает для одной цели (полный поиск, второй лучший без сыгранного хода, + неглубокие поиски) — автомат без ввода-вывода `game-review/src/job/work.rs`; на компьютере его ведут + процессы (`job/engines.rs`, поиски те же, что раньше), в браузере — `job/workers.rs::Dispatcher`: N + воркеров, каждый берёт следующую цель, всё по сообщениям, без ожиданий. Кэш разборов — через + `CacheStore` (папка или файлы платформы), формат тот же. +- **Сверка с настольной программой** — `apps/web/check/review.mjs`: браузер разбирает партии набора + `crates/game-review/chesscom/`, оценки читаются из его хранилища и сравниваются с кэшем `chesscom_check` + (нативный Stockfish 19, `target/chesscom-check/v1`) позиция за позицией (оценка, PV, глубина, + второй ход, неглубокий поиск). Замер 2026-10-30: 6 партий (evergreen, immortal, morphy-opera, + kasparov-topalov, owner-matovalov-1, tal-larsen), **359 позиций из 359 совпали полностью**, значит и отметки + !!/! те же. Разбор в Firefox headless на 8 воркерах — 12–28 с на партию. Перед этим нативный + `chesscom_check` после переделки задания на автомат прогнан заново: его оценки совпадают с отдельным запуском + Stockfish 19 с теми же командами. Попутная находка: старый кэш в основном каталоге + (`target/chesscom-check/v1`, от 2026-10-30 01:45) в 551 из 1487 позиций не совпадает со свежим поиском + (глубина и оценка) — он, видимо, сделан до нынешнего фиксированного поиска при той же версии + `SEARCH_VERSION`; проценты сверки с chess.com стоит пересчитать на свежем кэше (свежий прогон: !! найдено + 35 из 39 = 90 %, ! — 27 из 82 = 33 %). +- **«Мои партии»** (`my_games.rs`): PGN в хранилище браузера (`/data/my-games/…`), всегда на полке; Ctrl+S / + 💾 кладёт туда партию (в её запись или новой, без вопроса), удаление с отменой. Запись — те же байты, что на + компьютере: `chess_core::pgn::store` отдаёт результат `append/replace/remove/restore` байтами, + `platform::pgn_store` пишет их в файл (компьютер — как раньше) или в файлы страницы. При первом сохранении — + `navigator.storage.persist()`. +- **Настройки → «Данные в браузере»**: занято/свободно для сайта, постоянное хранение (и «Спросить браузер»), + «Мои партии» с размером и «Скачать всё в PGN», движок с «Удалить», предупреждение об очистке данных сайта. +- **Файлы.** Файл прошлого посещения (Firefox/Safari не дают к нему дороги): карточка «↻ Выбрать файл снова» + и экран с «Выбрать файл снова» / «Убрать из списка»; выбранный заново занимает его место на полке. + «Оставить копию в браузере» (кнопка в строке базы): копия в `/data/copies/`, отказ с объяснением, если + копии нужно больше (с запасом 10 %), чем браузер даёт сайту. Предел размера — §10. +- **Без справочника и поиска по позиции** (решение: в лёгкой версии нет): `CAPS.reference` прячет вкладку, + «Найти в базе», «Доска» в библиотеке и их клавиши. +- **Клавиши** (§4 дизайна): Alt+← — назад (Ctrl+W у браузера), 1…6 без модификатора — знаки, Ctrl+C — + копировать PGN, N в библиотеке — новая партия. + +## 9. Доработка этапа 2 + +- **База открывается в воркере** (`platform/web/import.rs`, `page/import-worker.js`). Воркер-модуль грузит + тот же `chesspenguin_web.js`/`.wasm` (второй экземпляр, модуль браузер берёт из кэша) и экспорт + `read_database(name, bytes, count)`: `chess_import::open_bytes` (PGN, CBV, ZIP, 7Z — в браузере всё + превращается в PGN) → `PgnDatabase::into_index()` → текст (передаётся без копии, transferable) и + `chess_core::PgnIndex` в JSON (serde за фичей `serde` у `chess-core`, включена только в веб-сборке). + Страница собирает базу `PgnDatabase::from_index` без повторного чтения; ошибки возвращаются своим + видом (`ImportError` ↔ `Failure`), поэтому тексты ошибок те же. Один воркер на визит, файлы по очереди. + Каталог фильтров строится уже на странице (из индекса, быстро). Замер (13,5 МБ CBV, самый длинный кадр за + время открытия): было 1000 мс (Firefox, открытие на потоке страницы), стало 17 мс (Firefox) и 67 мс + (Chromium). Прогресса чтения в вебе нет (строка «загрузка…» без числа). +- **Счётчики партий на карточках** (`db_counts.rs`): та же очередь заданий, что на компьютере; на + компьютере — свой поток, в браузере — тот же читатель, по одному файлу, ответ — только число партий. + Отметка файла — через `platform::fs::meta`, сохранение — `platform::fs`. +- **Chrome/Edge запоминают выбранный файл** (`platform/web/remembered.rs`): при наличии + `showOpenFilePicker` выбор идёт через него, ручка `FileSystemFileHandle` кладётся в IndexedDB (хранилище + `handles`, версия базы 2) под путём файла на странице. При следующем визите до старта интерфейса: + `queryPermission({mode:"read"})` = `granted` → файл читается сам; иначе карточка «🔒 Разрешить чтение», + по нажатию — `requestPermission` (вопрос браузера), затем база перечитывается. «Убрать из списка», + «Выбрать снова» и «Оставить копию» отпускают ручку. Только чтение: страница файлы пользователя не пишет. + Перетащенные файлы не запоминаются (egui отдаёт `File`, а не ручку) — для них текст «Перетащенный файл не + запоминается…». Папки открытых файлов нумеруются от времени визита (`/opened/<мс>/<имя>`), чтобы пути + разных визитов не совпадали. +- **Черновик несохранённой партии** (`my_games::Draft`, `/data/draft.json`): пока у партии есть изменения, + раз в 5 с пишется её PGN; сохранили или ушли без сохранения — черновик удаляется. При следующем старте над + библиотекой строка «Есть несохранённая партия: …, ходов: N» с «Открыть» / «Удалить». +- **Вопрос при уходе**: `beforeunload`, пока партия изменена или идёт разбор (`platform::page::warn_on_leave`). +- **«Назад» браузера**: вход в партию — `history.pushState({cpGame:true})`; `popstate` = «← Библиотека» (с теми + же вопросами о несохранённом); уход кнопкой программы снимает запись (`history.back()`, свой `popstate` + пропускается). +- **`EngineLocation`** (`engines.rs`): где запускается движок — `Program(PathBuf)` на компьютере, + `Worker(String)` (адрес скрипта) в браузере; анализ, задание разбора/подготовки, судья игры и настройки + берут его вместо пути. Настройки движка в вебе (без потоков и памяти) — сделано на этапе 2. + +## 10. Базы ChessBase в браузере и предел размера + +- **Файлы пользователя — `File` браузера, а не байты** (`vfs`: `Content::File`): страница не держит базу в + памяти, воркер-читатель получает `File` (без копии) и читает его сам, по одному файлу базы + (`reader_give`, затем `reader_read`). Копия в браузере («Оставить копию») читает файлы асинхронно и + кладёт всю базу в свою папку `/data/copies/<мс>/`. +- **ChessBase — несколько файлов.** Выбранные (или найденные в папке) файлы группируются + `chess_import::group_chosen`: `.cbh` и файлы того же имени рядом (регистр не важен), нужны `.cbh` и `.cbg` + (`chessbase::REQUIRED`), читаются `cbh, cbg, cba, cbp, cbt, cbc` (`chessbase::USED`); база кладётся в + одну папку на странице, путь — её `.cbh`; воркер собирает соседние файлы и вызывает + `chess_import::open_chessbase_owned` (байты отдаются, не копируются). +- **Выбран один `.cbh`** — сразу окно: «База ChessBase состоит из нескольких файлов… Выберите её папку + или сразу все её файлы» и подсказка «Разрешите доступ к папке базы — остальные файлы базы найдутся сами» + (Chrome/Edge) / «Выберите папку базы — …» (Firefox/Safari); кнопки «📁 Выбрать папку базы», «Выбрать + файлы базы», «Отмена». Без жеста пользователя браузер диалог папки не откроет, поэтому шаг — одно + нажатие в этом окне. Chrome/Edge: `showDirectoryPicker({mode:"read", startIn: <ручка .cbh>})` — диалог + открывается в папке выбранного файла, ручка папки запоминается (`{dir, names}` в IndexedDB) и при + следующем визите база появляется сама или через «🔒 Разрешить чтение». Firefox/Safari: + `` (берутся файлы прямо в папке). Папка без баз — сообщение «В этой папке нет + базы…». База с одним `.cbh` на полке (с прошлого визита) — экран с теми же кнопками. +- **Предел — 2 ГБ** по сумме файлов базы, которые читаются (`TOO_BIG`, для ChessBase — `USED`): больше — + окно «База слишком большая для браузера (N ГБ, предел 2,0 ГБ). Извините — откройте её в программе для + компьютера» со ссылкой «Скачать ChessPenguin для компьютера» (`/<язык>/#download`). Mega Database 2026 + (≈ 4,7 ГБ всего, читаемых файлов 2,2 ГБ) — отказ. Размеры везде — `platform::size_text`: единицы + (`{n} GB` → «ГБ», «Go») и десятичный знак (ключ `decimal comma`) по языку интерфейса. +- **Память, замер 2026-10-30**: PGN 1,95 ГБ (cp1251, 194 643 партии) открывается — Firefox 64 с, Chrome 60 с; + 1 ГБ — 32 с. Для этого исправлена `chess_core::repair::detect_letter_substitution`: она декодировала весь + текст и собирала `Vec` (×4 размера) — на компьютере лишние гигабайты, в wasm32 переполнение + `isize` (паника `capacity overflow` уже на 1 ГБ); теперь текст идёт кусками по 1 МБ. Если читателю всё же + не хватает памяти (wasm32: 4 ГБ, а один буфер — не больше 2 ГБ; база ChessBase превращается в PGN, который + может быть больше её файлов), воркер сообщает о сбое, страница пишет «Браузеру не хватает памяти для + этой базы. Откройте её в программе для компьютера» и заводит новый воркер. +- **Без служебных путей в текстах**: `platform::files::shown(path)` — имя файла в браузере, путь на + компьютере; ошибки чтения в вебе — без пути (`import_error`). +- Проверка `[CP_LANG=ru] apps/web/check/chessbase.mjs <папка небольшой базы> [<папка базы > 2 ГБ>]`: + одиночный `.cbh` → окно → папка → база прочитана; все файлы сразу; > 2 ГБ — отказ; в Chrome папка + запоминается. Firefox 159 и Chrome for Testing 156 — ok (тестовая база из `pgnFilesforExample/` только + локально, в репозиторий не входит). + +### Что не сделано + +- Прогресс чтения базы в воркере (сообщения о ходе разбора). +- Перетаскивание папки (egui отдаёт только файлы); несколько файлов базы перетащить можно. +- Запоминание перетащенных файлов в Chrome (`DataTransferItem.getAsFileSystemHandle` — egui его не отдаёт). +- Настоящий диалог `showOpenFilePicker` и настоящий вопрос «Разрешить» в Chrome headless не проверить: + проверены та же ручка из OPFS и ветки `granted` / `prompt` через подмену ответов браузера. + +## Изменения + +- 2026-10-30: этап 1 — слой платформы, `uci` с транспортом воркера, `apps/web`, страница `/app/`, проверки. +- 2026-10-30: этап 2 — движок, живой анализ, разбор на воркерах со сверкой, «Мои партии», данные в + браузере, файлы, клавиши; решение без COOP/COEP (§7). +- 2026-10-30: доработка (§9) — база в воркере, счётчики, Chrome/Edge помнят файлы, черновик, вопрос при + уходе, «Назад», `EngineLocation`; проверки в Chromium (Chrome for Testing 156). +- 2026-10-30: базы ChessBase из нескольких файлов и папки, предел 2 ГБ с вежливым отказом, понятные + сообщения без служебных путей, файлы пользователя читает воркер (§10). diff --git a/web/README.md b/web/README.md index 9da8ded..35c9b25 100644 --- a/web/README.md +++ b/web/README.md @@ -1,12 +1,18 @@ -# ChessPenguin в браузере (подпроект, исследование) +# ChessPenguin в браузере (подпроект) -Цель — версия программы, которая запускается в браузере, как настольная: открыть PGN и -ChessBase, смотреть партии, анализировать движком, разбирать партию с !! и !. +Цель — версия программы, которая запускается в браузере на компьютере, как настольная: открыть PGN и +ChessBase, смотреть партии, анализировать движком, разбирать партию с !! и !. Телефоны и планшеты +получают страницу о приложениях (решения владельца — `docs/decisions.md`, «Веб-версия»). -Статус: исследование (2026-10-30), кода ещё нет. Задача — `docs/dev/tasks.md` §22. +Статус: **этап 1 сделан** (2026-10-30, ветка `web-app`): программа собирается для браузера и работает в +Firefox — открыть PGN кнопкой и перетаскиванием, примеры, партия, ходы, скачать PGN; страница для +телефонов и планшетов. Дальше — движок, разбор, «Мои партии» (этап 2). Задача — `docs/dev/tasks.md` §22. -- Концепция, аналоги, что нужно пользователю — `docs/research/web-version.md` (аналитик). -- Техническая часть: что собирается для WebAssembly, что мешает, движок, файлы, потоки, - объём работ — `docs/research/web-version-tech.md` (разработчик). +- Архитектура, сборка, проверки, что дальше — `docs/dev/web.md` (разработчик). +- Код: `apps/web` (точка входа, страница `/app/`, `build.sh`, проверки в `check/`), слой платформы + `apps/desktop/src/platform`, транспорт движка в браузере `crates/uci/src/worker.rs`. +- Интерфейс — `docs/design/web-version.md` (дизайнер). +- Концепция, аналоги — `docs/research/web-version.md` (аналитик); техническое исследование — + `docs/research/web-version-tech.md`. -Опыты сборки — только в `target/` (не в репозитории), пока не выбран путь. +Сборка: `apps/web/build.sh` → `target/web/app/` (подробности — `docs/dev/web.md` §5). diff --git a/website/server/src/main.rs b/website/server/src/main.rs index 2cc78c2..01e6cd3 100644 --- a/website/server/src/main.rs +++ b/website/server/src/main.rs @@ -304,7 +304,14 @@ async fn main() { .route("/stats", get(stats)) .route("/stats.csv", get(stats_csv)) .route("/healthz", get(|| async { "ok" })) - .fallback_service(ServeDir::new(static_dir).fallback(get(not_found))) + .fallback_service( + // Precompressed copies (`.br`, `.gz`) next to a file go to the browsers that + // take them: the web version's program (/app/) is 23 MB, 6 MB in Brotli. + ServeDir::new(static_dir) + .precompressed_br() + .precompressed_gzip() + .fallback(get(not_found)), + ) .with_state(state); let listener = tokio::net::TcpListener::bind(("0.0.0.0", port)) .await diff --git a/website/site/i18n/de.json b/website/site/i18n/de.json index bf8a7bc..e0271e7 100644 --- a/website/site/i18n/de.json +++ b/website/site/i18n/de.json @@ -190,5 +190,20 @@ "play_b2": "Bedenkzeiten wie auf Lichess von 3+0 bis 30+20, eigene oder unbegrenzt; Uhren, Premoves, Zugrücknahme im Blitz, Remisangebote.", "play_b3": "Keine Engine-Hinweise während der Partie; ist die Stellung des Computers hoffnungslos, bietet er die Aufgabe an.", "play_b4": "Eine Partie lässt sich vertagen und später zu Ende spielen, die Uhren laufen dort weiter, wo sie standen. Jede Partie landet von selbst in Ihrer eigenen Datenbank; danach Analyse oder Revanche. Maia (316 MB) und Rodent (48–70 MB) werden beim ersten Spiel per Knopfdruck heruntergeladen; auf dem Handy ist Rodent schon dabei, seine Eröffnungsbücher (59 MB) werden einmal heruntergeladen.", - "play_link": "Über Maia" + "play_link": "Über Maia", + "app_title": "ChessPenguin – im Browser", + "app_phone_title": "ChessPenguin auf Handy und Tablet", + "app_and_lead": "Die Web-Version ist für Computer gemacht. Auf Handy und Tablet ist die Android-App bequemer – sie kann dasselbe: Datenbanken, Partien, Stockfish, Partieanalyse mit !! und !, Spiel gegen den Computer.", + "app_and_old": "Die App braucht Android 12 oder neuer, dieses Gerät hat Android {version}. Öffnen Sie ChessPenguin auf einem Computer.", + "app_and_more": "Installation – auf der Website", + "app_ios_lead": "Die App für iPhone und iPad kommt bald.", + "app_ios_now": "Bis dahin läuft ChessPenguin auf Computern – auch direkt im Browser – und unter Android. Schicken Sie sich den Link und öffnen Sie ihn am Computer.", + "app_send_link": "Link an mich senden", + "app_ios_notify": "Möchten Sie erfahren, wann sie erscheint? Schreiben Sie uns:", + "app_phone_generic": "Die Web-Version ist für Computer gemacht. Für Android gibt es eine App, die für iPhone und iPad kommt bald.", + "app_open_anyway": "Web-Version trotzdem öffnen", + "app_open_anyway_note": "Sie ist für den großen Bildschirm eines Computers gemacht: Auf Handy und Tablet ist alles klein, und für die Analyse lädt sie die Engine herunter ({size}).", + "app_nojs": "ChessPenguin braucht JavaScript.", + "app_loading": "ChessPenguin wird geladen…", + "app_failed": "ChessPenguin ist in diesem Browser nicht gestartet. Aktualisieren Sie den Browser oder öffnen Sie die Seite in Chrome, Edge, Firefox oder Safari." } diff --git a/website/site/i18n/en.json b/website/site/i18n/en.json index 81f5df7..aeb3fe0 100644 --- a/website/site/i18n/en.json +++ b/website/site/i18n/en.json @@ -190,5 +190,20 @@ "play_b2": "Lichess time controls from 3+0 to 30+20, your own, or unlimited; clocks, premoves, take-backs in blitz, draw offers.", "play_b3": "No engine hints during the game; when the computer’s position is hopeless, it offers to resign.", "play_b4": "A game can be put aside and finished later, the clocks going on where they stopped. Every game goes into your own database by itself; then analysis or a rematch. Maia (316 MB) and Rodent (48–70 MB) are downloaded with a button the first time you play; on the phone Rodent is already inside, and its opening books (59 MB) are downloaded once.", - "play_link": "About Maia" + "play_link": "About Maia", + "app_title": "ChessPenguin — in the browser", + "app_phone_title": "ChessPenguin on phones and tablets", + "app_and_lead": "The web version is made for computers. On a phone or tablet the Android app is more convenient — it has the same things: databases, games, Stockfish, game review with !! and !, playing against the computer.", + "app_and_old": "The app needs Android 12 or newer, and this device has Android {version}. Open ChessPenguin on a computer.", + "app_and_more": "How to install — on the website", + "app_ios_lead": "The iPhone and iPad app is coming soon.", + "app_ios_now": "For now ChessPenguin runs on computers — right in the browser too — and on Android. Send yourself the link and open it on a computer.", + "app_send_link": "Send the link to yourself", + "app_ios_notify": "Want to know when it's out? Write to us:", + "app_phone_generic": "The web version is made for computers. There is an app for Android, and one for iPhone and iPad is coming soon.", + "app_open_anyway": "Open the web version anyway", + "app_open_anyway_note": "It is made for a computer's big screen: on a phone or tablet everything is small, and for analysis it downloads the engine ({size}).", + "app_nojs": "ChessPenguin needs JavaScript.", + "app_loading": "Loading ChessPenguin…", + "app_failed": "ChessPenguin did not start in this browser. Update the browser or open the page in Chrome, Edge, Firefox or Safari." } diff --git a/website/site/i18n/es.json b/website/site/i18n/es.json index 0e9c998..1f9049e 100644 --- a/website/site/i18n/es.json +++ b/website/site/i18n/es.json @@ -190,5 +190,20 @@ "play_b2": "Ritmos de Lichess de 3+0 a 30+20, el tuyo o sin límite; relojes, premovimientos, deshacer jugada en blitz, ofertas de tablas.", "play_b3": "Sin pistas del motor durante la partida; cuando la posición del ordenador es desesperada, propone rendirse.", "play_b4": "Una partida se puede aplazar y terminar más tarde; los relojes siguen donde se quedaron. Cada partida se guarda sola en tu base; después, análisis o revancha. Maia (316 MB) y Rodent (48–70 MB) se descargan con un botón la primera vez que juegas; en el teléfono Rodent ya viene incluido y sus libros de aperturas (59 MB) se descargan una sola vez.", - "play_link": "Sobre Maia" + "play_link": "Sobre Maia", + "app_title": "ChessPenguin en el navegador", + "app_phone_title": "ChessPenguin en el móvil y la tableta", + "app_and_lead": "La versión web está pensada para ordenador. En el móvil y la tableta es más cómoda la app para Android, que tiene lo mismo: bases, partidas, Stockfish, análisis de la partida con !! y !, juego contra el ordenador.", + "app_and_old": "La app necesita Android 12 o posterior, y este dispositivo tiene Android {version}. Abre ChessPenguin en un ordenador.", + "app_and_more": "Cómo instalar, en el sitio web", + "app_ios_lead": "La app para iPhone y iPad llegará pronto.", + "app_ios_now": "Mientras tanto, ChessPenguin funciona en ordenadores, también directamente en el navegador, y en Android. Envíate el enlace y ábrelo en un ordenador.", + "app_send_link": "Enviarme el enlace", + "app_ios_notify": "¿Quieres saber cuándo sale? Escríbenos:", + "app_phone_generic": "La versión web está pensada para ordenador. Para Android hay una app, y la de iPhone y iPad llegará pronto.", + "app_open_anyway": "Abrir la versión web de todos modos", + "app_open_anyway_note": "Está pensada para la pantalla grande de un ordenador: en el móvil y la tableta todo se ve pequeño y, para analizar, descarga el motor ({size}).", + "app_nojs": "ChessPenguin necesita JavaScript.", + "app_loading": "Cargando ChessPenguin…", + "app_failed": "ChessPenguin no se ha iniciado en este navegador. Actualiza el navegador o abre la página en Chrome, Edge, Firefox o Safari." } diff --git a/website/site/i18n/fr.json b/website/site/i18n/fr.json index edc1c2f..0c7f8fc 100644 --- a/website/site/i18n/fr.json +++ b/website/site/i18n/fr.json @@ -190,5 +190,20 @@ "play_b2": "Cadences Lichess de 3+0 à 30+20, la vôtre ou sans limite ; pendules, prémouvements, reprise de coup en blitz, propositions de nulle.", "play_b3": "Aucune aide du moteur pendant la partie ; quand la position de l’ordinateur est perdue, il propose d’abandonner.", "play_b4": "Une partie peut être ajournée et finie plus tard, les pendules reprenant là où elles s’étaient arrêtées. Chaque partie va d’elle-même dans votre base ; ensuite, l’analyse ou une revanche. Maia (316 Mo) et Rodent (48–70 Mo) se téléchargent d’un bouton à la première partie ; sur le téléphone, Rodent est déjà inclus et ses livres d’ouvertures (59 Mo) se téléchargent une seule fois.", - "play_link": "À propos de Maia" + "play_link": "À propos de Maia", + "app_title": "ChessPenguin — dans le navigateur", + "app_phone_title": "ChessPenguin sur téléphone et tablette", + "app_and_lead": "La version web est faite pour l'ordinateur. Sur téléphone et tablette, l'application Android est plus pratique — elle fait la même chose : bases, parties, Stockfish, analyse de partie avec !! et !, jeu contre l'ordinateur.", + "app_and_old": "L'application nécessite Android 12 ou plus récent ; cet appareil a Android {version}. Ouvrez ChessPenguin sur un ordinateur.", + "app_and_more": "Comment installer — sur le site", + "app_ios_lead": "L'application pour iPhone et iPad arrive bientôt.", + "app_ios_now": "En attendant, ChessPenguin fonctionne sur ordinateur — aussi directement dans le navigateur — et sur Android. Envoyez-vous le lien et ouvrez-le sur un ordinateur.", + "app_send_link": "M'envoyer le lien", + "app_ios_notify": "Vous voulez savoir quand elle sortira ? Écrivez-nous :", + "app_phone_generic": "La version web est faite pour l'ordinateur. Il existe une application Android, celle pour iPhone et iPad arrive bientôt.", + "app_open_anyway": "Ouvrir quand même la version web", + "app_open_anyway_note": "Elle est faite pour le grand écran d'un ordinateur : sur téléphone et tablette tout est petit, et pour l'analyse elle télécharge le moteur ({size}).", + "app_nojs": "ChessPenguin a besoin de JavaScript.", + "app_loading": "Chargement de ChessPenguin…", + "app_failed": "ChessPenguin n'a pas démarré dans ce navigateur. Mettez le navigateur à jour ou ouvrez la page dans Chrome, Edge, Firefox ou Safari." } diff --git a/website/site/i18n/it.json b/website/site/i18n/it.json index 3fc78bd..3b60216 100644 --- a/website/site/i18n/it.json +++ b/website/site/i18n/it.json @@ -190,5 +190,20 @@ "play_b2": "Cadenze di Lichess da 3+0 a 30+20, la tua o illimitata; orologi, premosse, ritiro della mossa nel blitz, proposte di patta.", "play_b3": "Nessun suggerimento del motore durante la partita; quando la posizione del computer è persa, propone di abbandonare.", "play_b4": "Una partita si può sospendere e finire più tardi, con gli orologi che ripartono da dove si erano fermati. Ogni partita finisce da sola nel tuo database; poi analisi o rivincita. Maia (316 MB) e Rodent (48–70 MB) si scaricano con un pulsante la prima volta che giochi; sul telefono Rodent è già incluso e i suoi libri di aperture (59 MB) si scaricano una volta sola.", - "play_link": "Informazioni su Maia" + "play_link": "Informazioni su Maia", + "app_title": "ChessPenguin nel browser", + "app_phone_title": "ChessPenguin su telefono e tablet", + "app_and_lead": "La versione web è pensata per il computer. Su telefono e tablet è più comoda l'app per Android, che fa le stesse cose: database, partite, Stockfish, analisi della partita con !! e !, gioco contro il computer.", + "app_and_old": "L'app richiede Android 12 o successivo, e questo dispositivo ha Android {version}. Apri ChessPenguin su un computer.", + "app_and_more": "Come installare — sul sito", + "app_ios_lead": "L'app per iPhone e iPad arriverà presto.", + "app_ios_now": "Nel frattempo ChessPenguin funziona sul computer, anche direttamente nel browser, e su Android. Inviati il link e aprilo su un computer.", + "app_send_link": "Inviami il link", + "app_ios_notify": "Vuoi sapere quando esce? Scrivici:", + "app_phone_generic": "La versione web è pensata per il computer. Per Android c'è un'app, quella per iPhone e iPad arriverà presto.", + "app_open_anyway": "Apri comunque la versione web", + "app_open_anyway_note": "È pensata per lo schermo grande di un computer: su telefono e tablet è tutto piccolo e per l'analisi scarica il motore ({size}).", + "app_nojs": "ChessPenguin richiede JavaScript.", + "app_loading": "Caricamento di ChessPenguin…", + "app_failed": "ChessPenguin non si è avviato in questo browser. Aggiorna il browser o apri la pagina in Chrome, Edge, Firefox o Safari." } diff --git a/website/site/i18n/kk.json b/website/site/i18n/kk.json index 8e00df9..fef2dcd 100644 --- a/website/site/i18n/kk.json +++ b/website/site/i18n/kk.json @@ -190,5 +190,20 @@ "play_b2": "Lichess-тегідей уақыт бақылауы — 3+0-ден 30+20-ға дейін, өзіңіздікі немесе шексіз; сағаттар, алдын ала жүріс, блицте жүрісті қайтару, тең ойын ұсынысы.", "play_b3": "Ойын кезінде қозғалтқыш кеңестері жоқ; компьютердің позициясы үмітсіз болса, ол берілуді ұсынады.", "play_b4": "Ойынды кейінге қалдырып, кейін аяқтауға болады — сағаттар тоқтаған жерінен жалғасады. Әр ойын өзі сіздің базаңызға жазылады; одан кейін талдау немесе реванш. Maia (316 МБ) және Rodent (48–70 МБ) алғашқы ойында түймемен жүктеледі; телефонда Rodent ішінде бар, оның дебют кітаптары (59 МБ) бір рет жүктеледі.", - "play_link": "Maia туралы" + "play_link": "Maia туралы", + "app_title": "ChessPenguin — браузерде", + "app_phone_title": "ChessPenguin телефон мен планшетте", + "app_and_lead": "Веб-нұсқа компьютерге арналған. Телефон мен планшетте Android қолданбасы ыңғайлырақ — онда бәрі бар: базалар, партиялар, Stockfish, !! және ! белгілерімен партия талдауы, компьютермен ойын.", + "app_and_old": "Қолданбаға Android 12 не одан жаңасы керек, ал бұл құрылғыда Android {version}. ChessPenguin-ді компьютерде ашыңыз.", + "app_and_more": "Қалай орнату — сайтта", + "app_ios_lead": "iPhone мен iPad-қа арналған қолданба жақында шығады.", + "app_ios_now": "Әзірге ChessPenguin компьютерде — тікелей браузерде де — және Android-та жұмыс істейді. Сілтемені өзіңізге жіберіп, оны компьютерде ашыңыз.", + "app_send_link": "Сілтемені өзіме жіберу", + "app_ios_notify": "Қашан шығатынын білгіңіз келе ме? Бізге жазыңыз:", + "app_phone_generic": "Веб-нұсқа компьютерге арналған. Android үшін қолданба бар, ал iPhone мен iPad үшін жақында шығады.", + "app_open_anyway": "Бәрібір веб-нұсқаны ашу", + "app_open_anyway_note": "Ол компьютердің үлкен экранына арналған: телефон мен планшетте бәрі ұсақ, ал талдау үшін қозғалтқышты ({size}) жүктеп алады.", + "app_nojs": "ChessPenguin үшін JavaScript керек.", + "app_loading": "ChessPenguin жүктелуде…", + "app_failed": "ChessPenguin бұл браузерде іске қосылмады. Браузерді жаңартыңыз немесе бетті Chrome, Edge, Firefox не Safari-де ашыңыз." } diff --git a/website/site/i18n/pt.json b/website/site/i18n/pt.json index 9e32afa..37d60c0 100644 --- a/website/site/i18n/pt.json +++ b/website/site/i18n/pt.json @@ -190,5 +190,20 @@ "play_b2": "Ritmos do Lichess de 3+0 a 30+20, o seu ou sem limite; relógios, pré-lances, voltar lance no blitz, propostas de empate.", "play_b3": "Sem dicas do motor durante a partida; quando a posição do computador está perdida, ele propõe desistir.", "play_b4": "Uma partida pode ser adiada e terminada mais tarde, com os relógios a continuar de onde pararam. Cada partida vai sozinha para a sua base; depois, análise ou revanche. A Maia (316 MB) e o Rodent (48–70 MB) são baixados com um botão na primeira partida; no telefone o Rodent já vem incluído e os seus livros de aberturas (59 MB) são baixados uma única vez.", - "play_link": "Sobre a Maia" + "play_link": "Sobre a Maia", + "app_title": "ChessPenguin no navegador", + "app_phone_title": "ChessPenguin no celular e no tablet", + "app_and_lead": "A versão web foi feita para computador. No celular e no tablet, o app para Android é mais prático — ele tem o mesmo: bases, partidas, Stockfish, análise da partida com !! e !, jogo contra o computador.", + "app_and_old": "O app precisa do Android 12 ou mais recente, e este aparelho tem Android {version}. Abra o ChessPenguin em um computador.", + "app_and_more": "Como instalar — no site", + "app_ios_lead": "O app para iPhone e iPad chega em breve.", + "app_ios_now": "Por enquanto, o ChessPenguin funciona no computador — inclusive direto no navegador — e no Android. Envie o link para você e abra em um computador.", + "app_send_link": "Enviar o link para mim", + "app_ios_notify": "Quer saber quando sai? Escreva para nós:", + "app_phone_generic": "A versão web foi feita para computador. Para Android há um app, e o do iPhone e iPad chega em breve.", + "app_open_anyway": "Abrir a versão web mesmo assim", + "app_open_anyway_note": "Ela foi feita para a tela grande de um computador: no celular e no tablet tudo fica pequeno, e para a análise ela baixa o motor ({size}).", + "app_nojs": "O ChessPenguin precisa de JavaScript.", + "app_loading": "Carregando o ChessPenguin…", + "app_failed": "O ChessPenguin não iniciou neste navegador. Atualize o navegador ou abra a página no Chrome, Edge, Firefox ou Safari." } diff --git a/website/site/i18n/ru.json b/website/site/i18n/ru.json index f893b72..47566bd 100644 --- a/website/site/i18n/ru.json +++ b/website/site/i18n/ru.json @@ -190,5 +190,20 @@ "play_b2": "Контроль времени как на Lichess — от 3+0 до 30+20, свой или бессрочно; часы, предходы, ход назад в блице, предложение ничьей.", "play_b3": "Во время партии подсказок движка нет; когда позиция компьютера безнадёжна, он предлагает сдаться.", "play_b4": "Партию можно отложить и доиграть позже — часы продолжат с того же места. Каждая партия сама записывается в вашу базу; дальше — анализ или реванш. Maia (316 МБ) и Rodent (48–70 МБ) скачиваются по кнопке при первой игре; на телефоне Rodent уже внутри, его книги дебютов (59 МБ) скачиваются один раз.", - "play_link": "О Maia" + "play_link": "О Maia", + "app_title": "ChessPenguin — в браузере", + "app_phone_title": "ChessPenguin на телефоне и планшете", + "app_and_lead": "Веб-версия сделана для компьютера. На телефоне и планшете удобнее приложение для Android — в нём то же самое: базы, партии, Stockfish, разбор с !! и !, игра с компьютером.", + "app_and_old": "Приложению нужен Android 12 или новее, а на этом устройстве Android {version}. Откройте ChessPenguin на компьютере.", + "app_and_more": "Как установить — на сайте", + "app_ios_lead": "Приложение для iPhone и iPad скоро будет.", + "app_ios_now": "А пока ChessPenguin работает на компьютере — в том числе прямо в браузере — и на Android. Отправьте себе ссылку и откройте её на компьютере.", + "app_send_link": "Отправить ссылку себе", + "app_ios_notify": "Хотите узнать, когда оно выйдет, — напишите нам:", + "app_phone_generic": "Веб-версия сделана для компьютера. На Android есть приложение, для iPhone и iPad оно скоро будет.", + "app_open_anyway": "Всё равно открыть веб-версию", + "app_open_anyway_note": "Она сделана для большого экрана компьютера: на телефоне и планшете всё мелко, а для анализа она скачивает движок ({size}).", + "app_nojs": "Для ChessPenguin нужен JavaScript.", + "app_loading": "ChessPenguin загружается…", + "app_failed": "ChessPenguin не запустился в этом браузере. Обновите браузер или откройте страницу в Chrome, Edge, Firefox или Safari." } diff --git a/website/site/i18n/uz.json b/website/site/i18n/uz.json index 18077e3..75b8ca6 100644 --- a/website/site/i18n/uz.json +++ b/website/site/i18n/uz.json @@ -190,5 +190,20 @@ "play_b2": "Lichess’dagidek vaqt nazorati — 3+0 dan 30+20 gacha, o‘zingizniki yoki cheksiz; soatlar, oldindan yurish, blitsda yurishni qaytarish, durang taklifi.", "play_b3": "O‘yin davomida dvigatel maslahatlari yo‘q; kompyuter pozitsiyasi umidsiz bo‘lsa, u taslim bo‘lishni taklif qiladi.", "play_b4": "O‘yinni keyinga qoldirib, keyinroq oxiriga yetkazish mumkin — soatlar to‘xtagan joyidan davom etadi. Har bir o‘yin o‘zi sizning bazangizga yoziladi; keyin tahlil yoki revansh. Maia (316 MB) va Rodent (48–70 MB) birinchi o‘yinda tugma bilan yuklab olinadi; telefonda Rodent allaqachon ichida, uning debyut kitoblari (59 MB) bir marta yuklab olinadi.", - "play_link": "Maia haqida" + "play_link": "Maia haqida", + "app_title": "ChessPenguin — brauzerda", + "app_phone_title": "ChessPenguin telefon va planshetda", + "app_and_lead": "Veb-versiya kompyuter uchun qilingan. Telefon va planshetda Android ilovasi qulayroq — unda hammasi bor: bazalar, partiyalar, Stockfish, !! va ! belgilari bilan partiya tahlili, kompyuter bilan oʻyin.", + "app_and_old": "Ilova uchun Android 12 yoki yangirogʻi kerak, bu qurilmada esa Android {version}. ChessPenguin’ni kompyuterda oching.", + "app_and_more": "Qanday oʻrnatish — saytda", + "app_ios_lead": "iPhone va iPad uchun ilova tez orada chiqadi.", + "app_ios_now": "Hozircha ChessPenguin kompyuterda — toʻgʻridan-toʻgʻri brauzerda ham — va Androidda ishlaydi. Havolani oʻzingizga yuboring va uni kompyuterda oching.", + "app_send_link": "Havolani oʻzimga yuborish", + "app_ios_notify": "Qachon chiqishini bilmoqchimisiz? Bizga yozing:", + "app_phone_generic": "Veb-versiya kompyuter uchun qilingan. Android uchun ilova bor, iPhone va iPad uchun esa tez orada chiqadi.", + "app_open_anyway": "Baribir veb-versiyani ochish", + "app_open_anyway_note": "U kompyuterning katta ekrani uchun qilingan: telefon va planshetda hammasi mayda, tahlil uchun esa dvijokni ({size}) yuklab oladi.", + "app_nojs": "ChessPenguin uchun JavaScript kerak.", + "app_loading": "ChessPenguin yuklanmoqda…", + "app_failed": "ChessPenguin bu brauzerda ishga tushmadi. Brauzerni yangilang yoki sahifani Chrome, Edge, Firefox yoki Safari’da oching." }