Web version: the engine's location as a type, the browser's history and Back, the question on leaving, the draft of an unsaved game

EngineLocation: an engine starts from its program on a computer, from the
address of its Web Worker's script in a browser; analysis, the review job,
the judge and the settings take it instead of a path.

platform::page: a game on the screen is an entry of the browser's history,
so Back is «← Library» (with the same questions); unsaved changes or a
running review make the browser ask before the page is left. The draft of an
unsaved game is written every 5 s while it has changes and offered at the
next start (Open / Delete); a saved or left game takes it away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 17:35:30 +03:00
parent 3afeee09c7
commit 000821887f
15 changed files with 338 additions and 42 deletions

View file

@ -81,7 +81,8 @@ web-sys = { version = "0.3", features = [
"IdbTransactionMode", "IdbObjectStore", "DomStringList", "HtmlAudioElement",
"HtmlMediaElement", "HtmlCanvasElement", "console", "CacheStorage", "Cache",
"Request", "Response", "ResponseInit", "Headers", "ReadableStream",
"ReadableStreamDefaultReader", "StorageManager", "StorageEstimate",
"ReadableStreamDefaultReader", "StorageManager", "StorageEstimate", "History",
"BeforeUnloadEvent",
] }
[build-dependencies]

View file

@ -86,7 +86,7 @@ pub struct Analysis {
/// The current search ended (time limit reached); lines stay as the final result.
pub finished: bool,
/// Executable of the running engine (to detect a switch of the active engine).
pub engine_path: Option<std::path::PathBuf>,
pub engine_path: Option<crate::engines::EngineLocation>,
}
impl Analysis {
@ -296,10 +296,11 @@ impl Analysis {
/// Starts the engine of `cfg` at `path` with its options.
#[cfg(not(web))]
fn launch(
path: std::path::PathBuf,
location: crate::engines::EngineLocation,
cfg: EngineConfig,
ctx: &egui::Context,
) -> Result<Launch, String> {
let crate::engines::EngineLocation::Program(path) = location;
let (tx, rx) = std::sync::mpsc::channel();
let ctx_w = ctx.clone();
let ctx_done = ctx.clone();
@ -318,16 +319,17 @@ fn launch(
.map_err(|e| e.to_string())
}
/// Starts the engine of `cfg` in a worker: `path` is its script's address on the site.
/// Starts the engine of `cfg` in its Web Worker.
#[cfg(web)]
fn launch(
path: std::path::PathBuf,
location: crate::engines::EngineLocation,
cfg: EngineConfig,
ctx: &egui::Context,
) -> Result<Launch, String> {
let crate::engines::EngineLocation::Worker(script) = location;
let ctx = ctx.clone();
uci::Engine::start_worker(
uci::WorkerConfig::new(path.to_string_lossy()),
uci::WorkerConfig::new(script),
Box::new(move || ctx.request_repaint()),
)
.map(|s| Launch::Worker(s, cfg))

View file

@ -221,6 +221,12 @@ pub struct App {
pasting: Option<crate::platform::clipboard::Reading>,
/// A file of the last visit being chosen again (a browser's).
choosing_again: Option<PathBuf>,
/// The web version's draft of an unsaved game: the one left at the last visit
/// (offered), and when this visit's was last written (egui time; `None`: none).
#[cfg(web)]
draft_offer: Option<crate::my_games::Draft>,
#[cfg(web)]
draft_at: Option<f64>,
confirm_close: Option<CloseIntent>,
/// Close the game once the pending "save as" succeeds.
close_after_save: Option<CloseIntent>,
@ -457,6 +463,10 @@ impl App {
rx,
pasting: None,
choosing_again: None,
#[cfg(web)]
draft_offer: crate::my_games::read_draft(),
#[cfg(web)]
draft_at: None,
confirm_close: None,
close_after_save: None,
find_after_close: None,
@ -1786,7 +1796,7 @@ impl App {
self.settings
.active_engine()
.and_then(|e| e.executable())
.filter(|p| p.is_file())
.filter(|l| l.present())
});
let Some(aside) = self.put_aside.take() else {
return;
@ -2024,7 +2034,7 @@ impl App {
self.settings
.active_engine()
.and_then(|e| e.executable())
.filter(|p| p.is_file())
.filter(|l| l.present())
});
match &start.from {
Some(from) => self.game_from(from),
@ -2763,6 +2773,66 @@ impl App {
}
}
/// The page's side of the frame: the game on the screen as an entry of the browser's
/// history, the browser's question on leaving with unsaved work, the draft of an
/// unsaved game. Nothing of it on a computer.
fn page_frame(&mut self, ctx: &egui::Context) {
crate::platform::page::game_shown(ctx, self.game.is_some());
let modified = self.game.as_ref().is_some_and(|g| g.game.is_modified());
let reviewing = self.game.as_ref().is_some_and(|g| g.review_running());
crate::platform::page::warn_on_leave(modified || reviewing);
#[cfg(web)]
{
const EVERY: f64 = 5.0;
let now = ctx.input(|i| i.time);
match self.game.as_ref().filter(|g| g.game.is_modified()) {
Some(g) if self.draft_at.is_none_or(|t| now - t >= EVERY) => {
crate::my_games::write_draft(&crate::my_games::Draft {
title: g.title(),
moves: g.game.mainline().len().div_ceil(2),
pgn: g.game.to_pgn(),
});
self.draft_at = Some(now);
ctx.request_repaint_after(std::time::Duration::from_secs_f64(EVERY));
}
Some(_) => {}
// Saved, or left without saving: no draft of this visit is kept.
None if self.draft_at.take().is_some() => crate::my_games::delete_draft(),
None => {}
}
}
}
/// «There is an unsaved game» over the library, with Open and Delete.
#[cfg(web)]
fn draft_strip(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
let Some(d) = self.draft_offer.clone() else {
return;
};
let mut open = false;
let mut delete = false;
ui.horizontal(|ui| {
ui.label(
RichText::new(trf(
"There is an unsaved game: {title}, {n} moves.",
&[("title", &d.title), ("n", &d.moves)],
))
.color(ui.visuals().warn_fg_color),
);
open = ui.button(tr("Open")).clicked();
delete = ui.button(tr("Delete")).clicked();
});
ui.separator();
if open {
self.draft_offer = None;
self.open_pgn_text(ctx, d.pgn, false);
crate::my_games::delete_draft();
} else if delete {
self.draft_offer = None;
crate::my_games::delete_draft();
}
}
/// Files dropped on the window open as databases, like chosen ones; while files are
/// dragged over it, the window says so.
fn dropped_files(&mut self, ctx: &egui::Context) {
@ -3164,6 +3234,10 @@ impl eframe::App for App {
}
self.dropped_files(&ctx);
self.handle_async(&ctx);
// The browser's «Back» in a game: «← Library».
if crate::platform::page::take_back() && self.game.is_some() {
self.request_close(&ctx, CloseIntent::BackToLibrary);
}
// Dev hook (screenshots): the engine offer as on pressing L without an engine.
if std::env::var("CP_ENGINE_OFFER").is_ok() && !self.offer_hook_done {
self.offer_hook_done = true;
@ -3174,6 +3248,7 @@ impl eframe::App for App {
}
}
self.offer_events(&ctx);
self.page_frame(&ctx);
self.debug_step(&ctx);
self.debug_keys(&ctx);
self.debug_screenshot(&ctx);
@ -3458,6 +3533,8 @@ impl eframe::App for App {
self.library.online_busy = d.online.busy();
self.library.online_running = d.online.running();
}
#[cfg(web)]
self.draft_strip(ui, &ctx);
for a in self.library.show(ui, &dbs, &self.settings) {
match a {
LibraryAction::OpenGame { path, index, at } => {

View file

@ -101,17 +101,33 @@ pub fn clean_leftovers() {
}
}
/// The downloaded engine, if it is there (in a browser: the address of its worker).
pub fn installed() -> Option<PathBuf> {
/// The downloaded engine, if it is there.
pub fn installed() -> Option<crate::engines::EngineLocation> {
#[cfg(web)]
return crate::platform::web::engine::worker_script().map(PathBuf::from);
return crate::platform::web::engine::worker_script()
.map(crate::engines::EngineLocation::Worker);
#[cfg(not(web))]
{
let p = dir()?.join(EXE);
p.is_file().then_some(p)
p.is_file()
.then_some(crate::engines::EngineLocation::Program(p))
}
}
/// The size of the downloaded engine, in MB (0 when it is not there).
pub fn installed_mb() -> u64 {
#[cfg(web)]
return if crate::platform::web::engine::ready() {
crate::platform::web::engine::WASM_BYTES / 1_000_000
} else {
0
};
#[cfg(not(web))]
dir()
.and_then(|d| std::fs::metadata(d.join(EXE)).ok())
.map_or(0, |m| m.len() / 1_000_000)
}
/// Removes the downloaded engine (frees its space).
pub fn remove() -> std::io::Result<()> {
#[cfg(web)]
@ -188,10 +204,8 @@ impl Download {
match engine::download(|done, total| report(Stage::Downloading { done, total }), c)
.await
{
Ok(()) => match installed() {
Some(p) => Stage::Done(p),
None => Stage::Failed(Failure::Disk("not kept".into())),
},
// The engine's file: its worker's script.
Ok(()) => Stage::Done(PathBuf::from(engine::SCRIPT)),
Err(Fetch::Cancelled) => Stage::Cancelled,
Err(Fetch::Network(e)) => Stage::Failed(Failure::Network(e)),
Err(Fetch::Server(code)) => Stage::Failed(Failure::Server(code)),

View file

@ -27,9 +27,47 @@ pub fn bundled_stockfish() -> Option<PathBuf> {
candidates.into_iter().flatten().find(|p| is_executable(p))
}
/// Where an engine starts from: its program on a computer; in a browser, which runs no
/// programs, the address of its Web Worker's script.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EngineLocation {
#[cfg(not(web))]
Program(PathBuf),
#[cfg(web)]
Worker(String),
}
impl EngineLocation {
/// Whether the engine is there to start (its program's file; a worker always).
pub fn present(&self) -> bool {
match self {
#[cfg(not(web))]
EngineLocation::Program(p) => p.is_file(),
#[cfg(web)]
EngineLocation::Worker(_) => true,
}
}
}
impl std::fmt::Display for EngineLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
#[cfg(not(web))]
EngineLocation::Program(p) => write!(f, "{}", p.display()),
#[cfg(web)]
EngineLocation::Worker(script) => write!(f, "{script}"),
}
}
}
/// ChessPenguin's Stockfish: the bundled one, or else the downloaded one.
pub fn own_stockfish() -> Option<PathBuf> {
bundled_stockfish().or_else(crate::engine_download::installed)
pub fn own_stockfish() -> Option<EngineLocation> {
#[cfg(not(web))]
return bundled_stockfish()
.map(EngineLocation::Program)
.or_else(crate::engine_download::installed);
#[cfg(web)]
crate::engine_download::installed()
}
/// `stockfish` from `PATH` (for example, the distribution package). On macOS an app

View file

@ -233,6 +233,11 @@ impl GameView {
self.translation.suspend();
}
/// The whole-game analysis is running.
pub fn review_running(&self) -> bool {
self.review.running()
}
/// Copying the PGN always copies the original comments; say so when the translation is shown.
fn copy_pgn(&self) -> GameAction {
let note = if self.translation.shown().is_some() {
@ -2209,7 +2214,7 @@ impl GameView {
&mut self,
start: crate::play::Start,
(engine, file): (crate::play::Engine, std::path::PathBuf),
judge: Option<std::path::PathBuf>,
judge: Option<crate::engines::EngineLocation>,
record: Option<std::path::PathBuf>,
ctx: &egui::Context,
) {
@ -2319,7 +2324,7 @@ impl GameView {
saved: &crate::play::Saved,
to_move_left: Option<std::time::Duration>,
engine: (crate::play::Engine, std::path::PathBuf),
judge: Option<std::path::PathBuf>,
judge: Option<crate::engines::EngineLocation>,
journal: crate::player_games::Journal,
ctx: &egui::Context,
) {
@ -2362,7 +2367,7 @@ impl GameView {
&mut self,
start: crate::play::Start,
(engine, file): (crate::play::Engine, std::path::PathBuf),
judge: Option<std::path::PathBuf>,
judge: Option<crate::engines::EngineLocation>,
journal: Option<crate::player_games::Journal>,
clock: Option<crate::play::Clock>,
floor: NodeId,

View file

@ -217,6 +217,17 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String {
// Uzbek o‘ and g‘ are written with ‘ (U+2018): the interface font has no U+02BB.
const ROWS: &[[&str; 9]] = &[
// --- the web version ---
[
"There is an unsaved game: {title}, {n} moves.",
"Есть несохранённая партия: {title}, {n} ходов.",
"Il y a une partie non enregistrée : {title}, {n} coups.",
"Es gibt eine nicht gespeicherte Partie: {title}, {n} Züge.",
"Hay una partida sin guardar: {title}, {n} jugadas.",
"C'è una partita non salvata: {title}, {n} mosse.",
"Há uma partida não salva: {title}, {n} lances.",
"Saqlanmagan partiya bor: {title}, {n} yurish.",
"Сақталмаған партия бар: {title}, {n} жүріс.",
],
[
"📋 Keep a copy in the browser",
"📋 Оставить копию в браузере",

View file

@ -65,3 +65,34 @@ pub fn count() -> usize {
pub fn size() -> u64 {
crate::platform::fs::meta(&path()).map_or(0, |m| m.len)
}
/// A game left unsaved when the page was closed (docs/design/web-version.md §2.6): one,
/// the last, written every few seconds while it has changes. It guards against a
/// closed tab; it is not a save: offered at the next start, opened or deleted.
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Draft {
pub title: String,
pub moves: usize,
pub pgn: String,
}
fn draft_path() -> PathBuf {
crate::platform::data_dir()
.unwrap_or_default()
.join("draft.json")
}
pub fn write_draft(draft: &Draft) {
if let Ok(json) = serde_json::to_vec(draft) {
let _ = crate::platform::fs::write_atomic(&draft_path(), &json);
}
}
pub fn read_draft() -> Option<Draft> {
let bytes = crate::platform::fs::read(&draft_path()).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn delete_draft() {
let _ = crate::platform::fs::remove_file(&draft_path());
}

View file

@ -23,6 +23,7 @@ use web as imp;
pub mod clipboard;
pub mod files;
pub mod fs;
pub mod page;
pub mod pgn_store;
/// What the platform offers the interface: a feature it lacks is not shown.

View file

@ -0,0 +1,110 @@
//! The program as a page of a browser (docs/design/web-version.md §1.1, §1.3): a game
//! on the screen is an entry of the browser's history, so its «Back» means «← Library»;
//! unsaved work makes the browser ask before the page is left. A desktop program has
//! neither: nothing happens there.
#[cfg(web)]
mod imp {
use std::cell::Cell;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
thread_local! {
/// The history has our entry for the game on the screen.
static IN_GAME: Cell<bool> = const { Cell::new(false) };
/// «Back» was pressed (the entry left) and not taken yet.
static BACK: Cell<bool> = const { Cell::new(false) };
/// Our own `history.back()`: its `popstate` is not the user's.
static OWN_BACK: Cell<bool> = const { Cell::new(false) };
static LISTENING: Cell<bool> = const { Cell::new(false) };
static WARN: Cell<bool> = const { Cell::new(false) };
/// The page's `beforeunload`: the browser asks before the page is left.
static ASK: Closure<dyn FnMut(web_sys::BeforeUnloadEvent)> =
Closure::new(|e: web_sys::BeforeUnloadEvent| {
e.prevent_default();
e.set_return_value("");
});
}
fn listen(ctx: &egui::Context) {
if LISTENING.replace(true) {
return;
}
let ctx = ctx.clone();
let on_pop = Closure::<dyn FnMut()>::new(move || {
if OWN_BACK.replace(false) {
return;
}
if IN_GAME.replace(false) {
BACK.set(true);
ctx.request_repaint();
}
});
if let Some(w) = web_sys::window() {
let _ = w.add_event_listener_with_callback("popstate", on_pop.as_ref().unchecked_ref());
}
// Listens as long as the page lives.
on_pop.forget();
}
pub fn game_shown(ctx: &egui::Context, shown: bool) {
listen(ctx);
let Some(history) = web_sys::window().and_then(|w| w.history().ok()) else {
return;
};
if shown && !IN_GAME.get() {
let state = js_sys::Object::new();
let _ = js_sys::Reflect::set(&state, &"cpGame".into(), &JsValue::TRUE);
if history.push_state(&state, "").is_ok() {
IN_GAME.set(true);
}
} else if !shown && IN_GAME.get() {
// The game left by the program's own button: its entry goes too.
IN_GAME.set(false);
OWN_BACK.set(true);
let _ = history.back();
}
}
pub fn take_back() -> bool {
BACK.replace(false)
}
pub fn warn_on_leave(warn: bool) {
if WARN.replace(warn) == warn {
return;
}
let Some(w) = web_sys::window() else { return };
if warn {
ASK.with(|ask| w.set_onbeforeunload(Some(ask.as_ref().unchecked_ref())));
} else {
w.set_onbeforeunload(None);
}
}
}
/// The game is on the screen (`true`) or not: kept in step with the browser's history.
pub fn game_shown(ctx: &egui::Context, shown: bool) {
#[cfg(web)]
imp::game_shown(ctx, shown);
#[cfg(not(web))]
let _ = (ctx, shown);
}
/// The browser's «Back» left the game since the last call (then it is «← Library»).
pub fn take_back() -> bool {
#[cfg(web)]
return imp::take_back();
#[cfg(not(web))]
false
}
/// Whether leaving the page (closing the tab, reloading) should be asked about: the
/// browser asks in its own words.
pub fn warn_on_leave(warn: bool) {
#[cfg(web)]
imp::warn_on_leave(warn);
#[cfg(not(web))]
let _ = warn;
}

View file

@ -461,9 +461,10 @@ struct Request {
/// 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<Judge> {
pub fn start_judge(exe: crate::engines::EngineLocation, ctx: &egui::Context) -> Option<Judge> {
#[cfg(not(web))]
{
let crate::engines::EngineLocation::Program(exe) = exe;
let ctx = ctx.clone();
Some(Judge::start(
uci::EngineConfig::new(exe),

View file

@ -1971,7 +1971,7 @@ impl PrepScreen {
let processes = job_settings.processes;
let spawned = review::spawn_job(
"prep-engine",
path.clone(),
path,
job_settings,
targets,
cancel.clone(),

View file

@ -95,7 +95,7 @@ pub fn processes() -> usize {
/// through `tx`, each waking `ctx`.
pub fn spawn_job(
name: &str,
path: PathBuf,
engine: crate::engines::EngineLocation,
settings: JobSettings,
targets: Vec<game_review::Target>,
cancel: Arc<AtomicBool>,
@ -104,6 +104,7 @@ pub fn spawn_job(
) -> std::io::Result<JobRunner> {
#[cfg(not(web))]
{
let crate::engines::EngineLocation::Program(path) = engine;
std::thread::Builder::new()
.name(name.to_owned())
.spawn(move || {
@ -125,8 +126,9 @@ pub fn spawn_job(
#[cfg(web)]
{
let _ = name;
let crate::engines::EngineLocation::Worker(script) = engine;
let wake: Arc<dyn Fn() + Send + Sync> = Arc::new(move || ctx.request_repaint());
game_review::Dispatcher::start(&path.to_string_lossy(), &settings, targets, wake)
game_review::Dispatcher::start(&script, &settings, targets, wake)
.map(|dispatcher| JobRunner {
dispatcher,
tx,
@ -229,7 +231,13 @@ impl Review {
/// Starts the engine job with the engine at `path` (ChessPenguin's Stockfish). `full`
/// discards earlier results; otherwise only positions without an evaluation are
/// analysed (all of them for a stale analysis). Returns false if there is nothing to do.
pub fn start(&mut self, game: &Game, path: &Path, full: bool, ctx: &egui::Context) -> bool {
pub fn start(
&mut self,
game: &Game,
engine: &crate::engines::EngineLocation,
full: bool,
ctx: &egui::Context,
) -> bool {
self.job = None;
self.error = None;
let targets = self.analysis.begin(game, full);
@ -242,7 +250,7 @@ impl Review {
let settings = JobSettings::new(processes(), None);
let spawned = spawn_job(
"game-review",
path.to_owned(),
engine.clone(),
settings,
targets,
cancel.clone(),

View file

@ -53,22 +53,22 @@ impl EngineConfig {
/// Executable to start; `None` if ChessPenguin's Stockfish is neither bundled nor
/// downloaded yet (it is offered for download then).
pub fn executable(&self) -> Option<PathBuf> {
pub fn executable(&self) -> Option<crate::engines::EngineLocation> {
if self.builtin {
crate::engines::own_stockfish()
} else {
Some(self.path.clone())
// A browser runs no engine programs: there are none but its own.
#[cfg(not(web))]
return Some(crate::engines::EngineLocation::Program(self.path.clone()));
#[cfg(web)]
None
}
}
/// Whether the engine can be started: ChessPenguin's Stockfish is there (in a
/// browser: downloaded into it), or the file of another engine.
pub fn present(&self) -> bool {
if self.builtin {
crate::engines::own_stockfish().is_some()
} else {
self.path.is_file()
}
self.executable().is_some_and(|l| l.present())
}
}

View file

@ -298,7 +298,7 @@ impl SettingsWindow {
)
.on_hover_text(p.display().to_string());
} else if let Some(p) = crate::engine_download::installed() {
let mb = std::fs::metadata(&p).map_or(0, |m| m.len() / 1_000_000);
let mb = crate::engine_download::installed_mb();
ui.label(
RichText::new(trf(
"Downloaded by ChessPenguin · {mb} MB",
@ -307,7 +307,7 @@ impl SettingsWindow {
.small()
.weak(),
)
.on_hover_text(p.display().to_string());
.on_hover_text(p.to_string());
} else {
ui.horizontal(|ui| {
ui.label(
@ -333,9 +333,7 @@ impl SettingsWindow {
let mut answer = None;
let modal = egui::Modal::new(egui::Id::new("remove_engine")).show(ui.ctx(), |ui| {
ui.set_width(360.0);
let mb = crate::engine_download::installed()
.and_then(|p| std::fs::metadata(p).ok())
.map_or(0, |m| m.len() / 1_000_000);
let mb = crate::engine_download::installed_mb();
ui.label(trf(
"Remove Stockfish 19? This frees {mb} MB. You can download it again at any time.",
&[("mb", &mb)],
@ -383,9 +381,8 @@ impl SettingsWindow {
ui.label(RichText::new(tr("Found on this computer:")).strong());
for cfg in found {
ui.horizontal(|ui| {
let path = cfg.executable().unwrap_or_default();
ui.label(&cfg.name)
.on_hover_text(path.display().to_string());
let path = cfg.executable().map(|l| l.to_string()).unwrap_or_default();
ui.label(&cfg.name).on_hover_text(path);
if ui.button(tr("Add")).clicked() {
s.engines.push(cfg);
if s.active_engine.is_none() {