Web version, stage 1: the interface as a library over a platform layer; apps/web

apps/desktop becomes a library (chesspenguin_app: the interface) and a thin
binary; apps/web starts the same interface in a page's canvas (eframe's
WebRunner). cfg(web) (build.rs) marks WebAssembly in a browser.

The platform layer (apps/desktop/src/platform): the program's folders, files,
background work, the files the user opens or saves, the clipboard and what
the platform offers (CAPS). On a computer it is the system as before; in a
browser the program's data lives in IndexedDB behind an in-memory file tree
loaded before the start, the files the user opens are read into it for the
session (only read), background jobs run on the page's thread after the
frame, the clipboard is read through the browser's API, sounds play through
audio elements, a game is saved as a download.

What a browser does not have is not built for it: updates, the online games
window and its probe, engine processes (analysis starts a Web Worker there;
the review and preparation jobs, Rodent and the judge are native), blocking
requests (engine, Maia and Rodent downloads report no download for the
platform, translation reports that it makes no requests). The desktop
program behaves as before; its build finds unused code (the web build
compiles parts it never shows).

apps/web: the entry point, the page /app/ (device check before anything large
is loaded: phones and tablets get the page about the apps in the site's nine
languages, keys app_* in website/site/i18n), build.sh (wasm-bindgen, profile
web), a static server and headless Firefox checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 15:09:17 +03:00
parent a4445d2c15
commit 3e69a5d57c
61 changed files with 2628 additions and 552 deletions

View file

@ -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"

View file

@ -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");

View file

@ -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<Result<EngineHandle, uci::EngineError>>),
/// 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<Result<EngineHandle, uci::EngineError>> {
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<EngineHandle>,
spawning: Option<Receiver<Result<EngineHandle, uci::EngineError>>>,
spawning: Option<Launch>,
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<Launch, String> {
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<Launch, String> {
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();

View file

@ -215,19 +215,17 @@ pub struct App {
play_next: Option<PlayNext>,
tx: Sender<Async>,
rx: Receiver<Async>,
/// «Paste PGN»: the clipboard being read.
pasting: Option<crate::platform::clipboard::Reading>,
confirm_close: Option<CloseIntent>,
/// Close the game once the pending "save as" succeeds.
close_after_save: Option<CloseIntent>,
/// 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<GameView>,
/// 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<PathBuf>,
/// 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<PathBuf> = 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=<game index>` opens a game from the first database, `CP_PLY=<n>` 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<PathBuf> = 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);
}

View file

@ -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<T> {
cancel: Arc<AtomicBool>,
progress: Arc<AtomicUsize>,
@ -902,14 +902,12 @@ impl<T: Send + 'static> Background<T> {
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,

View file

@ -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<SignIn, String> {
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<SignIn, String> {
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<Value, (u16, String)> {
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<String, Failure> {
let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner());
@ -398,6 +415,7 @@ fn access_token() -> Result<String, Failure> {
refresh(&t)
}
#[cfg(not(web))]
fn refresh(t: &Tokens) -> Result<String, Failure> {
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<Vec<String>, Failure> {
Err(crate::translate::no_requests())
}
#[cfg(web)]
pub fn respond(
_model: &str,
_system: &str,
_user: &str,
_cancel: &AtomicBool,
) -> Result<String, Failure> {
Err(crate::translate::no_requests())
}
#[cfg(not(web))]
/// The models this account may use (`visibility: list`).
pub fn models() -> Result<Vec<String>, 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<String, Failure> {
let mut text = String::new();

View file

@ -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);

View file

@ -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<PathBuf, Failure> {
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<PathBuf, Failure>
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<PathBuf, Failure> {
let exe = dir.join(EXE);
let wanted = |name: &str| -> Option<PathBuf> {
@ -382,6 +403,7 @@ fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result<PathBuf, Failure> {
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);

View file

@ -30,6 +30,7 @@ pub enum OfferEvent {
/// Use the Stockfish found on this computer, then run `Pending`.
UseSystem(PathBuf, Option<Pending>),
/// 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<OfferEvent>) {
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;

View file

@ -35,6 +35,7 @@ pub fn own_stockfish() -> Option<PathBuf> {
/// `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<PathBuf> {
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<PathBuf> {
.find(|p| is_executable(p))
}
/// A browser has no programs of the system to find.
#[cfg(web)]
pub fn system_stockfish() -> Option<PathBuf> {
None
}
fn is_executable(p: &Path) -> bool {
let Ok(meta) = std::fs::metadata(p) else {
return false;

View file

@ -24,8 +24,7 @@ const SAMPLES: [(&str, &str); 2] = [
];
fn dir() -> Option<PathBuf> {
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)]

View file

@ -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<State> {
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<State> {
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));

View file

@ -80,13 +80,15 @@ pub struct GameView {
play_start: Option<crate::play::Start>,
/// «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<crate::train::Training>,
/// A line from the clipboard that would go elsewhere than the user stands: asked.
paste_pending: Option<chess_core::paste::PastePlan>,
/// Text to paste on the next frame (dev hook `CP_PASTE_LINE`).
paste_request: Option<String>,
/// The menu's «Paste a line»: the clipboard being read.
clipboard: Option<crate::platform::clipboard::Reading>,
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<GameAction>) {
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

View file

@ -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<Option<(String, std::time::Instant, u32)>>,
last: std::sync::Mutex<Option<(String, web_time::Instant, u32)>>,
/// `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)

View file

@ -61,29 +61,31 @@ impl Lang {
pub fn from_locales<S: AsRef<str>>(locales: impl IntoIterator<Item = S>) -> 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<Lang> {
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",

View file

@ -1846,6 +1846,7 @@ impl LargeView {
.on_disabled_hover_text(&online.hint)
.clicked()
{
#[cfg(not(web))]
actions.push(LibraryAction::UpdateOnline(path.to_path_buf()));
}
}

158
apps/desktop/src/lib.rs Normal file
View file

@ -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<String>,
) -> 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 <database> [report.txt]]`.
#[cfg(not(web))]
pub fn run_native() -> eframe::Result {
// `chesspenguin --bench <database> [report.txt]`: timings instead of the window
// (`docs/dev/import.md`, "Замер на другой машине").
let args: Vec<std::ffi::OsString> = 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 <database> [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
}

View file

@ -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);
}
});

View file

@ -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<PathBuf, String> {
let dir = dir().ok_or("no data directory")?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;

View file

@ -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 <database> [report.txt]`: timings instead of the window
// (`docs/dev/import.md`, "Замер на другой машине").
let args: Vec<std::ffi::OsString> = 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 <database> [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()
}

View file

@ -1,14 +1,15 @@
//! Games from Lichess and Chess.com on the desktop: the databases live in
//! `<local data dir>/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<std::sync::mpsc::Receiver<[bool; 2]>>,
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<std::time::Instant>,
last: Option<web_time::Instant>,
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 {

View file

@ -37,7 +37,7 @@ struct Job {
work: Background<Result<Done, Failure>>,
/// 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<std::time::Instant>,
stopped: Option<web_time::Instant>,
/// 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(

View file

@ -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<Mutex<Option<Option<String>>>>,
}
impl Reading {
/// The text once read (`Some(None)`: empty, refused or unavailable).
pub fn poll(&self) -> Option<Option<String>> {
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 }
}

View file

@ -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<PathBuf>) + 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::<Vec<_>>()
.join(",");
super::web::page::pick_files(&accept, move |files| {
then(
files
.into_iter()
.map(|(name, bytes)| super::web::vfs::add_opened(&name, bytes))
.collect(),
);
});
}
}
/// The files dropped on the window in this frame, as databases to open: `then` gets
/// their paths once read (in a browser they are kept for the session like chosen
/// ones). The desktop program does not take dropped files: nothing comes there.
pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Vec<PathBuf>) + Send + 'static) {
#[cfg(not(web))]
{
let _ = (ctx, then);
}
#[cfg(web)]
{
let files: Vec<web_sys::File> = 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:?}"))
}

View file

@ -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<Vec<u8>> {
#[cfg(not(web))]
{
std::fs::read(path)
}
#[cfg(web)]
{
super::web::vfs::read(path)
}
}
pub fn read_to_string(path: &Path) -> io::Result<String> {
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<Vec<u8>> {
#[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<Meta> {
#[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)
}
}

View file

@ -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<PathBuf> {
imp::config_dir()
}
/// The program's data kept for good (`~/.local/share/chesspenguin`).
pub fn data_dir() -> Option<PathBuf> {
imp::data_dir()
}
/// Data the program can make again (`~/.cache/chesspenguin`).
pub fn cache_dir() -> Option<PathBuf> {
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<PathBuf> {
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<chess_import::Opened, chess_import::ImportError> {
imp::open_database(path, progress, cancel)
}

View file

@ -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> {
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
}
pub fn config_dir() -> Option<PathBuf> {
project().map(|d| d.config_dir().to_path_buf())
}
pub fn data_dir() -> Option<PathBuf> {
project().map(|d| d.data_dir().to_path_buf())
}
pub fn cache_dir() -> Option<PathBuf> {
project().map(|d| d.cache_dir().to_path_buf())
}
pub fn examples_dir() -> Option<PathBuf> {
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<Opened, ImportError> {
chess_import::open(path, progress, cancel)
}

View file

@ -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<JsValue, JsValue> {
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::<web_sys::IdbRequest>().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<web_sys::IdbDatabase, JsValue> {
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::<web_sys::IdbOpenDbRequest>().ok())
.and_then(|r| r.result().ok())
.and_then(|r| r.dyn_into::<web_sys::IdbDatabase>().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<Option<web_sys::IdbDatabase>> =
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<u8>)> {
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::<js_sys::Uint8Array>().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<web_sys::IdbObjectStore> {
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<u8>) {
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:?}");
}
}

View file

@ -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<PathBuf> {
Some(PathBuf::from(vfs::CONFIG))
}
pub fn data_dir() -> Option<PathBuf> {
Some(PathBuf::from(vfs::DATA))
}
pub fn cache_dir() -> Option<PathBuf> {
Some(PathBuf::from(vfs::CACHE))
}
pub fn examples_dir() -> Option<PathBuf> {
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<Opened, ImportError> {
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)
}

View file

@ -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::Document> {
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<dyn FnOnce(Vec<(String, Vec<u8>)>)>;
thread_local! {
/// What to do with the files chosen next.
static ON_PICKED: RefCell<Option<Picked>> = const { RefCell::new(None) };
}
/// The page's file input, made once: hidden, several files, `accept` the extensions.
fn open_input(accept: &str) -> Result<web_sys::HtmlInputElement, JsValue> {
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::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
let Some(input) = ev
.target()
.and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
else {
return;
};
let files: Vec<web_sys::File> = 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<web_sys::File>) -> Vec<(String, Vec<u8>)> {
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<u8>)>) + '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(())
}

View file

@ -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<u8>,
modified_ms: u64,
readonly: bool,
}
thread_local! {
static FILES: RefCell<BTreeMap<PathBuf, Entry>> = const { RefCell::new(BTreeMap::new()) };
/// The number of the last file opened (each gets a folder of its own).
static OPENED_COUNT: RefCell<u32> = 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<Vec<u8>> {
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<Meta> {
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<u8>) -> 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<u8>) -> 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
}

View file

@ -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<Judge> {
#[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<Mutex<Option<String>>>,
},
/// 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<String> {
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,
}),
}
}

View file

@ -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<JobMsg>,
@ -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;

View file

@ -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<game_review::Target>,
cancel: Arc<AtomicBool>,
tx: std::sync::mpsc::Sender<JobMsg>,
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<JobMsg>,
cancel: Arc<AtomicBool>,
@ -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)

View file

@ -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<PathBuf, Failure> {
let (tag, bin) = binary().ok_or(Failure::Unsupported)?;
let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?;

View file

@ -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<PathBuf, Failure> {
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<PathBuf, Failure>
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<PathBuf, Failure> {
@ -152,6 +163,7 @@ fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result<PathBuf, Failure> {
/// 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);

View file

@ -222,14 +222,12 @@ impl Default for Settings {
impl Settings {
pub fn config_dir() -> Option<PathBuf> {
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<PathBuf> {
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
.map(|d| d.cache_dir().to_path_buf())
crate::platform::cache_dir()
}
fn file() -> Option<PathBuf> {
@ -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)]

View file

@ -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<SettingsAction>, 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<String>,
available: &Option<String>,
actions: &mut Vec<SettingsAction>,
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();
}

View file

@ -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<Sender<(SoundSet, Sound, f32)>>,
}
#[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<std::collections::HashMap<usize, String>>,
}
#[cfg(web)]
impl SoundPlayer {
pub fn new() -> Self {
Self {
urls: Default::default(),
}
}
fn url(&self, bytes: &'static [u8]) -> Option<String> {
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();
}
}
}

View file

@ -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<Vec<String>, 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<String, Failure> {
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<Vec<String>, 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<Vec<Str
Ok(ids)
}
#[cfg(not(web))]
fn net_failure(e: ureq::Error, local: bool) -> 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 {

View file

@ -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,

View file

@ -12,13 +12,12 @@ pub struct Viewed {
impl Viewed {
fn file() -> Option<PathBuf> {
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::<Vec<u64>>(&b).ok())
.unwrap_or_default();
Viewed {