Online games: anyone's games, one download per database, crash-safe resume, unfinished Lichess games, friendly errors, progress per site

- the window and the shelf speak of any player's games (yours, a pupil's, an opponent's)
- a database is claimed by one download at a time; updates write into the database itself
- merged databases of different nicknames get names of their own
- the state remembers the file length and its last bytes: what a crash appended is cut off
- a deleted database is downloaded again; a partial download goes on the shelf
- Lichess games still being played are fetched once they end (correspondence)
- downloads stop and save on quitting; results show as a toast when the window is closed
- New games button with the time of the last download, disabled offline; 🌐 on online databases

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-20 08:30:31 +03:00
parent 79a1a43423
commit e0c99074e2
7 changed files with 1179 additions and 461 deletions

View file

@ -892,6 +892,7 @@ impl eframe::App for App {
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 } => {
@ -937,6 +938,12 @@ impl eframe::App for App {
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.
@ -1054,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,14 +2079,6 @@ 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",
],
[
"(already here: {n})",
"(уже есть: {n})",
"(déjà ici : {n})",
"(schon vorhanden: {n})",
"(ya aquí: {n})",
"(già presenti: {n})",
],
[
"A different nickname on Chess.com",
"На Chess.com другой ник",
@ -2095,14 +2087,6 @@ const ROWS: &[[&str; 6]] = &[
"Otro apodo en Chess.com",
"Un altro nickname su Chess.com",
],
[
"Download your online games by nickname into a database",
"Загрузить свои онлайн-партии по нику в базу",
"Télécharger vos parties en ligne par pseudo dans une base",
"Ihre Online-Partien per Nickname in eine Datenbank laden",
"Descargar tus partidas en línea por apodo a una base",
"Scarica le tue partite online per nickname in una base",
],
[
"Fetch the games played since the last download",
"Загрузить партии, сыгранные после прошлой загрузки",
@ -2112,14 +2096,6 @@ const ROWS: &[[&str; 6]] = &[
"Scarica le partite giocate dall'ultimo download",
],
["Find", "Найти", "Rechercher", "Suchen", "Buscar", "Cerca"],
[
"Games from",
"Партии с",
"Parties de",
"Partien von",
"Partidas de",
"Partite da",
],
[
"Letters, digits, _ and -, 2 to 30 characters",
"Латиница, цифры, _ и -, от 2 до 30 символов",
@ -2128,7 +2104,6 @@ const ROWS: &[[&str; 6]] = &[
"Letras, dígitos, _ y -, de 2 a 30 caracteres",
"Lettere, cifre, _ e -, da 2 a 30 caratteri",
],
["Nickname", "Ник", "Pseudo", "Nickname", "Apodo", "Nickname"],
[
"Nickname on Chess.com",
"Ник на Chess.com",
@ -2153,30 +2128,6 @@ const ROWS: &[[&str; 6]] = &[
"El mismo apodo",
"Lo stesso nickname",
],
[
"What is downloaded is kept; Update continues from there",
"Скачанное сохранится; «Обновить» продолжит с этого места",
"Ce qui est téléchargé est conservé ; « Mettre à jour » reprend à partir de là",
"Bereits Geladenes bleibt; „Aktualisieren“ setzt dort fort",
"Lo descargado se conserva; «Actualizar» continúa desde ahí",
"Quanto scaricato resta; «Aggiorna» riprende da lì",
],
[
"Your games from Lichess and Chess.com",
"Ваши партии с Lichess и Chess.com",
"Vos parties de Lichess et Chess.com",
"Ihre Partien von Lichess und Chess.com",
"Tus partidas de Lichess y Chess.com",
"Le tue partite da Lichess e Chess.com",
],
[
"Your online games become a database here, to search and analyse. Only the nickname is needed, no login.",
"Ваши онлайн-партии станут базой здесь: искать, разбирать, анализировать. Нужен только ник, входить в аккаунт не нужно.",
"Vos parties en ligne deviennent une base ici, pour chercher et analyser. Seul le pseudo est nécessaire, sans connexion.",
"Ihre Online-Partien werden hier zu einer Datenbank zum Suchen und Analysieren. Nur der Nickname wird gebraucht, keine Anmeldung.",
"Tus partidas en línea se convierten aquí en una base para buscar y analizar. Solo hace falta el apodo, sin iniciar sesión.",
"Le tue partite online diventano qui una base da cercare e analizzare. Serve solo il nickname, senza accesso.",
],
[
"as on the site",
"как на сайте",
@ -2193,110 +2144,6 @@ const ROWS: &[[&str; 6]] = &[
"actualizando…",
"aggiornamento…",
],
[
"{p}: +{n} games, {t} in «{name}»",
"{p}: +{n} партий, всего {t} в «{name}»",
"{p} : +{n} parties, {t} dans « {name} »",
"{p}: +{n} Partien, {t} in „{name}“",
"{p}: +{n} partidas, {t} en «{name}»",
"{p}: +{n} partite, {t} in «{name}»",
],
[
"{p}: failed ({e})",
"{p}: не получилось ({e})",
"{p} : échec ({e})",
"{p}: fehlgeschlagen ({e})",
"{p}: error ({e})",
"{p}: non riuscito ({e})",
],
[
"{p}: nothing new, {t} games in «{name}»",
"{p}: новых нет, {t} партий в «{name}»",
"{p} : rien de nouveau, {t} parties dans « {name} »",
"{p}: nichts Neues, {t} Partien in „{name}“",
"{p}: nada nuevo, {t} partidas en «{name}»",
"{p}: niente di nuovo, {t} partite in «{name}»",
],
[
"{p}: stopped, {t} games kept in «{name}»",
"{p}: остановлено, сохранено {t} партий в «{name}»",
"{p} : arrêté, {t} parties conservées dans « {name} »",
"{p}: angehalten, {t} Partien in „{name}“ behalten",
"{p}: detenido, {t} partidas guardadas en «{name}»",
"{p}: fermato, {t} partite conservate in «{name}»",
],
[
"{p}: the site asks to wait a minute; then try again",
"{p}: сайт просит подождать минуту, потом попробуйте снова",
"{p} : le site demande d'attendre une minute, puis réessayez",
"{p}: die Seite bittet um eine Minute Geduld, dann erneut versuchen",
"{p}: el sitio pide esperar un minuto; luego inténtalo de nuevo",
"{p}: il sito chiede di attendere un minuto, poi riprova",
],
[
"{p}: {name} — games of {m} months",
"{p}: {name} — партии за {m} мес.",
"{p} : {name} — parties de {m} mois",
"{p}: {name} — Partien aus {m} Monaten",
"{p}: {name} — partidas de {m} meses",
"{p}: {name} — partite di {m} mesi",
],
[
"{p}: {name} — up to {n} games (about {m} min the first time)",
"{p}: {name} — до {n} партий (первый раз около {m} мин)",
"{p} : {name} — jusqu'à {n} parties (environ {m} min la première fois)",
"{p}: {name} — bis zu {n} Partien (beim ersten Mal etwa {m} Min.)",
"{p}: {name} — hasta {n} partidas (la primera vez, unos {m} min)",
"{p}: {name} — fino a {n} partite (la prima volta circa {m} min)",
],
[
"{p}: {n} games",
"{p}: {n} партий",
"{p} : {n} parties",
"{p}: {n} Partien",
"{p}: {n} partidas",
"{p}: {n} partite",
],
[
"{p}: {n} of up to {t} games",
"{p}: {n} из примерно {t} партий",
"{p} : {n} sur environ {t} parties",
"{p}: {n} von bis zu {t} Partien",
"{p}: {n} de hasta {t} partidas",
"{p}: {n} di circa {t} partite",
],
[
"✖ {p}: no answer ({e})",
"✖ {p}: нет ответа ({e})",
"✖ {p} : pas de réponse ({e})",
"✖ {p}: keine Antwort ({e})",
"✖ {p}: sin respuesta ({e})",
"✖ {p}: nessuna risposta ({e})",
],
[
"✖ {p}: no such player",
"✖ {p}: игрок не найден",
"✖ {p} : joueur introuvable",
"✖ {p}: Spieler nicht gefunden",
"✖ {p}: jugador no encontrado",
"✖ {p}: giocatore non trovato",
],
[
"⟳ Update",
"⟳ Обновить",
"⟳ Mettre à jour",
"⟳ Aktualisieren",
"⟳ Actualizar",
"⟳ Aggiorna",
],
[
"⬇ Download ({n})",
"⬇ Загрузить ({n})",
"⬇ Télécharger ({n})",
"⬇ Herunterladen ({n})",
"⬇ Descargar ({n})",
"⬇ Scarica ({n})",
],
[
"Checking…",
"Проверяю…",
@ -2953,14 +2800,6 @@ const ROWS: &[[&str; 6]] = &[
"Tienes la {old}",
"Hai la {old}",
],
[
"Put the games of both sites into one database",
"Сложить партии с обоих сайтов в одну базу",
"Mettre les parties des deux sites dans une seule base",
"Partien beider Seiten in eine Datenbank legen",
"Poner las partidas de ambos sitios en una sola base",
"Mettere le partite di entrambi i siti in una sola base",
],
[
"Otherwise each site gets a database of its own",
"Иначе у каждого сайта будет своя база",
@ -2970,21 +2809,269 @@ const ROWS: &[[&str; 6]] = &[
"Altrimenti ogni sito avrà la sua base",
],
[
"Into «{name}» (already {n} games there; only new ones are added)",
"В базу «{name}» (там уже {n} партий; добавятся только новые)",
"Dans « {name} » (déjà {n} parties ; seules les nouvelles sont ajoutées)",
"In „{name}“ (schon {n} Partien dort; nur neue kommen dazu)",
"En «{name}» (ya hay {n} partidas; solo se añaden las nuevas)",
"In «{name}» (già {n} partite; si aggiungono solo le nuove)",
"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",
],
[
"Into the new database «{name}»",
"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…",
"Проверка движка…",

View file

@ -207,6 +207,8 @@ pub struct Library {
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`).
@ -232,6 +234,7 @@ impl Library {
scroll_to_selected: false,
online: false,
online_busy: Vec::new(),
online_running: None,
sizes: HashMap::new(),
update: None,
}
@ -618,7 +621,7 @@ impl Library {
if self.online
&& ui
.button("🌐")
.on_hover_text(tr("Download your online games by nickname into a database"))
.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);
@ -701,17 +704,26 @@ impl Library {
let visuals = ui.style().interact(&resp);
ui.painter()
.rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside);
for (dy, text) in [(-9.0, tr("Games from")), (9.0, "Lichess · Chess.com")] {
ui.painter().text(
rect.center() + vec2(0.0, dy),
egui::Align2::CENTER_CENTER,
text,
egui::FontId::proportional(14.0),
visuals.text_color(),
);
}
let below = match self.online_running {
Some(n) => trf("downloading… {n}", &[("n", &large_db::grouped(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 your online games by nickname into a database"))
.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);
@ -768,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,
);
@ -933,13 +949,28 @@ impl Library {
if self.online_busy.contains(&path) {
ui.add(egui::Spinner::new().size(14.0));
ui.label(RichText::new(tr("updating…")).weak());
} else if self.online
&& ui
.small_button(tr("⟳ Update"))
.on_hover_text(tr("Fetch the games played since the last download"))
} 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()));
{
actions.push(LibraryAction::UpdateOnline(path.clone()));
}
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {

View file

@ -1,6 +1,7 @@
//! The user's games from Lichess and Chess.com, by nickname (no login): each platform's
//! games become a PGN database of their own in `<local data dir>/online/`, with a small
//! state file next to it so that "Update" fetches only the new games (and continues an
//! A player's games from Lichess and Chess.com, by nickname (no login; anyone's: the
//! user's own, a pupil's, an opponent's): they become a PGN database in
//! `<local data dir>/online/` (one per site, or both sites in one), with a small state
//! file next to it so that "Update" fetches only the new games (and continues an
//! interrupted download). Both public APIs are probed at start; a platform that does not
//! answer as expected (offline, the API changed) is simply not offered.
//!
@ -53,9 +54,9 @@ fn agent(stream: bool) -> ureq::Agent {
.http_status_as_error(false)
.timeout_connect(Some(Duration::from_secs(10)))
.timeout_recv_response(Some(Duration::from_secs(30)))
// A long export is one response: no limit on the body, only on the rest.
// A long export is one response: hours for the body (a stalled one ends).
.timeout_recv_body(if stream {
None
Some(Duration::from_secs(4 * 3600))
} else {
Some(Duration::from_secs(60))
})
@ -74,6 +75,8 @@ pub enum Failure {
Unexpected(String),
/// Writing the database failed.
Disk(String),
/// The database is being downloaded already.
Busy,
}
impl std::fmt::Display for Failure {
@ -83,6 +86,7 @@ impl std::fmt::Display for Failure {
Failure::RateLimited => write!(f, "rate limited"),
Failure::Unexpected(e) => write!(f, "unexpected answer: {e}"),
Failure::Disk(e) => write!(f, "{e}"),
Failure::Busy => write!(f, "the database is being downloaded already"),
}
}
}
@ -249,19 +253,54 @@ pub fn database_path(p: Platform, username: &str) -> Option<PathBuf> {
dir().map(|d| d.join(format!("{username} ({}).pgn", p.name())))
}
/// The database of several accounts in one: "Name (Lichess + Chess.com).pgn", named
/// after the first account.
/// The database of several accounts in one: "Name (Lichess + Chess.com).pgn" when the
/// nicknames are the same, "Name (Lichess) + Other (Chess.com).pgn" otherwise (so that
/// another set of accounts never lands in the same file).
pub fn combined_path(accounts: &[Account]) -> Option<PathBuf> {
let first = accounts.first()?;
if accounts.len() == 1 {
return database_path(first.platform, &first.username);
}
let platforms = accounts
let same = accounts
.iter()
.map(|a| a.platform.name())
.collect::<Vec<_>>()
.join(" + ");
dir().map(|d| d.join(format!("{} ({platforms}).pgn", first.username)))
.all(|a| a.username.eq_ignore_ascii_case(&first.username));
let name = if same {
let platforms = accounts
.iter()
.map(|a| a.platform.name())
.collect::<Vec<_>>()
.join(" + ");
format!("{} ({platforms})", first.username)
} else {
accounts
.iter()
.map(|a| format!("{} ({})", a.username, a.platform.name()))
.collect::<Vec<_>>()
.join(" + ")
};
dir().map(|d| d.join(format!("{name}.pgn")))
}
/// The online databases already holding `account` (several when it was downloaded
/// alone and together with another one), those with more accounts first.
pub fn holding(account: &Account) -> Vec<PathBuf> {
let Some(dir) = dir() else {
return Vec::new();
};
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut found: Vec<(usize, PathBuf)> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "pgn"))
.filter_map(|p| {
let s = State::load(&p)?;
s.holds(account).then_some((s.accounts.len(), p))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
found.into_iter().map(|(_, p)| p).collect()
}
fn state_path(pgn: &Path) -> PathBuf {
@ -275,6 +314,11 @@ pub struct AccountState {
pub username: String,
/// Lichess: creation time (ms) of the newest game fetched.
pub lichess_last: Option<i64>,
/// Lichess: games still being played when last fetched (id, creation time ms):
/// the next update asks again from the oldest of them, so that a long
/// (correspondence) game is fetched once it ends.
#[serde(default)]
pub lichess_pending: Vec<(String, i64)>,
/// Chess.com: the newest month fetched ("2026/10") and the end time (s) of its
/// last game fetched.
pub chesscom_month: Option<String>,
@ -288,8 +332,21 @@ pub struct State {
pub accounts: Vec<AccountState>,
/// Games written so far.
pub games: u64,
/// When the last download finished (Unix seconds).
#[serde(default)]
pub updated: Option<i64>,
/// The length of the database file when the state was saved, and its last bytes:
/// what a crash appended after that is cut off before the next download (only if
/// the file still ends the same way there, i.e. nobody else changed it).
#[serde(default)]
pub bytes: Option<u64>,
#[serde(default)]
pub tail: Vec<u8>,
}
/// How many last bytes of the file the state remembers.
const TAIL: usize = 64;
impl State {
pub fn load(pgn: &Path) -> Option<State> {
let text = std::fs::read_to_string(state_path(pgn)).ok()?;
@ -307,6 +364,10 @@ impl State {
.map_err(|e| Failure::Disk(e.to_string()))
}
fn holds(&self, a: &Account) -> bool {
self.accounts.iter().any(|s| s.is(a))
}
/// The accounts of the database, to update it.
pub fn accounts(&self) -> Vec<Account> {
self.accounts
@ -323,11 +384,52 @@ impl State {
}
}
impl AccountState {
fn is(&self, a: &Account) -> bool {
self.platform == Some(a.platform) && self.username.eq_ignore_ascii_case(&a.username)
}
}
impl Account {
/// The same account (the counts aside).
pub fn same(&self, other: &Account) -> bool {
self.platform == other.platform && self.username.eq_ignore_ascii_case(&other.username)
}
}
/// An online database (it has a state file).
pub fn is_online(pgn: &Path) -> bool {
dir().is_some_and(|d| pgn.parent() == Some(d.as_path())) && state_path(pgn).exists()
}
/// What a running download is doing, for the progress line: the account (its index in
/// the accounts passed to [`download`]), the games of that account so far, and for
/// Chess.com the months done of all.
#[derive(Debug, Default)]
pub struct Progress {
pub account: AtomicUsize,
pub games: AtomicUsize,
pub months_done: AtomicUsize,
pub months_total: AtomicUsize,
}
fn now_secs() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
}
/// "5 min ago", "3 h ago", "2 d ago" for a time in Unix seconds.
pub fn ago(t: i64) -> String {
use crate::i18n::trf;
let s = (now_secs() - t).max(0);
match s {
0..3600 => trf("{n} min ago", &[("n", &(s / 60).max(1))]),
3600..86400 => trf("{n} h ago", &[("n", &(s / 3600))]),
_ => trf("{n} d ago", &[("n", &(s / 86400))]),
}
}
/// The result of a download.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Done {
@ -339,30 +441,83 @@ pub struct Done {
pub cancelled: bool,
}
/// The databases being written now: one download per file at a time.
static WRITING: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
/// Holds a database for one download; released when dropped.
struct Claim(PathBuf);
impl Claim {
fn take(path: &Path) -> Option<Claim> {
let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner());
if w.iter().any(|p| p == path) {
return None;
}
w.push(path.to_owned());
Some(Claim(path.to_owned()))
}
}
impl Drop for Claim {
fn drop(&mut self) {
let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner());
w.retain(|p| *p != self.0);
}
}
/// Appends games to the database file and keeps the state in step.
struct Writer {
path: PathBuf,
file: std::io::BufWriter<std::fs::File>,
state: State,
added: u64,
/// The file's length and last bytes as written (flushed or not).
len: u64,
tail: Vec<u8>,
}
impl Writer {
fn open(path: &Path, state: State) -> Result<Writer, Failure> {
/// Opens the database for appending; a state that does not match the file (the file
/// is gone, or a crash left games after the state) is put right first.
fn open(path: &Path, mut state: State) -> Result<Writer, Failure> {
let disk = |e: std::io::Error| Failure::Disk(e.to_string());
if let Some(d) = path.parent() {
std::fs::create_dir_all(d).map_err(disk)?;
}
let file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.append(true)
.open(path)
.map_err(disk)?;
let mut len = file.metadata().map_err(disk)?.len();
if let Some(b) = state.bytes
&& len > b
&& b as usize >= state.tail.len()
{
let mut end = vec![0; state.tail.len()];
use std::io::{Read, Seek, SeekFrom};
let mut f = &file;
f.seek(SeekFrom::Start(b - state.tail.len() as u64))
.and_then(|_| f.read_exact(&mut end))
.map_err(disk)?;
if end == state.tail {
file.set_len(b).map_err(disk)?;
len = b;
}
}
let tail = if len == state.bytes.unwrap_or(u64::MAX) {
std::mem::take(&mut state.tail)
} else {
Vec::new()
};
Ok(Writer {
path: path.to_owned(),
file: std::io::BufWriter::new(file),
state,
added: 0,
len,
tail,
})
}
@ -371,10 +526,16 @@ impl Writer {
if pgn.is_empty() {
return Ok(());
}
self.file
.write_all(pgn.as_bytes())
.and_then(|_| self.file.write_all(b"\n\n"))
.map_err(|e| Failure::Disk(e.to_string()))?;
for part in [pgn.as_bytes(), b"\n\n"] {
self.file
.write_all(part)
.map_err(|e| Failure::Disk(e.to_string()))?;
self.len += part.len() as u64;
self.tail.extend_from_slice(part);
}
if self.tail.len() > TAIL {
self.tail.drain(..self.tail.len() - TAIL);
}
self.added += 1;
self.state.games += 1;
Ok(())
@ -385,10 +546,15 @@ impl Writer {
self.file
.flush()
.map_err(|e| Failure::Disk(e.to_string()))?;
self.state.bytes = Some(self.len);
self.state.tail = self.tail.clone();
self.state.save(&self.path)
}
fn done(mut self, cancelled: bool) -> Result<Done, Failure> {
if !cancelled {
self.state.updated = Some(now_secs());
}
self.commit()?;
Ok(Done {
path: self.path,
@ -399,38 +565,30 @@ impl Writer {
}
}
/// Fetches the games of `accounts` new since the last run into their database (one
/// database for all of them); `progress` counts the games added. Cancelling keeps what
/// was fetched.
/// Fetches the games of `accounts` new since the last run into the database at `path`
/// (one database for all of them); `progress` counts the games added, `status` tells
/// what is being fetched. Cancelling keeps what was fetched. One download per database
/// at a time ([`Failure::Busy`] otherwise).
pub fn download(
accounts: &[Account],
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Result<Done, Failure> {
let path = combined_path(accounts).ok_or_else(|| Failure::Disk("no data directory".into()))?;
download_to(accounts, &path, progress, cancel)
}
/// [`download`] into the database at `path`.
fn download_to(
accounts: &[Account],
path: &Path,
progress: &AtomicUsize,
cancel: &AtomicBool,
status: &Progress,
) -> Result<Done, Failure> {
let _claim = Claim::take(path).ok_or(Failure::Busy)?;
let path = path.to_owned();
let mut state = State::load(&path).unwrap_or_else(|| {
// A database without its state: start it anew rather than append duplicates.
let _ = std::fs::remove_file(&path);
State::default()
});
let mut state = State::load(&path)
// The games are gone (the file was deleted): fetch them again.
.filter(|s| path.exists() || s.games == 0)
.unwrap_or_else(|| {
// A database without its state: start it anew rather than append duplicates.
let _ = std::fs::remove_file(&path);
State::default()
});
// Accounts not in the database yet start from their first game.
for a in accounts {
if !state
.accounts
.iter()
.any(|s| s.platform == Some(a.platform) && s.username.eq_ignore_ascii_case(&a.username))
{
if !state.holds(a) {
state.accounts.push(AccountState {
platform: Some(a.platform),
username: a.username.clone(),
@ -441,17 +599,14 @@ fn download_to(
let mut w = Writer::open(&path, state)?;
let mut result = Ok(false);
for i in 0..w.state.accounts.len() {
let wanted = accounts.iter().any(|a| {
Some(a.platform) == w.state.accounts[i].platform
&& a.username
.eq_ignore_ascii_case(&w.state.accounts[i].username)
});
if !wanted {
let Some(k) = accounts.iter().position(|a| w.state.accounts[i].is(a)) else {
continue;
}
};
status.account.store(k, Ordering::Relaxed);
status.games.store(0, Ordering::Relaxed);
result = match w.state.accounts[i].platform {
Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel),
Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel),
Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel, status),
Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status),
None => Ok(false),
};
if !matches!(result, Ok(false)) {
@ -468,6 +623,56 @@ fn download_to(
}
}
#[cfg(test)]
fn download_to(
accounts: &[Account],
path: &Path,
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Result<Done, Failure> {
download(accounts, path, progress, cancel, &Progress::default())
}
/// Lichess's answer for one game, as far as the download cares.
struct LichessGame<'a> {
id: &'a str,
created: i64,
/// Still being played (not exported as a game yet).
playing: bool,
standard: bool,
pgn: &'a str,
}
fn lichess_game(v: &Value) -> Option<LichessGame<'_>> {
Some(LichessGame {
id: v["id"].as_str()?,
created: v["createdAt"].as_i64()?,
playing: matches!(v["status"].as_str(), Some("created" | "started")),
standard: v["variant"]
.as_str()
.is_none_or(|x| x == "standard" || x == "fromPosition"),
pgn: v["pgn"].as_str()?,
})
}
/// What to do with a game of the Lichess export: `Some(write?)`, given the newest game
/// fetched before this run and the games pending then (unfinished). The export repeats
/// games from the oldest pending one on; those fetched already are skipped.
fn lichess_keep(a: &mut AccountState, g: &LichessGame, before: Option<i64>) -> bool {
let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id);
if g.playing {
if pending.is_none() && g.standard {
a.lichess_pending.push((g.id.to_owned(), g.created));
}
return false;
}
if let Some(k) = pending {
a.lichess_pending.remove(k);
return g.standard;
}
g.standard && before.is_none_or(|b| g.created > b)
}
/// The games of account `i` of the writer's database from Lichess. `Ok(true)` when
/// cancelled.
fn lichess(
@ -475,15 +680,25 @@ fn lichess(
i: usize,
progress: &AtomicUsize,
cancel: &AtomicBool,
status: &Progress,
) -> Result<bool, Failure> {
let a = &w.state.accounts[i];
let before = a.lichess_last;
let from = a
.lichess_pending
.iter()
.map(|(_, t)| *t)
.chain(before.map(|b| b + 1))
.min();
let pending_before: Vec<String> = a.lichess_pending.iter().map(|(id, _)| id.clone()).collect();
let mut url = format!(
"https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&pgnInJson=true\
"https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false&pgnInJson=true\
&perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence\
&clocks=false&evals=false&opening=true",
w.state.accounts[i].username
a.username
);
if let Some(last) = w.state.accounts[i].lichess_last {
url.push_str(&format!("&since={}", last + 1));
if let Some(from) = from {
url.push_str(&format!("&since={from}"));
}
let resp = agent(true)
.get(&url)
@ -496,6 +711,7 @@ fn lichess(
code => return Err(Failure::Unexpected(format!("HTTP {code}"))),
}
let reader = BufReader::new(resp.into_body().into_reader());
let mut seen: Vec<String> = Vec::new();
for (n, line) in reader.lines().enumerate() {
if cancel.load(Ordering::Relaxed) {
return Ok(true);
@ -506,23 +722,29 @@ fn lichess(
}
let v: Value =
serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?;
let (Some(pgn), Some(created)) = (v["pgn"].as_str(), v["createdAt"].as_i64()) else {
return Err(Failure::Unexpected(
"a game without pgn or createdAt".into(),
));
};
if v["variant"]
.as_str()
.is_none_or(|x| x == "standard" || x == "fromPosition")
{
w.game(pgn)?;
progress.fetch_add(1, Ordering::Relaxed);
let g = lichess_game(&v)
.ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?;
if pending_before.iter().any(|id| id == g.id) {
seen.push(g.id.to_owned());
}
w.state.accounts[i].lichess_last = Some(created);
let a = &mut w.state.accounts[i];
if lichess_keep(a, &g, before) {
let pgn = g.pgn.to_owned();
w.game(&pgn)?;
progress.fetch_add(1, Ordering::Relaxed);
status.games.fetch_add(1, Ordering::Relaxed);
}
let a = &mut w.state.accounts[i];
a.lichess_last = Some(a.lichess_last.map_or(g.created, |l| l.max(g.created)));
if n % 100 == 99 {
w.commit()?;
}
}
// The whole export arrived: a game pending before that did not come again is gone
// (deleted, or a variant that ended).
w.state.accounts[i]
.lichess_pending
.retain(|(id, _)| !pending_before.contains(id) || seen.contains(id));
Ok(false)
}
@ -533,10 +755,14 @@ fn chesscom(
i: usize,
progress: &AtomicUsize,
cancel: &AtomicBool,
status: &Progress,
) -> Result<bool, Failure> {
let lower = w.state.accounts[i].username.to_ascii_lowercase();
let months = archives(&lower)?;
status.months_total.store(months.len(), Ordering::Relaxed);
status.months_done.store(0, Ordering::Relaxed);
for url in months {
status.months_done.fetch_add(1, Ordering::Relaxed);
// ".../games/2026/10" → "2026/10"; months before the last fetched are done.
let month = url.rsplitn(3, '/').take(2).collect::<Vec<_>>();
let month = format!(
@ -574,6 +800,7 @@ fn chesscom(
}
w.game(pgn)?;
progress.fetch_add(1, Ordering::Relaxed);
status.games.fetch_add(1, Ordering::Relaxed);
w.state.accounts[i].chesscom_last_end = Some(end);
}
// The mark moves to this month even when it had no standard games (the end
@ -633,11 +860,13 @@ impl Probe {
self.job = None;
self.last = Some(std::time::Instant::now());
}
if self.job.is_none()
&& !self.available.iter().all(|a| *a)
&& self.last.is_some_and(|t| t.elapsed() >= Self::RETRY)
{
self.spawn();
if self.job.is_none() && !self.available.iter().all(|a| *a) {
match self.last {
Some(t) if t.elapsed() >= Self::RETRY => self.spawn(),
// Wake up for the retry even when nothing else repaints.
Some(t) => self.ctx.request_repaint_after(Self::RETRY - t.elapsed()),
None => {}
}
}
}
@ -654,6 +883,148 @@ impl Probe {
mod tests {
use super::*;
fn temp_dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("cp-online-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn account(p: Platform, name: &str) -> Account {
Account {
platform: p,
username: name.into(),
games: None,
months: None,
}
}
const GAME: &str = "[Event \"x\"]\n\n1. e4 e5 1-0";
#[test]
fn a_crash_leaves_no_duplicates() {
let dir = temp_dir("crash");
let path = dir.join("db.pgn");
let state = State {
accounts: vec![AccountState {
platform: Some(Platform::Lichess),
username: "a".into(),
..AccountState::default()
}],
..State::default()
};
let mut w = Writer::open(&path, state).unwrap();
w.game(GAME).unwrap();
w.game(GAME).unwrap();
w.commit().unwrap();
let good = std::fs::read(&path).unwrap();
// Games written after the last commit, then the process died.
w.game(GAME).unwrap();
w.file.flush().unwrap();
drop(w);
assert!(std::fs::read(&path).unwrap().len() > good.len());
let w = Writer::open(&path, State::load(&path).unwrap()).unwrap();
assert_eq!(w.state.games, 2);
drop(w);
assert_eq!(std::fs::read(&path).unwrap(), good, "cut back to the state");
// Somebody else changed the file: it is left alone.
let mut other = good.clone();
other[0] = b' ';
other.extend_from_slice(GAME.as_bytes());
std::fs::write(&path, &other).unwrap();
let w = Writer::open(&path, State::load(&path).unwrap()).unwrap();
drop(w);
assert_eq!(std::fs::read(&path).unwrap(), other);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_deleted_database_is_downloaded_again() {
let dir = temp_dir("deleted");
let path = dir.join("db.pgn");
let state = State {
accounts: vec![AccountState {
platform: Some(Platform::Lichess),
username: "a".into(),
lichess_last: Some(5),
..AccountState::default()
}],
games: 7,
..State::default()
};
state.save(&path).unwrap();
let never = AtomicBool::new(false);
// No account asked for: nothing fetched, only the state put right.
let d = download_to(&[], &path, &AtomicUsize::new(0), &never).unwrap();
assert_eq!(d.total, 0);
let s = State::load(&path).unwrap_or_default();
assert!(s.accounts.iter().all(|a| a.lichess_last.is_none()));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn one_download_per_database() {
let path = PathBuf::from("/nonexistent/cp-claim.pgn");
let first = Claim::take(&path).expect("free");
assert!(Claim::take(&path).is_none());
let never = AtomicBool::new(false);
assert_eq!(
download_to(&[], &path, &AtomicUsize::new(0), &never),
Err(Failure::Busy)
);
drop(first);
assert!(Claim::take(&path).is_some());
}
#[test]
fn names_of_merged_databases() {
let name = |a: &[Account]| {
combined_path(a)
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
};
let li = account(Platform::Lichess, "Magnus");
assert_eq!(name(std::slice::from_ref(&li)), "Magnus (Lichess).pgn");
let cc = account(Platform::ChessCom, "magnus");
assert_eq!(name(&[li.clone(), cc]), "Magnus (Lichess + Chess.com).pgn");
let other = account(Platform::ChessCom, "MagnusCarlsen");
assert_eq!(
name(&[li, other]),
"Magnus (Lichess) + MagnusCarlsen (Chess.com).pgn"
);
}
#[test]
fn unfinished_lichess_games_come_later() {
let mut a = AccountState::default();
let g = |id: &'static str, created: i64, playing: bool| LichessGame {
id,
created,
playing,
standard: true,
pgn: "",
};
// First run: a correspondence game is still on, a later one is over.
assert!(!lichess_keep(&mut a, &g("corr", 10, true), None));
assert!(lichess_keep(&mut a, &g("blitz", 20, false), None));
assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]);
// The next run starts from the pending game: it is over now and is kept, the
// game fetched before is not repeated.
assert!(lichess_keep(&mut a, &g("corr", 10, false), Some(20)));
assert!(!lichess_keep(&mut a, &g("blitz", 20, false), Some(20)));
assert!(lichess_keep(&mut a, &g("new", 30, false), Some(20)));
assert!(a.lichess_pending.is_empty());
// A variant game is neither kept nor waited for.
let mut v = g("960", 40, true);
v.standard = false;
assert!(!lichess_keep(&mut a, &v, Some(30)));
assert!(a.lichess_pending.is_empty());
}
/// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of
/// the repository): lookup, an interrupted Lichess download continued without gaps
/// or duplicates, a full Chess.com download, and an update that adds nothing. Run
@ -853,6 +1224,7 @@ mod tests {
..AccountState::default()
}],
games: 3,
..State::default()
};
s.save(&pgn).unwrap();
assert_eq!(State::load(&pgn), Some(s));

View file

@ -1,29 +1,54 @@
//! The window "Games from Lichess and Chess.com": one nickname (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`).
//! 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::{tr, trf};
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(std::path::PathBuf),
Added(PathBuf),
/// A database got new games: reload it.
Updated(std::path::PathBuf),
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)]
@ -38,9 +63,7 @@ pub struct OnlineDialog {
/// The nicknames `found` answers.
found_for: (String, String),
jobs: Vec<Job>,
/// Per finished download: the platforms ("Lichess + Chess.com"), the database name
/// and the outcome.
results: Vec<(String, String, Result<Done, Failure>)>,
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
@ -49,26 +72,89 @@ pub struct OnlineDialog {
auto_download: bool,
}
fn count(n: u64) -> String {
crate::large_db::grouped(n as usize)
}
/// "Lichess + Chess.com".
fn platforms(accounts: &[Account]) -> String {
accounts
.iter()
.map(|a| a.platform.name())
.collect::<Vec<_>>()
.join(" + ")
/// 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: &std::path::Path) -> String {
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) {
@ -96,37 +182,65 @@ impl OnlineDialog {
}
/// Databases being downloaded or updated.
pub fn busy(&self) -> Vec<std::path::PathBuf> {
self.jobs
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_map(|j| online::combined_path(&j.accounts))
.collect()
.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: &std::path::Path, ctx: &egui::Context) {
pub fn update(&mut self, path: &Path, ctx: &egui::Context) {
let Some(state) = online::State::load(path) else {
return;
};
if self.busy().iter().any(|p| p == path) {
return;
}
self.start(state.accounts(), true, ctx);
self.start(state.accounts(), path.to_owned(), true, ctx);
}
fn start(&mut self, accounts: Vec<Account>, update: bool, ctx: &egui::Context) {
if accounts.is_empty() {
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, 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,
});
}
}
@ -157,23 +271,43 @@ impl OnlineDialog {
while i < self.jobs.len() {
if let Some(r) = self.jobs[i].work.poll() {
let job = self.jobs.remove(i);
let r = r.unwrap_or(Err(Failure::Network("stopped".into())));
if let Ok(done) = &r {
if job.update {
if done.added > 0 {
events.push(OnlineEvent::Updated(done.path.clone()));
}
} else if done.total > 0 {
events.push(OnlineEvent::Added(done.path.clone()));
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 label = platforms(&job.accounts);
let name = online::combined_path(&job.accounts)
.map(|p| db_name(&p))
.unwrap_or_default();
self.results.retain(|(_, n, _)| *n != name);
self.results.push((label, name, r));
// An update finished with the window closed: say so once it is opened.
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;
}
@ -185,33 +319,40 @@ impl OnlineDialog {
return (events, changed);
}
let mut open = true;
egui::Window::new(tr("Your games from Lichess and Chess.com"))
egui::Window::new(tr("Games from Lichess and Chess.com"))
.open(&mut open)
.default_width(520.0)
.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);
changed |= self.body(ui, probe, settings, &mut events);
});
if !open {
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) -> bool {
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(
"Your online games become a database here, to search and analyse. Only the nickname is needed, no login.",
"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("Nickname"));
ui.label(tr("Player's nickname"));
let r = ui.add(
egui::TextEdit::singleline(&mut self.nick)
.hint_text(tr("as on the site"))
@ -220,6 +361,7 @@ impl OnlineDialog {
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 {
@ -238,9 +380,9 @@ impl OnlineDialog {
Some(o) => {
ui.horizontal(|ui| {
ui.label(tr("Nickname on Chess.com"));
clear |= ui
.add(egui::TextEdit::singleline(o).desired_width(180.0))
.changed();
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"))
@ -280,13 +422,9 @@ impl OnlineDialog {
if auto {
self.auto_find = false;
}
if ui
.add_enabled(
!wanted.is_empty() && valid && !searching,
egui::Button::new(tr("Find")),
)
.clicked()
|| (auto && !wanted.is_empty() && valid)
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();
@ -313,157 +451,233 @@ impl OnlineDialog {
}
});
if self.found_for == nicks && !self.found.is_empty() {
ui.add_space(4.0);
let mut start: Vec<Account> = Vec::new();
for (p, l) in &self.found {
ui.horizontal(|ui| match l {
Lookup::Found(a) => {
let what = match (a.games, a.months) {
(Some(g), _) => {
let secs = g / online::LICHESS_RATE;
trf(
"{p}: {name} — up to {n} games (about {m} min the first time)",
&[
("p", &p.name()),
("name", &a.username),
("n", &count(g)),
("m", &secs.div_ceil(60).max(1)),
],
)
}
(_, Some(m)) => trf(
"{p}: {name} — games of {m} months",
&[("p", &p.name()), ("name", &a.username), ("m", &m)],
),
_ => format!("{}: {}", p.name(), a.username),
};
ui.label(format!("✔ {what}"));
if !self.jobs.iter().any(|j| j.accounts.contains(a)) {
start.push(a.clone());
}
}
Lookup::NotFound => {
ui.label(
RichText::new(trf("✖ {p}: no such player", &[("p", &p.name())])).weak(),
);
}
Lookup::Failed(e) => {
ui.label(
RichText::new(trf(
"✖ {p}: no answer ({e})",
&[("p", &p.name()), ("e", e)],
))
.color(ui.visuals().warn_fg_color),
);
}
});
}
// 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("Put the games of both sites into one database"),
)
.on_hover_text(tr("Otherwise each site gets a database of its own"))
.changed()
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))) =>
{
self.separate = !one;
Some(a.clone())
}
}
// Where the games go, and what is there already.
let targets: Vec<Vec<Account>> = if together {
vec![start.clone()]
} else {
start.iter().map(|a| vec![a.clone()]).collect()
};
for t in &targets {
if let Some(path) = online::combined_path(t) {
let text = match online::State::load(&path) {
Some(s) => trf(
"Into «{name}» (already {n} games there; only new ones are added)",
&[("name", &db_name(&path)), ("n", &count(s.games))],
_ => 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)),
],
),
None => trf(
"Into the new database «{name}»",
&[("name", &db_name(&path))],
(_, Some(m)) => trf(
"{p}: {name} — months with games: {m}",
&[("p", &p.name()), ("name", &a.username), ("m", &m)],
),
_ => format!("{}: {}", p.name(), a.username),
};
ui.label(RichText::new(text).weak());
ui.label(format!("✔ {what}"));
}
}
let auto = std::mem::take(&mut self.auto_download) && !start.is_empty();
if !start.is_empty() && (ui.button(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 in targets {
self.start(t, false, ui.ctx());
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 !self.jobs.is_empty() || !self.results.is_empty() {
ui.separator();
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));
let n = j.work.progress() as u64;
let known: u64 = j.accounts.iter().filter_map(|a| a.games).sum();
let label = platforms(&j.accounts);
let text = if known > 0 && j.accounts.iter().all(|a| a.games.is_some()) {
trf(
"{p}: {n} of up to {t} games",
&[("p", &label), ("n", &count(n)), ("t", &count(known))],
)
} else {
trf("{p}: {n} games", &[("p", &label), ("n", &count(n))])
};
ui.label(text);
ui.label(RichText::new(db_name(&j.path)).strong());
if ui
.small_button(tr("Stop"))
.on_hover_text(tr(
"What is downloaded is kept; Update continues from there",
"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);
}
for (p, name, r) in &self.results {
let p = p.as_str();
let line = match r {
Ok(d) if d.cancelled => trf(
"{p}: stopped, {t} games kept in «{name}»",
&[("p", &p), ("t", &count(d.total)), ("name", name)],
),
Ok(d) if d.added == 0 => trf(
"{p}: nothing new, {t} games in «{name}»",
&[("p", &p), ("t", &count(d.total)), ("name", name)],
),
Ok(d) => trf(
"{p}: +{n} games, {t} in «{name}»",
&[
("p", &p),
("n", &count(d.added)),
("t", &count(d.total)),
("name", name),
],
),
Err(Failure::RateLimited) => trf(
"{p}: the site asks to wait a minute; then try again",
&[("p", &p)],
),
Err(e) => trf("{p}: failed ({e})", &[("p", &p), ("e", e)]),
};
ui.label(line);
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());
}
changed
}
}

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)),
)
}