Merge feature/online-games: games from Lichess and Chess.com (0.8.0)
Some checks failed
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run
Release / version (push) Has been cancelled
Release / linux (push) Has been cancelled
Release / flatpak (push) Has been cancelled
Release / windows (push) Has been cancelled
Release / macos (push) Has been cancelled
Release / publish (push) Has been cancelled

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-20 08:50:18 +03:00
commit 98183f9ffe
16 changed files with 2532 additions and 22 deletions

View file

@ -2,6 +2,19 @@
All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/).
## [0.8.0] — 2026-10-20
- Games from Lichess and Chess.com: anyone's games by nickname — yours, a pupil's, an
opponent's, a champion's (no login; another nickname for Chess.com if it differs). See what
was found, download the games into a database — both sites merged into one by default, or
one per site — and later fetch the new ones with "⟳ New games" in the database header. The
progress shows per site with the time left; the window may be closed meanwhile (the result
then shows as a message). An interrupted download — stopped, failed, or the program closed —
keeps what it got and continues where it stopped, without duplicates (also after a crash);
games still being played (correspondence) are fetched once they end. Only standard chess is
kept. The feature is offered only when the sites answer: ChessPenguin asks each for a public
profile at start (nothing of yours is sent), so offline it stays hidden.
## [0.7.1] — 2026-10-20
- Updates: at start ChessPenguin asks GitHub for the latest version (can be turned off in

8
Cargo.lock generated
View file

@ -661,7 +661,7 @@ dependencies = [
[[package]]
name = "chess-core"
version = "0.7.1"
version = "0.8.0"
dependencies = [
"encoding_rs",
"pgn-reader",
@ -671,7 +671,7 @@ dependencies = [
[[package]]
name = "chess-import"
version = "0.7.1"
version = "0.8.0"
dependencies = [
"chess-core",
"encoding_rs",
@ -684,7 +684,7 @@ dependencies = [
[[package]]
name = "chesspenguin"
version = "0.7.1"
version = "0.8.0"
dependencies = [
"arboard",
"chess-core",
@ -4284,7 +4284,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uci"
version = "0.7.1"
version = "0.8.0"
dependencies = [
"thiserror 2.0.21",
]

View file

@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/chess-core", "crates/chess-import", "crates/uci", "apps/desktop"]
[workspace.package]
version = "0.7.1"
version = "0.8.0"
edition = "2024"
rust-version = "1.97"
license = "GPL-3.0-or-later"

View file

@ -39,6 +39,7 @@
copy PGN/FEN, save a game to a new file.
- **Looks** — 17 piece sets, 37 boards (flat colours and textures), 7 sound sets,
dark and light themes.
- **Online games** — download anyone's games from Lichess and Chess.com by nickname (yours, a pupil's, an opponent's; no login) into a database, both sites merged or one per site, and fetch the new ones with one click.
- **Languages** — English, Русский, Français, Deutsch, Español, Italiano.
| Game analysis: graph and report | Engine marks and better lines |

View file

@ -26,6 +26,7 @@
- **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор,
копирование PGN/FEN, сохранение партии в новый файл.
- **Оформление** — 17 наборов фигур, 37 досок (цвета и текстуры), 7 наборов звуков, тёмная и светлая тема.
- **Ваши онлайн-партии** — загрузка своих партий с Lichess и Chess.com по нику (без входа) в базу и обновление одной кнопкой.
- **Языки** — English, Русский, Français, Deutsch, Español, Italiano.
| Анализ партии: график и отчёт | Отметки движка и лучшие варианты |

View file

@ -52,6 +52,9 @@ pub struct App {
/// 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,
online: crate::online_ui::OnlineDialog,
/// A position to find in a database once the game is closed.
find_after_close: Option<(PathBuf, shakmaty::Chess, Vec<shakmaty::Move>, bool)>,
/// Games left for one opened from the reference tab ("⬅ Back to …"), kept as they
@ -175,6 +178,8 @@ impl App {
reference: Default::default(),
engine_offer: crate::engine_offer::EngineOffer::new(),
offer_hook_done: false,
online_probe: crate::online::Probe::start(ctx),
online: crate::online_ui::OnlineDialog::from_env(),
allow_quit: false,
applied_dark: None,
debug: DebugStartup::from_env(),
@ -884,6 +889,10 @@ impl eframe::App for App {
}
} else {
let dbs = self.settings.databases.clone();
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();
for a in self.library.show(ui, &dbs, &self.settings) {
match a {
LibraryAction::OpenGame { path, index, at } => {
@ -900,6 +909,8 @@ impl eframe::App for App {
}
LibraryAction::PastePgn => self.paste_pgn(&ctx),
LibraryAction::AddDatabases => self.pick_databases(&ctx),
LibraryAction::OnlineGames => self.online.open_with(&self.settings),
LibraryAction::UpdateOnline(p) => self.online.update(&p, &ctx),
LibraryAction::OpenUpdate => self.update_ui.open = true,
LibraryAction::RemoveDatabase(p) => {
self.settings.databases.retain(|d| *d != p);
@ -911,6 +922,30 @@ impl eframe::App for App {
}
}
let (events, changed) = self
.online
.show(&ctx, &self.online_probe, &mut self.settings);
self.settings_dirty |= changed;
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();
@ -1026,6 +1061,13 @@ impl eframe::App for App {
fn on_exit(&mut self) {
self.analysis.stop();
// 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() {
if crate::online::State::load(&p).is_some_and(|s| s.games > 0) {
self.settings.touch_database(&p);
}
}
let _ = self.settings.save();
}
}

View file

@ -2079,6 +2079,71 @@ const ROWS: &[[&str; 6]] = &[
"Partidas de la base solo con los jugadores y el resultado, sin jugadas",
"Partite della base con solo giocatori e risultato, senza mosse",
],
[
"A different nickname on Chess.com",
"На Chess.com другой ник",
"Un autre pseudo sur Chess.com",
"Anderer Nickname auf Chess.com",
"Otro apodo en Chess.com",
"Un altro nickname su Chess.com",
],
[
"Fetch the games played since the last download",
"Загрузить партии, сыгранные после прошлой загрузки",
"Récupérer les parties jouées depuis le dernier téléchargement",
"Die seit dem letzten Download gespielten Partien holen",
"Descargar las partidas jugadas desde la última descarga",
"Scarica le partite giocate dall'ultimo download",
],
["Find", "Найти", "Rechercher", "Suchen", "Buscar", "Cerca"],
[
"Letters, digits, _ and -, 2 to 30 characters",
"Латиница, цифры, _ и -, от 2 до 30 символов",
"Lettres, chiffres, _ et -, de 2 à 30 caractères",
"Buchstaben, Ziffern, _ und -, 2 bis 30 Zeichen",
"Letras, dígitos, _ y -, de 2 a 30 caracteres",
"Lettere, cifre, _ e -, da 2 a 30 caratteri",
],
[
"Nickname on Chess.com",
"Ник на Chess.com",
"Pseudo sur Chess.com",
"Nickname auf Chess.com",
"Apodo en Chess.com",
"Nickname su Chess.com",
],
[
"Stop",
"Остановить",
"Arrêter",
"Anhalten",
"Detener",
"Ferma",
],
[
"The same nickname",
"Тот же ник",
"Le même pseudo",
"Derselbe Nickname",
"El mismo apodo",
"Lo stesso nickname",
],
[
"as on the site",
"как на сайте",
"comme sur le site",
"wie auf der Seite",
"como en el sitio",
"come sul sito",
],
[
"updating…",
"обновляется…",
"mise à jour…",
"wird aktualisiert…",
"actualizando…",
"aggiornamento…",
],
[
"Checking…",
"Проверяю…",
@ -2735,6 +2800,278 @@ const ROWS: &[[&str; 6]] = &[
"Tienes la {old}",
"Hai la {old}",
],
[
"Otherwise each site gets a database of its own",
"Иначе у каждого сайта будет своя база",
"Sinon chaque site a sa propre base",
"Sonst bekommt jede Seite eine eigene Datenbank",
"Si no, cada sitio tendrá su propia base",
"Altrimenti ogni sito avrà la sua base",
],
[
"Download any player's games by nickname into a database: yours, a pupil's, an opponent's",
"Скачать партии любого игрока по нику в базу: свои, ученика, соперника",
"Télécharger les parties de n'importe quel joueur par pseudo dans une base : les vôtres, celles d'un élève, d'un adversaire",
"Partien beliebiger Spieler per Nickname in eine Datenbank laden: eigene, eines Schülers, eines Gegners",
"Descargar las partidas de cualquier jugador por apodo a una base: las tuyas, de un alumno, de un rival",
"Scarica le partite di qualsiasi giocatore per nickname in una base: le tue, di un allievo, di un avversario",
],
[
"Online games",
"Онлайн-партии",
"Parties en ligne",
"Online-Partien",
"Partidas en línea",
"Partite online",
],
[
"No connection to Lichess and Chess.com",
"Нет связи с Lichess и Chess.com",
"Pas de connexion à Lichess et Chess.com",
"Keine Verbindung zu Lichess und Chess.com",
"Sin conexión con Lichess y Chess.com",
"Nessuna connessione a Lichess e Chess.com",
],
[
"⟳ New games",
"⟳ Новые партии",
"⟳ Nouvelles parties",
"⟳ Neue Partien",
"⟳ Partidas nuevas",
"⟳ Nuove partite",
],
[
"downloading… {n}",
"скачивается… {n}",
"téléchargement… {n}",
"wird geladen… {n}",
"descargando… {n}",
"download… {n}",
],
[
"Fetch the games played since the last download ({when})",
"Скачать партии, сыгранные после прошлой загрузки ({when})",
"Récupérer les parties jouées depuis le dernier téléchargement ({when})",
"Die seit dem letzten Download gespielten Partien holen ({when})",
"Descargar las partidas jugadas desde la última descarga ({when})",
"Scarica le partite giocate dall'ultimo download ({when})",
],
[
"{n} min ago",
"{n} мин назад",
"il y a {n} min",
"vor {n} Min.",
"hace {n} min",
"{n} min fa",
],
[
"{n} h ago",
"{n} ч назад",
"il y a {n} h",
"vor {n} Std.",
"hace {n} h",
"{n} h fa",
],
[
"{n} d ago",
"{n} дн. назад",
"il y a {n} j",
"vor {n} T.",
"hace {n} d",
"{n} g fa",
],
[
"Could not write the database: no permission to write or the disk is full.",
"Не удалось записать базу: нет прав на запись или диск заполнен.",
"Impossible d'écrire la base : pas de droit d'écriture ou disque plein.",
"Die Datenbank konnte nicht geschrieben werden: keine Schreibrechte oder die Festplatte ist voll.",
"No se pudo escribir la base: sin permiso de escritura o el disco está lleno.",
"Impossibile scrivere la base: nessun permesso di scrittura o disco pieno.",
],
[
"This database is being downloaded already.",
"Эта база уже скачивается.",
"Cette base est déjà en cours de téléchargement.",
"Diese Datenbank wird bereits geladen.",
"Esta base ya se está descargando.",
"Questa base è già in download.",
],
[
"Games from Lichess and Chess.com",
"Партии с Lichess и Chess.com",
"Parties de Lichess et Chess.com",
"Partien von Lichess und Chess.com",
"Partidas de Lichess y Chess.com",
"Partite da Lichess e Chess.com",
],
[
"Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.",
"Партии любого игрока — свои, ученика, соперника — станут здесь базой для поиска и анализа. Нужен только ник, входить в аккаунт не нужно.",
"Les parties de n'importe quel joueur — les vôtres, celles d'un élève, d'un adversaire — deviennent ici une base pour chercher et analyser. Seul le pseudo est nécessaire, sans connexion.",
"Die Partien beliebiger Spieler — eigene, eines Schülers, eines Gegners — werden hier zu einer Datenbank zum Suchen und Analysieren. Nur der Nickname ist nötig, keine Anmeldung.",
"Las partidas de cualquier jugador — las tuyas, de un alumno, de un rival — se convierten aquí en una base para buscar y analizar. Solo hace falta el apodo, sin iniciar sesión.",
"Le partite di qualsiasi giocatore — le tue, di un allievo, di un avversario — diventano qui una base da cercare e analizzare. Serve solo il nickname, nessun accesso.",
],
[
"Player's nickname",
"Ник игрока",
"Pseudo du joueur",
"Nickname des Spielers",
"Apodo del jugador",
"Nickname del giocatore",
],
[
"Merge the games of both sites into one database",
"Объединить партии с обоих сайтов в одну базу",
"Réunir les parties des deux sites dans une seule base",
"Partien beider Seiten in einer Datenbank zusammenführen",
"Unir las partidas de ambos sitios en una sola base",
"Unire le partite di entrambi i siti in una sola base",
],
[
"What is downloaded is kept; downloading again continues from there",
"Скачанное сохранится; следующая загрузка продолжит с этого места",
"Ce qui est téléchargé est conservé ; le prochain téléchargement reprend à partir de là",
"Bereits Geladenes bleibt; der nächste Download setzt dort fort",
"Lo descargado se conserva; la próxima descarga continúa desde ahí",
"Il già scaricato resta; il prossimo download riprende da lì",
],
[
"You can close the window: the download goes on, and what is downloaded is kept.",
"Окно можно закрыть: загрузка продолжится, скачанное не пропадёт.",
"Vous pouvez fermer la fenêtre : le téléchargement continue et ce qui est téléchargé est conservé.",
"Das Fenster kann geschlossen werden: der Download läuft weiter, Geladenes bleibt erhalten.",
"Puedes cerrar la ventana: la descarga continúa y lo descargado se conserva.",
"Puoi chiudere la finestra: il download continua e il già scaricato resta.",
],
[
"Open the database",
"Открыть базу",
"Ouvrir la base",
"Datenbank öffnen",
"Abrir la base",
"Apri la base",
],
[
"{p} does not answer. Check the internet connection and try again.",
"{p} не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.",
"{p} ne répond pas. Vérifiez la connexion Internet et réessayez.",
"{p} antwortet nicht. Prüfen Sie die Internetverbindung und versuchen Sie es erneut.",
"{p} no responde. Comprueba la conexión a internet e inténtalo de nuevo.",
"{p} non risponde. Controlla la connessione a internet e riprova.",
],
[
"{p} asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.",
"{p} просит сделать паузу: слишком много запросов подряд. Подождите минуту и попробуйте снова — скачанное сохранится.",
"{p} demande une pause : trop de requêtes d'affilée. Attendez une minute et réessayez ; ce qui est téléchargé est conservé.",
"{p} bittet um eine Pause: zu viele Anfragen hintereinander. Warten Sie eine Minute und versuchen Sie es erneut; Geladenes bleibt erhalten.",
"{p} pide una pausa: demasiadas solicitudes seguidas. Espera un minuto e inténtalo de nuevo; lo descargado se conserva.",
"{p} chiede una pausa: troppe richieste di fila. Aspetta un minuto e riprova; il già scaricato resta.",
],
[
"{p} answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.",
"{p} ответил непонятно — возможно, сайт что-то поменял. Попробуйте позже или обновите ChessPenguin.",
"{p} a répondu d'une façon que ChessPenguin ne comprend pas : le site a peut-être changé. Réessayez plus tard ou mettez ChessPenguin à jour.",
"{p} hat unverständlich geantwortet: die Seite hat sich vielleicht geändert. Versuchen Sie es später oder aktualisieren Sie ChessPenguin.",
"{p} respondió de una forma que ChessPenguin no entiende: quizá el sitio cambió. Inténtalo más tarde o actualiza ChessPenguin.",
"{p} ha risposto in un modo che ChessPenguin non capisce: forse il sito è cambiato. Riprova più tardi o aggiorna ChessPenguin.",
],
[
"“{name}”: stopped, {total} in the database",
"«{name}»: остановлено, в базе {total}",
"« {name} » : arrêté, {total} dans la base",
"„{name}“: angehalten, {total} in der Datenbank",
"«{name}»: detenido, {total} en la base",
"«{name}»: fermato, {total} nella base",
],
[
"“{name}”: no new games",
"«{name}»: новых партий нет",
"« {name} » : pas de nouvelles parties",
"„{name}“: keine neuen Partien",
"«{name}»: no hay partidas nuevas",
"«{name}»: nessuna partita nuova",
],
[
"“{name}”: +{added}, {total} in all",
"«{name}»: +{added}, всего {total}",
"« {name} » : +{added}, {total} en tout",
"„{name}“: +{added}, insgesamt {total}",
"«{name}»: +{added}, {total} en total",
"«{name}»: +{added}, {total} in tutto",
],
[
"“{name}”: {e}",
"«{name}»: {e}",
"« {name} » : {e}",
"„{name}“: {e}",
"«{name}»: {e}",
"«{name}»: {e}",
],
[
"{p}: {name} — {games}, about {m} min the first time",
"{p}: {name} — {games}, первый раз около {m} мин",
"{p} : {name} — {games}, environ {m} min la première fois",
"{p}: {name} — {games}, beim ersten Mal etwa {m} Min.",
"{p}: {name} — {games}, la primera vez unos {m} min",
"{p}: {name} — {games}, la prima volta circa {m} min",
],
[
"{p}: {name} — {games}",
"{p}: {name} — {games}",
"{p} : {name} — {games}",
"{p}: {name} — {games}",
"{p}: {name} — {games}",
"{p}: {name} — {games}",
],
[
"{p}: {name} — months with games: {m}",
"{p}: {name} — месяцев с партиями: {m}",
"{p} : {name} — mois avec des parties : {m}",
"{p}: {name} — Monate mit Partien: {m}",
"{p}: {name} — meses con partidas: {m}",
"{p}: {name} — mesi con partite: {m}",
],
[
"✖ {p}: no player with this nickname — check the spelling",
"✖ {p}: игрока с таким ником нет — проверьте написание",
"✖ {p} : aucun joueur avec ce pseudo — vérifiez l'orthographe",
"✖ {p}: kein Spieler mit diesem Nickname — prüfen Sie die Schreibweise",
"✖ {p}: no hay ningún jugador con este apodo — revisa cómo se escribe",
"✖ {p}: nessun giocatore con questo nickname — controlla come si scrive",
],
[
"Into “{name}” (already {n} there; only new games are added)",
"В базу «{name}» (там уже {n}; добавятся только новые)",
"Dans « {name} » (déjà {n} ; seules les nouvelles parties sont ajoutées)",
"In „{name}“ (schon {n} dort; nur neue Partien kommen dazu)",
"En «{name}» (ya hay {n}; solo se añaden las nuevas)",
"In «{name}» (già {n}; si aggiungono solo le nuove)",
],
[
"Into the new database “{name}”",
"В новую базу «{name}»",
"Dans la nouvelle base « {name} »",
"In die neue Datenbank „{name}“",
"En la nueva base «{name}»",
"Nella nuova base «{name}»",
],
[
"Lichess: {n} of about {t} · about {m} min left",
"Lichess: {n} из примерно {t} · осталось около {m} мин",
"Lichess : {n} sur environ {t} · encore environ {m} min",
"Lichess: {n} von etwa {t} · noch etwa {m} Min.",
"Lichess: {n} de unas {t} · quedan unos {m} min",
"Lichess: {n} di circa {t} · mancano circa {m} min",
],
[
"Chess.com: month {i} of {n} · {games}",
"Chess.com: месяц {i} из {n} · {games}",
"Chess.com : mois {i} sur {n} · {games}",
"Chess.com: Monat {i} von {n} · {games}",
"Chess.com: mes {i} de {n} · {games}",
"Chess.com: mese {i} di {n} · {games}",
],
[
"Checking engine…",
"Проверка движка…",
@ -3999,6 +4336,8 @@ mod tests {
include_str!("settings_ui.rs"),
include_str!("widgets.rs"),
include_str!("reference.rs"),
include_str!("online.rs"),
include_str!("online_ui.rs"),
include_str!("update.rs"),
include_str!("update_ui.rs"),
include_str!("report.rs"),

View file

@ -58,6 +58,10 @@ pub enum LibraryAction {
NewGame,
PastePgn,
AddDatabases,
/// The window for downloading games from Lichess and Chess.com.
OnlineGames,
/// Fetch the new games of an online database.
UpdateOnline(PathBuf),
/// The window offering a newer version.
OpenUpdate,
RemoveDatabase(PathBuf),
@ -199,6 +203,12 @@ pub struct Library {
view: Vec<usize>,
view_key: Option<(PathBuf, String, SortKey, bool)>,
scroll_to_selected: bool,
/// Lichess or Chess.com answered at start (the online games are offered).
pub online: bool,
/// Online databases being downloaded or updated.
pub online_busy: Vec<PathBuf>,
/// Games downloaded so far while downloads run (shown on the shelf card).
pub online_running: Option<usize>,
/// A newer version to offer (its number), next to Settings.
pub update: Option<String>,
/// File sizes of databases (`file_size`).
@ -222,6 +232,9 @@ impl Library {
view: Vec::new(),
view_key: None,
scroll_to_selected: false,
online: false,
online_busy: Vec::new(),
online_running: None,
sizes: HashMap::new(),
update: None,
}
@ -296,6 +309,18 @@ impl Library {
}
}
/// Reads a database again (its file changed), keeping it selected if it was.
pub fn reload(&mut self, path: &Path, ctx: &egui::Context) {
let selected = self.selected_db.as_deref() == Some(path);
self.forget(path);
self.small.remove(path);
if selected {
self.select_db(path, ctx);
} else {
self.load(path, ctx);
}
}
pub fn forget(&mut self, path: &Path) {
self.info.remove(path);
self.large.remove(path);
@ -593,6 +618,14 @@ impl Library {
{
actions.push(LibraryAction::AddDatabases);
}
if self.online
&& ui
.button("🌐")
.on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's"))
.clicked()
{
actions.push(LibraryAction::OnlineGames);
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("⚙ Settings")).clicked() {
actions.push(LibraryAction::OpenSettings);
@ -666,6 +699,36 @@ impl Library {
{
actions.push(LibraryAction::AddDatabases);
}
if self.online {
let (rect, resp) = ui.allocate_exact_size(vec2(150.0, 64.0), Sense::click());
let visuals = ui.style().interact(&resp);
ui.painter()
.rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside);
let below = match self.online_running {
Some(n) => trf("downloading… {n}", &[("n", &crate::i18n::games(n))]),
None => "Lichess · Chess.com".to_owned(),
};
ui.painter().text(
rect.center() + vec2(0.0, -9.0),
egui::Align2::CENTER_CENTER,
format!("🌐 {}", tr("Online games")),
egui::FontId::proportional(15.0),
visuals.text_color(),
);
ui.painter().text(
rect.center() + vec2(0.0, 11.0),
egui::Align2::CENTER_CENTER,
below,
egui::FontId::proportional(13.0),
ui.visuals().weak_text_color(),
);
if resp
.on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's"))
.clicked()
{
actions.push(LibraryAction::OnlineGames);
}
}
});
ui.add_space(8.0);
}
@ -717,7 +780,11 @@ impl Library {
ui.painter().text(
rect.left_top() + vec2(12.0, 10.0),
egui::Align2::LEFT_TOP,
"🗄",
if crate::online::is_online(path) {
"🌐"
} else {
"🗄"
},
egui::FontId::proportional(22.0),
text_color,
);
@ -878,6 +945,34 @@ impl Library {
if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() {
self.notes_open = Some(path.clone());
}
if crate::online::is_online(&path) {
if self.online_busy.contains(&path) {
ui.add(egui::Spinner::new().size(14.0));
ui.label(RichText::new(tr("updating…")).weak());
} else {
let when = crate::online::State::load(&path)
.and_then(|s| s.updated)
.map(crate::online::ago);
let hint = if !self.online {
tr("No connection to Lichess and Chess.com").to_owned()
} else if let Some(w) = when {
trf(
"Fetch the games played since the last download ({when})",
&[("when", &w)],
)
} else {
tr("Fetch the games played since the last download").to_owned()
};
if ui
.add_enabled(self.online, egui::Button::new(tr("⟳ New games")).small())
.on_hover_text(&hint)
.on_disabled_hover_text(&hint)
.clicked()
{
actions.push(LibraryAction::UpdateOnline(path.clone()));
}
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let small = self
.small

View file

@ -15,6 +15,8 @@ mod i18n;
mod large_db;
mod library;
mod notation;
mod online;
mod online_ui;
mod reference;
mod report;
mod review;

1321
apps/desktop/src/online.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,683 @@
//! The window "Games from Lichess and Chess.com": a player's nickname (anyone's: the
//! user's own, a pupil's, an opponent's; another one for Chess.com if it differs), the
//! platforms to look on, what was found, then the downloads with their progress. Only the
//! platforms that answered the probe at start are offered (`online::Probe`).
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use egui::{RichText, Ui};
use crate::board_search::Background;
use crate::i18n::{games, tr, trf};
use crate::online::{self, Account, Done, Failure, Lookup, Platform, Probe};
use crate::settings::Settings;
/// What the window asks of the application.
pub enum OnlineEvent {
/// A database was downloaded (or partly, then cancelled): put it on the shelf.
Added(PathBuf),
/// A database got new games: reload it.
Updated(PathBuf),
/// Show this database (and the window closes).
Open(PathBuf),
/// A download finished while the window was closed: say how it went.
Message(String),
}
struct Job {
/// One account, or several downloaded into one database.
accounts: Vec<Account>,
path: PathBuf,
/// Updating a database already on the shelf (not a first download).
update: bool,
/// The database is new (so the totals of the accounts are what is left to fetch).
fresh: bool,
status: Arc<online::Progress>,
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>,
}
/// A finished download.
struct Outcome {
accounts: Vec<Account>,
path: PathBuf,
update: bool,
/// The platform that failed (`None`: the disk, or not known).
platform: Option<Platform>,
result: Result<Done, Failure>,
}
#[derive(Default)]
pub struct OnlineDialog {
pub open: bool,
nick: String,
/// A different nickname on Chess.com, when asked for.
other: Option<String>,
pick: [bool; 2],
lookup: Option<Background<Vec<(Platform, Lookup)>>>,
found: Vec<(Platform, Lookup)>,
/// The nicknames `found` answers.
found_for: (String, String),
jobs: Vec<Job>,
results: Vec<Outcome>,
/// Two accounts found: download them into separate databases (one by default).
separate: bool,
/// Dev hook (screenshots): look the nickname up once the probe answered, and
/// download what was found.
auto_find: bool,
auto_download: bool,
}
/// Where the found accounts go: all into one database (`together`) or each into its
/// own. A database already holding the accounts is kept (also when one site does not
/// answer this time: its partner's games still go where they went before).
fn targets(start: &[Account], together: bool) -> Vec<(Vec<Account>, PathBuf)> {
let groups: Vec<Vec<Account>> = if together {
vec![start.to_vec()]
} else {
start.iter().map(|a| vec![a.clone()]).collect()
};
// Only one account found: any database holding it (the merged one first).
let any = start.len() == 1;
groups
.into_iter()
.filter_map(|g| {
let existing = online::holding(&g[0]).into_iter().find(|p| {
online::State::load(p).is_some_and(|s| {
let mine = s.accounts();
any || (mine.len() == g.len()
&& g.iter().all(|a| mine.iter().any(|m| m.same(a))))
})
});
let path = existing.or_else(|| online::combined_path(&g))?;
Some((g, path))
})
.collect()
}
/// The file name of a database without the extension.
fn db_name(path: &Path) -> String {
path.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default()
}
/// What went wrong, in words for a chess player (the technical text goes under
/// "Details").
fn failure_text(platform: Option<Platform>, e: &Failure) -> String {
let p = platform.map_or("—", Platform::name);
match e {
Failure::Network(_) => trf(
"{p} does not answer. Check the internet connection and try again.",
&[("p", &p)],
),
Failure::RateLimited => trf(
"{p} asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.",
&[("p", &p)],
),
Failure::Unexpected(_) => trf(
"{p} answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.",
&[("p", &p)],
),
Failure::Disk(_) => {
tr("Could not write the database: no permission to write or the disk is full.")
.to_owned()
}
Failure::Busy => tr("This database is being downloaded already.").to_owned(),
}
}
/// "“Name”: +12 games, 6 600 in all" and the like.
fn outcome_text(o: &Outcome) -> String {
let name = db_name(&o.path);
match &o.result {
Ok(d) if d.cancelled => trf(
"“{name}”: stopped, {total} in the database",
&[("name", &name), ("total", &games(d.total as usize))],
),
Ok(d) if d.added == 0 => trf("“{name}”: no new games", &[("name", &name)]),
Ok(d) => trf(
"“{name}”: +{added}, {total} in all",
&[
("name", &name),
("added", &games(d.added as usize)),
("total", &games(d.total as usize)),
],
),
Err(e) => trf(
"“{name}”: {e}",
&[("name", &name), ("e", &failure_text(o.platform, e))],
),
}
}
impl OnlineDialog {
/// Opens the window with the nicknames used last time.
pub fn open_with(&mut self, settings: &Settings) {
if !self.open && self.jobs.is_empty() && self.lookup.is_none() {
self.nick = settings.online_nick.clone();
self.other = settings.online_nick_chesscom.clone();
self.pick = [true, true];
self.found.clear();
}
self.open = true;
}
/// Dev hook: `CP_ONLINE=<nick>` opens the window and looks the nickname up,
/// `CP_ONLINE_DOWNLOAD=1` then downloads (screenshots, manual checks).
pub fn from_env() -> OnlineDialog {
let mut d = OnlineDialog::default();
if let Ok(nick) = std::env::var("CP_ONLINE") {
d.open = true;
d.nick = nick;
d.pick = [true, true];
d.auto_find = true;
d.auto_download = std::env::var("CP_ONLINE_DOWNLOAD").is_ok();
}
d
}
/// Databases being downloaded or updated.
pub fn busy(&self) -> Vec<PathBuf> {
self.jobs.iter().map(|j| j.path.clone()).collect()
}
/// The games downloaded so far by the running jobs (for the shelf card), if any run.
pub fn running(&self) -> Option<usize> {
(!self.jobs.is_empty()).then(|| self.jobs.iter().map(|j| j.work.progress()).sum())
}
/// Stops the downloads and waits a little for them to save what they fetched (on
/// quitting: the next update then continues without duplicates). Returns the new
/// databases among them, to put on the shelf with what they got so far.
pub fn stop_all(&mut self) -> Vec<PathBuf> {
let new = self
.jobs
.iter()
.filter(|j| !j.update)
.map(|j| j.path.clone())
.collect();
for j in &self.jobs {
j.work.cancel();
}
let start = std::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));
}
new
}
/// Fetches the new games of an online database on the shelf.
pub fn update(&mut self, path: &Path, ctx: &egui::Context) {
let Some(state) = online::State::load(path) else {
return;
};
self.start(state.accounts(), path.to_owned(), true, ctx);
}
fn start(&mut self, accounts: Vec<Account>, path: PathBuf, update: bool, ctx: &egui::Context) {
if self.jobs.iter().any(|j| j.path == path) {
return;
}
let fresh = online::State::load(&path).is_none();
let now = ctx.input(|i| i.time);
let a = accounts.clone();
let status = Arc::new(online::Progress::default());
let (s, p) = (status.clone(), path.clone());
if let Some(work) = Background::spawn(ctx, now, move |progress, cancel| {
Some(online::download(&a, &p, progress, cancel, &s))
}) {
self.results.retain(|o| o.path != path);
self.jobs.push(Job {
accounts,
path,
update,
fresh,
status,
work,
stopped: None,
});
}
}
fn nick_for(&self, p: Platform) -> String {
match (p, &self.other) {
(Platform::ChessCom, Some(o)) => o.trim().to_owned(),
_ => self.nick.trim().to_owned(),
}
}
/// Collects finished work; the window itself when open.
pub fn show(
&mut self,
ctx: &egui::Context,
probe: &Probe,
settings: &mut Settings,
) -> (Vec<OnlineEvent>, bool) {
let mut events = Vec::new();
let mut changed = false;
if let Some(l) = &self.lookup
&& let Some(r) = l.poll()
{
self.found = r.unwrap_or_default();
self.lookup = None;
}
let mut i = 0;
while i < self.jobs.len() {
if let Some(r) = self.jobs[i].work.poll() {
let job = self.jobs.remove(i);
let result = r.unwrap_or(Err(Failure::Network("stopped".into())));
// What a failed download got before the failure is kept: a new
// database goes on the shelf with it, an updated one is reloaded.
let total = match &result {
Ok(d) => d.total,
Err(_) => online::State::load(&job.path).map_or(0, |s| s.games),
};
if job.update {
if result.as_ref().map_or(true, |d| d.added > 0) {
events.push(OnlineEvent::Updated(job.path.clone()));
}
} else if total > 0 {
events.push(OnlineEvent::Added(job.path.clone()));
}
let platform = match &result {
Err(Failure::Disk(_)) | Ok(_) => None,
Err(_) => job
.accounts
.get(job.status.account.load(Ordering::Relaxed))
.map(|a| a.platform),
};
let outcome = Outcome {
accounts: job.accounts,
path: job.path,
update: job.update,
platform,
result,
};
if !self.open {
events.push(OnlineEvent::Message(outcome_text(&outcome)));
}
self.results.push(outcome);
} else if self.jobs[i]
.stopped
.is_some_and(|t| t.elapsed() > std::time::Duration::from_secs(10))
{
self.jobs.remove(i);
} else {
i += 1;
}
}
if !self.jobs.is_empty() || self.lookup.is_some() {
ctx.request_repaint_after(std::time::Duration::from_millis(250));
}
if !self.open {
return (events, changed);
}
let mut open = true;
egui::Window::new(tr("Games from Lichess and Chess.com"))
.open(&mut open)
.default_width(540.0)
.collapsible(false)
.pivot(egui::Align2::CENTER_TOP)
.default_pos(ctx.content_rect().center_top() + egui::vec2(0.0, 120.0))
.show(ctx, |ui| {
changed |= self.body(ui, probe, settings, &mut events);
});
if !open || events.iter().any(|e| matches!(e, OnlineEvent::Open(_))) {
self.open = false;
}
(events, changed)
}
fn body(
&mut self,
ui: &mut Ui,
probe: &Probe,
settings: &mut Settings,
events: &mut Vec<OnlineEvent>,
) -> bool {
let mut changed = false;
ui.label(
RichText::new(tr(
"Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.",
))
.weak(),
);
ui.add_space(6.0);
let both = probe.has(Platform::Lichess) && probe.has(Platform::ChessCom);
let mut enter = false;
ui.horizontal(|ui| {
ui.label(tr("Player's nickname"));
let r = ui.add(
egui::TextEdit::singleline(&mut self.nick)
.hint_text(tr("as on the site"))
.desired_width(220.0),
);
if r.changed() {
self.found.clear();
}
enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
});
ui.horizontal(|ui| {
for p in Platform::ALL {
if probe.has(p) {
let i = p as usize;
if ui.checkbox(&mut self.pick[i], p.name()).changed() {
self.found.clear();
}
}
}
});
if both && self.pick[1] {
let mut clear = false;
let mut same = false;
match &mut self.other {
Some(o) => {
ui.horizontal(|ui| {
ui.label(tr("Nickname on Chess.com"));
let r = ui.add(egui::TextEdit::singleline(o).desired_width(180.0));
clear |= r.changed();
enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
same = ui
.small_button("✕")
.on_hover_text(tr("The same nickname"))
.clicked();
});
}
None => {
if ui.link(tr("A different nickname on Chess.com")).clicked() {
self.other = Some(self.nick.clone());
clear = true;
}
}
}
if same {
self.other = None;
clear = true;
}
if clear {
self.found.clear();
}
}
let wanted: Vec<Platform> = Platform::ALL
.into_iter()
.filter(|p| probe.has(*p) && self.pick[*p as usize])
.collect();
let nicks = (
self.nick_for(Platform::Lichess),
self.nick_for(Platform::ChessCom),
);
let valid = wanted
.iter()
.all(|p| online::valid_nick(&self.nick_for(*p)));
ui.add_space(4.0);
ui.horizontal(|ui| {
let searching = self.lookup.is_some();
let auto = self.auto_find && probe.any();
if auto {
self.auto_find = false;
}
let can = !wanted.is_empty() && valid && !searching;
if ui.add_enabled(can, egui::Button::new(tr("Find"))).clicked()
|| ((auto || enter) && can)
{
let list: Vec<(Platform, String)> =
wanted.iter().map(|p| (*p, self.nick_for(*p))).collect();
self.found_for = nicks.clone();
let now = ui.input(|i| i.time);
self.lookup = Background::spawn(ui.ctx(), now, move |_, _| {
Some(
list.into_iter()
.map(|(p, n)| (p, online::lookup(p, &n)))
.collect(),
)
});
settings.online_nick = self.nick.trim().to_owned();
settings.online_nick_chesscom = self.other.as_ref().map(|o| o.trim().to_owned());
changed = true;
}
if searching {
ui.add(egui::Spinner::new());
} else if !self.nick.trim().is_empty() && !valid {
ui.label(
RichText::new(tr("Letters, digits, _ and -, 2 to 30 characters"))
.color(ui.visuals().warn_fg_color),
);
}
});
if self.found_for == nicks && !self.found.is_empty() {
self.found_ui(ui);
}
self.jobs_ui(ui);
self.results_ui(ui, events);
changed
}
/// What was found, the choice of one database or separate ones, and Download.
fn found_ui(&mut self, ui: &mut Ui) {
ui.add_space(4.0);
let start: Vec<Account> = self
.found
.iter()
.filter_map(|(_, l)| match l {
Lookup::Found(a)
if !self
.jobs
.iter()
.any(|j| j.accounts.iter().any(|x| x.same(a))) =>
{
Some(a.clone())
}
_ => None,
})
.collect();
// Accounts some database already holds (then the "first time" estimate is wrong).
let held = |a: &Account| !online::holding(a).is_empty();
for (p, l) in &self.found {
match l {
Lookup::Found(a) => {
let what = match (a.games, a.months) {
(Some(g), _) if !held(a) => {
let secs = g / online::LICHESS_RATE;
trf(
"{p}: {name} — {games}, about {m} min the first time",
&[
("p", &p.name()),
("name", &a.username),
("games", &games(g as usize)),
("m", &secs.div_ceil(60).max(1)),
],
)
}
(Some(g), _) => trf(
"{p}: {name} — {games}",
&[
("p", &p.name()),
("name", &a.username),
("games", &games(g as usize)),
],
),
(_, Some(m)) => trf(
"{p}: {name} — months with games: {m}",
&[("p", &p.name()), ("name", &a.username), ("m", &m)],
),
_ => format!("{}: {}", p.name(), a.username),
};
ui.label(format!("✔ {what}"));
}
Lookup::NotFound => {
ui.label(
RichText::new(trf(
"✖ {p}: no player with this nickname — check the spelling",
&[("p", &p.name())],
))
.weak(),
);
}
Lookup::Failed(e) => {
ui.label(
RichText::new(format!("✖ {}", failure_text(Some(*p), e)))
.color(ui.visuals().warn_fg_color),
);
}
}
}
if start.is_empty() {
return;
}
// Both platforms: one database by default (the player's games together).
let together = start.len() > 1 && !self.separate;
if start.len() > 1 {
let mut one = !self.separate;
if ui
.checkbox(
&mut one,
tr("Merge the games of both sites into one database"),
)
.on_hover_text(tr("Otherwise each site gets a database of its own"))
.changed()
{
self.separate = !one;
}
}
// Where the games go, and what is there already.
let targets = targets(&start, together);
for (_, path) in &targets {
let text = match online::State::load(path) {
Some(s) => trf(
"Into “{name}” (already {n} there; only new games are added)",
&[("name", &db_name(path)), ("n", &games(s.games as usize))],
),
None => trf(
"Into the new database “{name}”",
&[("name", &db_name(path))],
),
};
ui.label(RichText::new(text).weak());
}
ui.add_space(4.0);
let auto = std::mem::take(&mut self.auto_download);
if crate::widgets::primary(ui, tr("⬇ Download")).clicked() || auto {
// From the window the database goes (back) on the shelf, also when it was
// downloaded before and only gets the new games now.
for (t, path) in targets {
self.start(t, path, false, ui.ctx());
}
}
}
/// The running downloads: the database, the site and how far it got, Stop.
fn jobs_ui(&mut self, ui: &mut Ui) {
if self.jobs.is_empty() {
return;
}
ui.separator();
let mut stop = None;
for (k, j) in self.jobs.iter().enumerate() {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new().size(14.0));
ui.label(RichText::new(db_name(&j.path)).strong());
if ui
.small_button(tr("Stop"))
.on_hover_text(tr(
"What is downloaded is kept; downloading again continues from there",
))
.clicked()
{
stop = Some(k);
}
});
let s = &j.status;
let Some(a) = j.accounts.get(s.account.load(Ordering::Relaxed)) else {
continue;
};
let n = s.games.load(Ordering::Relaxed) as u64;
match (a.platform, a.games) {
(Platform::Lichess, Some(total)) if j.fresh && total > 0 => {
let left = total.saturating_sub(n) / online::LICHESS_RATE;
ui.label(trf(
"Lichess: {n} of about {t} · about {m} min left",
&[
("n", &crate::large_db::grouped(n as usize)),
("t", &crate::large_db::grouped(total as usize)),
("m", &left.div_ceil(60).max(1)),
],
));
ui.add(egui::ProgressBar::new((n as f32 / total as f32).min(1.0)));
}
(Platform::ChessCom, _) if s.months_total.load(Ordering::Relaxed) > 0 => {
let (done, all) = (
s.months_done.load(Ordering::Relaxed),
s.months_total.load(Ordering::Relaxed),
);
ui.label(trf(
"Chess.com: month {i} of {n} · {games}",
&[("i", &done), ("n", &all), ("games", &games(n as usize))],
));
ui.add(egui::ProgressBar::new(done as f32 / all as f32));
}
(p, _) => {
ui.label(format!("{}: {}", p.name(), games(n as usize)));
}
}
}
if let Some(k) = stop {
self.jobs[k].work.cancel();
self.jobs[k]
.stopped
.get_or_insert_with(std::time::Instant::now);
}
ui.label(
RichText::new(tr(
"You can close the window: the download goes on, and what is downloaded is kept.",
))
.weak(),
);
}
/// The finished downloads: how they went, Open the database / Try again.
fn results_ui(&mut self, ui: &mut Ui, events: &mut Vec<OnlineEvent>) {
if self.results.is_empty() {
return;
}
ui.separator();
let mut retry = None;
for (k, o) in self.results.iter().enumerate() {
match &o.result {
Ok(d) => {
ui.horizontal_wrapped(|ui| {
ui.label(format!("✔ {}", outcome_text(o)));
if d.total > 0 && ui.button(tr("Open the database")).clicked() {
events.push(OnlineEvent::Open(o.path.clone()));
}
});
}
Err(e) => {
ui.label(
RichText::new(format!("⚠ {}", outcome_text(o)))
.color(ui.visuals().warn_fg_color),
);
ui.horizontal(|ui| {
if ui.button(tr("Try again")).clicked() {
retry = Some(k);
}
egui::CollapsingHeader::new(tr("Details"))
.id_salt(("online-details", k))
.show(ui, |ui| {
ui.label(RichText::new(e.to_string()).small().weak());
});
});
}
}
}
if let Some(k) = retry {
let o = self.results.remove(k);
self.start(o.accounts, o.path, o.update, ui.ctx());
}
}
}

View file

@ -84,6 +84,10 @@ pub struct Settings {
pub engines_discovered: bool,
/// The sample databases were put on the shelf (see `examples::first_run_setup`).
pub examples_added: bool,
/// The nickname last looked up on Lichess / Chess.com, and a different one for
/// Chess.com.
pub online_nick: String,
pub online_nick_chesscom: Option<String>,
/// Ask GitHub for a newer release at start (Settings → About).
pub check_updates: bool,
/// A version the user chose to skip (its button is not shown).
@ -145,6 +149,8 @@ impl Default for Settings {
review: ReviewSettings::default(),
engines_discovered: false,
examples_added: false,
online_nick: String::new(),
online_nick_chesscom: None,
check_updates: true,
skipped_version: None,
last_version: None,

View file

@ -209,7 +209,7 @@ impl UpdateDialog {
ui.label(tr("It starts after a restart. Unsaved games are asked about first; databases and settings stay as they are."));
ui.add_space(6.0);
ui.horizontal(|ui| {
if primary(ui, tr("⟳ Restart now")).clicked() {
if crate::widgets::primary(ui, tr("⟳ Restart now")).clicked() {
events.push(UpdateEvent::Restart(exe.clone()));
}
if ui.button(tr("Later")).clicked() {
@ -226,7 +226,7 @@ impl UpdateDialog {
ui.label(tr("2. In the window of the disk image, drag the ChessPenguin icon onto the Applications folder and choose Replace."));
ui.label(tr("3. Start ChessPenguin from Applications."));
ui.add_space(6.0);
if primary(ui, tr("Quit ChessPenguin")).clicked() {
if crate::widgets::primary(ui, tr("Quit ChessPenguin")).clicked() {
events.push(UpdateEvent::Quit);
}
return;
@ -296,7 +296,7 @@ impl UpdateDialog {
));
ui.add_space(6.0);
ui.horizontal(|ui| {
if primary(ui, action(retry, tr("⬆ Update"))).clicked() {
if crate::widgets::primary(ui, action(retry, tr("⬆ Update"))).clicked() {
self.start(release, k, ui.ctx());
}
self.not_now(ui, release, events);
@ -309,7 +309,7 @@ impl UpdateDialog {
));
ui.add_space(6.0);
ui.horizontal(|ui| {
if primary(ui, action(retry, tr("⬇ Download"))).clicked() {
if crate::widgets::primary(ui, action(retry, tr("⬇ Download"))).clicked() {
self.start(release, kind, ui.ctx());
}
self.not_now(ui, release, events);
@ -322,7 +322,7 @@ impl UpdateDialog {
));
ui.add_space(6.0);
ui.horizontal(|ui| {
if primary(ui, action(retry, tr("⬇ Download"))).clicked() {
if crate::widgets::primary(ui, action(retry, tr("⬇ Download"))).clicked() {
self.start(release, k, ui.ctx());
}
self.not_now(ui, release, events);
@ -385,15 +385,6 @@ fn heading(ui: &mut Ui, release: &Release) {
ui.add_space(6.0);
}
/// The main button of the window: filled, a little taller.
fn primary(ui: &mut Ui, label: &str) -> egui::Response {
ui.add(
egui::Button::new(RichText::new(label).strong())
.fill(ui.visuals().selection.bg_fill)
.min_size(egui::vec2(0.0, 30.0)),
)
}
/// A command in a monospace box with a Copy button beside it.
fn command_line(ui: &mut Ui, command: &str, events: &mut Vec<UpdateEvent>) {
ui.horizontal(|ui| {
@ -406,7 +397,7 @@ fn command_line(ui: &mut Ui, command: &str, events: &mut Vec<UpdateEvent>) {
ui.set_max_width(width);
ui.add(egui::Label::new(RichText::new(command).monospace()).wrap());
});
if primary(ui, tr("Copy")).clicked() {
if crate::widgets::primary(ui, tr("Copy")).clicked() {
events.push(UpdateEvent::CopyText(command.to_owned()));
}
});

View file

@ -39,3 +39,12 @@ pub fn update_button(ui: &mut egui::Ui, label: &str) -> egui::Response {
ui.button(egui::RichText::new(label).color(ui.visuals().hyperlink_color))
.on_hover_text(crate::i18n::tr("A new version of ChessPenguin is out"))
}
/// The main button of a window: filled, a little taller.
pub fn primary(ui: &mut egui::Ui, label: &str) -> egui::Response {
ui.add(
egui::Button::new(egui::RichText::new(label).strong())
.fill(ui.visuals().selection.bg_fill)
.min_size(egui::vec2(0.0, 30.0)),
)
}

View file

@ -11,6 +11,8 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i
| `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху»; при открытой доске в фоне строится, чего не хватает для быстрого поиска (`Base::prepare`: свой ускоритель без пригодного `.cbb`, дебютный индекс при достаточной памяти; каталог кэша `boosters/`) со строкой прогресса над доской |
| `update.rs` | Обновления: проверка последнего выпуска (GitHub API, при старте, отключается в «О программе»), вид установки (`detect`: zip на Windows, `.app` на macOS, AppImage — только если исполняемый файл внутри `$APPDIR`, архив tar.gz по соседним файлам, `/usr/bin` → pacman/dpkg/rpm, Flatpak по `FLATPAK_ID`, иначе «другое»), выбор файла выпуска по окончанию имени, загрузка с проверкой SHA-256 из `SHA256SUMS.txt`, замена исполняемого файла (`replace_file`: копия рядом и одно переименование; на Windows работающий `.exe` переименовывается в `.old`, удаляется при следующем запуске), команды для пакетов (`cd <папка> && sudo apt/dnf/zypper/pacman … ./файл`, все слова в одинарных кавычках, если в них есть что-то кроме безопасных символов), папка «Загрузки» (XDG, затем `~/.config/user-dirs.dirs` пользователя — у Flatpak своя папка настроек, затем `~/Downloads`, затем домашняя). Тесты: версии, файлы для каждого вида, команды и экранирование (через `sh`), замена работающего исполняемого файла (CI на Windows и macOS тоже), обновление архива из локального «выпуска» |
| `update_ui.rs` | Окно «Обновление ChessPenguin»: «Вышла версия X · У вас Y · Что нового», один сценарий на вид установки с главной кнопкой, «Не сейчас», «Пропустить эту версию» (`skipped_version`); скачивание с прогрессом (окно можно закрыть, кнопка у «Настроек» показывает проценты); итог: «Перезапустить сейчас / Позже», шаги для macOS с «Закрыть ChessPenguin», команда с «Копировать», «Открыть папку» и шагами для пакетов; ошибки понятными словами, исходный текст — в «Подробностях». Перезапуск: `request_close(QuitApp)`, в `finish_close` настройки сохраняются, новый процесс запускается без переменных `CP_*`; отмена вопроса о партиях отменяет и перезапуск |
| `online.rs` | Онлайн-партии: проба обоих API при старте (повтор через 5 минут), поиск ника, загрузка в PGN-базу в `<data>/online/` с файлом состояния `.online.json` (аккаунты базы, отметки Lichess `since`/незаконченные партии и Chess.com месяц/время, число партий, длина файла и его последние байты — хвост после аварии обрезается), одна загрузка на файл (`Claim`), имена `Ник (Lichess + Chess.com).pgn` или `A (Lichess) + B (Chess.com).pgn`. Живой тест `online_live` (ник — только через `CP_ONLINE_NICK`). |
| `online_ui.rs` | Окно «Партии с Lichess и Chess.com»: ник игрока (любого: свой, ученика, соперника; другой ник для Chess.com), площадки, ответившие на пробу, «Найти» (Enter), найденное, «Объединить партии с обоих сайтов в одну базу» (по умолчанию), строка «В базу …» (`targets`: база, где эти аккаунты уже есть, иначе новая), «Скачать», прогресс по сайту (Lichess: из N, оставшееся время; Chess.com: месяц i из n), «Остановить», итоги с «Открыть базу» / «Попробовать снова» и «Подробностями»; при закрытом окне итог — тостом; `stop_all` при выходе. |
| `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой |
| `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура |
| `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках |
@ -44,7 +46,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe
```
`CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии,
`CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN).
`CP_ONLINE=<ник>` — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. `CP_ONLINE=<ник>` — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу загрузить). Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN).
## Языки

View file

@ -43,6 +43,11 @@
<category>BoardGame</category>
</categories>
<releases>
<release version="0.8.0" date="2026-10-20">
<description>
<p>Games from Lichess and Chess.com: download anyone's games by nickname — yours, a pupil's, an opponent's — into a database, both sites merged or one per site, and fetch the new ones with one click. Interrupted downloads continue without duplicates.</p>
</description>
</release>
<release version="0.7.1" date="2026-10-20">
<description>
<p>Updates: ChessPenguin tells when a new version is out and updates itself where it can (Windows, AppImage, the Linux archive); for packages it downloads the new one and shows the command that installs it.</p>