diff --git a/Cargo.lock b/Cargo.lock index 37cd7d9..defa3d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -850,6 +850,18 @@ dependencies = [ "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" @@ -857,7 +869,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", ] @@ -4428,7 +4442,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]] @@ -4678,6 +4695,7 @@ dependencies = [ "chrono", "serde", "serde_json", + "web-time", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 71cd9c0..a18757a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ members = [ "crates/play", "crates/prep", "apps/desktop", + "apps/web", ] [workspace.package] @@ -56,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/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index e3f2cd0..19e8abc 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,37 @@ 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] +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", +] } + [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..ce02388 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, @@ -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,47 @@ impl Analysis { } } +/// Starts the engine of `cfg` at `path` with its options. +#[cfg(not(web))] +fn launch( + path: std::path::PathBuf, + cfg: EngineConfig, + ctx: &egui::Context, +) -> Result { + 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 a worker: `path` is its script's address on the site. +#[cfg(web)] +fn launch( + path: std::path::PathBuf, + cfg: EngineConfig, + ctx: &egui::Context, +) -> Result { + let ctx = ctx.clone(); + uci::Engine::start_worker( + uci::WorkerConfig::new(path.to_string_lossy()), + 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..47c3c5b 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -215,19 +215,17 @@ pub struct App { play_next: Option, tx: Sender, rx: Receiver, + /// «Paste PGN»: the clipboard being read. + pasting: 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 +235,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 +251,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 +383,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(); @@ -376,12 +418,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 +446,12 @@ impl App { play_next: None, tx, rx, + pasting: 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 +460,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}", @@ -2052,6 +2078,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() @@ -2217,7 +2244,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 +2262,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 +2329,7 @@ impl App { } } + #[cfg(not(web))] fn spawn_dialog( &self, ctx: &egui::Context, @@ -2312,22 +2348,16 @@ 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 |paths| { + if !paths.is_empty() { + let _ = tx.send(Async::DatabasesPicked(paths)); + } + 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 +2371,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,6 +2404,7 @@ impl App { } fn handle_async(&mut self, ctx: &egui::Context) { + self.pasted(ctx); while let Ok(msg) = self.rx.try_recv() { match msg { Async::DatabasesPicked(paths) => { @@ -2691,16 +2723,38 @@ 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 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 +2894,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(); } @@ -3028,7 +3178,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 +3341,14 @@ 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(); + } for a in self.library.show(ui, &dbs, &self.settings) { match a { LibraryAction::OpenGame { path, index, at } => { @@ -3221,9 +3378,12 @@ 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); @@ -3262,88 +3422,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 +3438,19 @@ 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, SettingsAction::DownloadEngine => self.engine_offer.start(&ctx), SettingsAction::CancelDownload => self.engine_offer.cancel(), SettingsAction::RemoveDownloaded => { @@ -3500,7 +3584,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); } 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..426c974 100644 --- a/apps/desktop/src/db_counts.rs +++ b/apps/desktop/src/db_counts.rs @@ -172,7 +172,8 @@ fn stamp(path: &Path) -> Option<(u64, u64)> { #[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); diff --git a/apps/desktop/src/engine_download.rs b/apps/desktop/src/engine_download.rs index f0130a2..5a4af94 100644 --- a/apps/desktop/src/engine_download.rs +++ b/apps/desktop/src/engine_download.rs @@ -148,11 +148,28 @@ 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) } + /// A browser downloads no engine programs: there is no download for it, as for a + /// computer without a published build. + #[cfg(web)] + pub fn start(_ctx: &egui::Context) -> Download { + Download::unsupported() + } + + /// The download of a platform that has none. + #[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 +222,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 +246,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 +269,7 @@ pub fn fetch( result } +#[cfg(not(web))] fn fetch_into( url: &str, to: &Path, @@ -328,6 +348,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 +403,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); diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs index 663fd78..91cc0f8 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), } @@ -298,6 +299,7 @@ impl EngineOffer { if self.mode != Mode::Own { ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { if ui.button(tr("Choose engine file…")).clicked() { + #[cfg(not(web))] events.push(OfferEvent::ChooseFile); self.open = false; self.pending = None; @@ -368,6 +370,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); @@ -405,6 +409,7 @@ impl EngineOffer { if self.mode != Mode::Own { ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { if ui.button(tr("Choose engine file…")).clicked() { + #[cfg(not(web))] events.push(OfferEvent::ChooseFile); self.open = false; self.failure = None; diff --git a/apps/desktop/src/engines.rs b/apps/desktop/src/engines.rs index 7f91a19..46b8750 100644 --- a/apps/desktop/src/engines.rs +++ b/apps/desktop/src/engines.rs @@ -35,6 +35,7 @@ pub fn own_stockfish() -> Option { /// `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 +49,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..1d95583 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, @@ -796,6 +803,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,6 +969,18 @@ 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)) + + if cfg!(web) { + button( + ui, + if compact { + "⇩" + } else { + tr("⇩ Download PGN") + }, + ) + } else { + 0.0 + } + button(ui, "⏷") + button( ui, @@ -1085,11 +1108,22 @@ 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"); @@ -1538,7 +1572,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 { @@ -1934,6 +1968,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,7 +1984,7 @@ 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() { @@ -2286,7 +2325,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); } @@ -2320,7 +2359,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 +2370,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 +2551,7 @@ impl GameView { } return; } - let now = std::time::Instant::now(); + let now = web_time::Instant::now(); let clock = s .clock .as_ref() @@ -2551,7 +2588,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 +2668,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 +2708,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 +2740,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 +2842,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 +3043,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 +3145,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 +3363,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 +3858,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 +3907,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 +4441,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 diff --git a/apps/desktop/src/graphics.rs b/apps/desktop/src/graphics.rs index 9ac715e..8a7091c 100644 --- a/apps/desktop/src/graphics.rs +++ b/apps/desktop/src/graphics.rs @@ -162,7 +162,7 @@ pub fn options(mode: Mode) -> 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..8422b02 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,51 @@ 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 --- + [ + "⇩ 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..9ceccc7 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -1846,6 +1846,7 @@ impl LargeView { .on_disabled_hover_text(&online.hint) .clicked() { + #[cfg(not(web))] actions.push(LibraryAction::UpdateOnline(path.to_path_buf())); } } diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs new file mode 100644 index 0000000..bb2de84 --- /dev/null +++ b/apps/desktop/src/lib.rs @@ -0,0 +1,158 @@ +//! 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; +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; + 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 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..152a187 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -48,10 +48,13 @@ 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), OpenSettings, @@ -106,18 +109,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 } @@ -263,29 +263,27 @@ impl Library { 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, - ); - // The filters' index of a PGN is built here, not on the screen's thread - // (a large download takes a second, §9.7). - if let Ok(opened) = &res - && let Database::Pgn(pgn) = &opened.db - { - pgn.catalog(); - } - let _ = tx.send(res); - ctx.request_repaint(); - }); + let spawned = crate::platform::spawn("db-open", move || { + let res = crate::platform::open_database( + &path_owned, + &mut |sp| { + if let Ok(mut g) = p.lock() { + *g = sp; + } + ctx.request_repaint(); + }, + &c, + ); + // The filters' index of a PGN is built here, not on the screen's thread + // (a large download takes a second, §9.7). + if let Ok(opened) = &res + && let Database::Pgn(pgn) = &opened.db + { + pgn.catalog(); + } + let _ = tx.send(res); + ctx.request_repaint(); + }); let slot = match spawned { Ok(_) => Slot::Loading { progress, @@ -759,6 +757,7 @@ impl Library { { actions.push(LibraryAction::OpenSettings); } + #[cfg(not(web))] if let Some(v) = &self.update && crate::widgets::update_button(ui, v).clicked() { @@ -970,6 +969,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 { @@ -1043,6 +1043,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); } }); 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/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..83156b8 --- /dev/null +++ b/apps/desktop/src/platform/files.rs @@ -0,0 +1,93 @@ +//! 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. + +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", +]; + +/// Asks the user for databases to open; `then` gets their paths (nothing when the +/// user cancelled). The dialog does not hold the screen: `then` comes later. +pub fn pick_databases(then: impl FnOnce(Vec) + 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.unwrap_or_default()); + }); + } + #[cfg(web)] + { + let accept = DATABASES + .iter() + .step_by(2) + .map(|e| format!(".{e}")) + .collect::>() + .join(","); + super::web::page::pick_files(&accept, move |files| { + then( + files + .into_iter() + .map(|(name, bytes)| super::web::vfs::add_opened(&name, bytes)) + .collect(), + ); + }); + } +} + +/// The files dropped on the window in this frame, as databases to open: `then` gets +/// their paths once read (in a browser they are kept for the session like chosen +/// ones). The desktop program does not take dropped files: nothing comes there. +pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Vec) + 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; + } + wasm_bindgen_futures::spawn_local(async move { + let read = super::web::page::read_files(files).await; + then( + read.into_iter() + .map(|(name, bytes)| super::web::vfs::add_opened(&name, bytes)) + .collect(), + ); + }); + } +} + +/// 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..3ecda3c --- /dev/null +++ b/apps/desktop/src/platform/mod.rs @@ -0,0 +1,124 @@ +//! 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; + +/// 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 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, +}; + +/// 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, +}; + +/// 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) +} + +/// 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}"); +} + +/// Opens a database the library shows: its file on the disk, or in a browser the file +/// the user gave the page (or a sample built in). +pub fn open_database( + path: &std::path::Path, + progress: &mut dyn FnMut(chess_core::ScanProgress), + cancel: &std::sync::atomic::AtomicBool, +) -> Result { + imp::open_database(path, progress, cancel) +} diff --git a/apps/desktop/src/platform/native.rs b/apps/desktop/src/platform/native.rs new file mode 100644 index 0000000..49ab101 --- /dev/null +++ b/apps/desktop/src/platform/native.rs @@ -0,0 +1,42 @@ +//! 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, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + chess_import::open(path, progress, cancel) +} diff --git a/apps/desktop/src/platform/web/idb.rs b/apps/desktop/src/platform/web/idb.rs new file mode 100644 index 0000000..76e4d78 --- /dev/null +++ b/apps/desktop/src/platform/web/idb.rs @@ -0,0 +1,119 @@ +//! The program's data in the browser's storage: one IndexedDB database, one store of +//! files by path. Read whole at the start (settings and marks are small); every write +//! goes there behind the interface, in the order made. + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +const DB: &str = "chesspenguin"; +const STORE: &str = "files"; + +/// 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, 1)?; + 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()) + && !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() -> Option { + OPENED.with_borrow(|db| { + let tx = db + .as_ref()? + .transaction_with_str_and_mode(STORE, web_sys::IdbTransactionMode::Readwrite) + .ok()?; + tx.object_store(STORE).ok() + }) +} + +/// 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/mod.rs b/apps/desktop/src/platform/web/mod.rs new file mode 100644 index 0000000..652015d --- /dev/null +++ b/apps/desktop/src/platform/web/mod.rs @@ -0,0 +1,59 @@ +//! 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 idb; +pub mod page; +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: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let bytes = vfs::read(path).map_err(|source| ImportError::Io { + path: path.to_owned(), + source, + })?; + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + chess_import::open_bytes(&name, bytes, progress, cancel) +} diff --git a/apps/desktop/src/platform/web/page.rs b/apps/desktop/src/platform/web/page.rs new file mode 100644 index 0000000..72e0fc9 --- /dev/null +++ b/apps/desktop/src/platform/web/page.rs @@ -0,0 +1,120 @@ +//! The page around the program: choosing files, downloads, the next task. + +use std::cell::RefCell; + +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +/// The element through which files are chosen (one for the page; checks give it files). +pub const OPEN_INPUT_ID: &str = "cp-open-files"; + +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, made once: hidden, several files, `accept` the extensions. +fn open_input(accept: &str) -> Result { + let doc = document().ok_or("no document")?; + if let Some(el) = doc.get_element_by_id(OPEN_INPUT_ID) { + let input: web_sys::HtmlInputElement = el.dyn_into()?; + input.set_accept(accept); + return Ok(input); + } + let input: web_sys::HtmlInputElement = doc.create_element("input")?.dyn_into()?; + input.set_id(OPEN_INPUT_ID); + input.set_type("file"); + input.set_multiple(true); + input.set_accept(accept); + 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(""); + let Some(then) = ON_PICKED.with_borrow_mut(Option::take) else { + return; + }; + wasm_bindgen_futures::spawn_local(async move { + then(read_files(files).await); + }); + }); + 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) +} + +/// The contents of `files`, with their names (a file that cannot be read is left out). +pub async fn read_files(files: Vec) -> Vec<(String, Vec)> { + let mut out = Vec::with_capacity(files.len()); + for f in files { + match wasm_bindgen_futures::JsFuture::from(f.array_buffer()).await { + Ok(buf) => out.push((f.name(), js_sys::Uint8Array::new(&buf).to_vec())), + Err(e) => log::warn!("cannot read {}: {e:?}", f.name()), + } + } + out +} + +/// Asks the user for files (the browser's dialog); `then` gets their contents once +/// chosen. Must run soon after the user's click or key (a browser opens the dialog +/// only then: egui handles input in the next frame, well within that time). +pub fn pick_files(accept: &str, then: impl FnOnce(Vec<(String, Vec)>) + 'static) { + match open_input(accept) { + 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/vfs.rs b/apps/desktop/src/platform/web/vfs.rs new file mode 100644 index 0000000..44ca3ea --- /dev/null +++ b/apps/desktop/src/platform/web/vfs.rs @@ -0,0 +1,142 @@ +//! 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. + +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 { + bytes: Vec, + modified_ms: u64, + readonly: bool, +} + +thread_local! { + static FILES: RefCell> = const { RefCell::new(BTreeMap::new()) }; + /// The number of the last file opened (each gets a folder of 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 { + bytes, + modified_ms: 0, + readonly: false, + }, + ); + } + }); +} + +pub fn read(path: &Path) -> io::Result> { + FILES.with_borrow(|files| { + files + .get(path) + .map(|e| e.bytes.clone()) + .ok_or_else(|| not_found(path)) + }) +} + +pub fn meta(path: &Path) -> io::Result { + FILES.with_borrow(|files| { + files + .get(path) + .map(|e| Meta { + len: e.bytes.len() as u64, + 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 { + 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(()) + }) +} + +/// A file the user gave the page (chosen or dropped): kept for the session, only read. +/// Its path ends with its own name, in a folder of its own. +pub fn add_opened(name: &str, bytes: Vec) -> PathBuf { + let n = OPENED_COUNT.with_borrow_mut(|n| { + *n += 1; + *n + }); + // A name is a file's, not a path (a browser gives no folders; this makes sure). + let name = name.rsplit(['/', '\\']).next().unwrap_or(name); + let path = Path::new(OPENED).join(n.to_string()).join(name); + FILES.with_borrow_mut(|files| { + files.insert( + path.clone(), + Entry { + bytes, + modified_ms: now_ms(), + readonly: true, + }, + ); + }); + path +} diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 01749fc..5f1f4eb 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,26 @@ 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: std::path::PathBuf, ctx: &egui::Context) -> Option { + #[cfg(not(web))] + { + 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 +487,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 +573,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 +584,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 +609,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 +649,7 @@ impl Opponent { } } } + #[cfg(not(web))] Worker::Rodent(player) => { if let Some((m, pause)) = player.answer() { self.thinking = false; @@ -618,13 +661,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..aab8a4b 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,11 +946,7 @@ struct ListRow { event: String, } -enum JobMsg { - Event(JobEvent), - Done, - Failed(String), -} +use crate::review::JobMsg; struct EngineJob { rx: Receiver, @@ -1972,30 +1968,15 @@ 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(); - }); + let spawned = review::spawn_job( + "prep-engine", + path.clone(), + job_settings, + targets, + cancel.clone(), + tx, + ctx.clone(), + ); if let Err(e) = spawned { self.error = Some(e.to_string()); return; diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index 6402e42..883020c 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -33,12 +33,59 @@ pub enum ReportAction { Analyse, } -enum JobMsg { +/// What an engine job sends to the screen. +pub enum JobMsg { Event(JobEvent), Done, Failed(String), } +/// Runs the engine job over `targets` with ChessPenguin's Stockfish at `path` on a +/// thread named `name`: its events and its end come through `tx`, each waking `ctx`. +/// A browser starts no engine processes: there the job cannot run (the error). +pub fn spawn_job( + name: &str, + path: PathBuf, + settings: JobSettings, + targets: Vec, + cancel: Arc, + tx: std::sync::mpsc::Sender, + ctx: egui::Context, +) -> std::io::Result<()> { + #[cfg(not(web))] + { + 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 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.request_repaint(); + }) + .map(drop) + } + #[cfg(web)] + { + let _ = (name, path, settings, targets, cancel, tx, ctx); + Err(std::io::ErrorKind::Unsupported.into()) + } +} + struct Job { rx: Receiver, cancel: Arc, @@ -119,25 +166,15 @@ 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(); - }); + let spawned = spawn_job( + "game-review", + path.to_owned(), + settings, + targets, + cancel.clone(), + tx, + ctx.clone(), + ); if let Err(e) = spawned { self.error = Some(e.to_string()); return false; @@ -728,7 +765,8 @@ pub fn processes() -> usize { /// 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..7804ad7 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -222,14 +222,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 +239,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 +281,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 +295,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..da8137f 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -19,6 +19,7 @@ pub enum Tab { } pub enum SettingsAction { + #[cfg(not(web))] AddEngine, /// Download the official Stockfish (decision 14). DownloadEngine, @@ -29,10 +30,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, } @@ -99,35 +103,12 @@ impl SettingsWindow { 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 => { @@ -176,16 +157,18 @@ impl SettingsWindow { 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()) .on_hover_text(dir.display().to_string()); if ui.button(tr("Change…")).clicked() { + #[cfg(not(web))] actions.push(SettingsAction::PickBaseFolder); } }); @@ -245,6 +228,7 @@ impl SettingsWindow { actions.push(SettingsAction::DownloadEngine); } if ui.button(tr("Choose engine file…")).clicked() { + #[cfg(not(web))] actions.push(SettingsAction::AddEngine); } }); @@ -432,6 +416,7 @@ impl SettingsWindow { ) .clicked() { + #[cfg(not(web))] actions.push(SettingsAction::AddEngine); } if self.checking_engine { @@ -767,3 +752,40 @@ 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(); +} 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..950392f --- /dev/null +++ b/apps/web/build.sh @@ -0,0 +1,58 @@ +#!/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" "$out/" +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(" [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)): + 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/shot.mjs b/apps/web/check/shot.mjs new file mode 100644 index 0000000..10395ea --- /dev/null +++ b/apps/web/check/shot.mjs @@ -0,0 +1,18 @@ +// A screenshot of a page of the web version in headless Firefox, with its console: +// +// node apps/web/check/shot.mjs [wait-ms] [width] [height] +import { writeFileSync } from 'node:fs'; +import { launch } from './firefox.mjs'; +import { sleep, tab } from './bidi.mjs'; + +const [url, out, wait = '6000', width = '1400', height = '860'] = process.argv.slice(2); +const ff = await launch(); +try { + const t = await tab(ff.browser, Number(width), Number(height)); + await t.navigate(url); + await sleep(Number(wait)); + writeFileSync(out, await t.screenshot()); + console.log('saved', out); +} finally { + await ff.stop(); +} 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/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..9f802d9 --- /dev/null +++ b/apps/web/page/page.js @@ -0,0 +1,208 @@ +// 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=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: "../static/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 === "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..5280429 --- /dev/null +++ b/apps/web/src/lib.rs @@ -0,0 +1,24 @@ +//! 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::*; + +/// 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/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." }