diff --git a/CHANGELOG.md b/CHANGELOG.md index e125d6c..8128635 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Cargo.lock b/Cargo.lock index dbe61ff..d603e90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", ] diff --git a/Cargo.toml b/Cargo.toml index af4c638..e75728c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/README.md b/README.md index beb4d64..0492e32 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/README.ru.md b/README.ru.md index faaa67a..15fe1d2 100644 --- a/README.ru.md +++ b/README.ru.md @@ -26,6 +26,7 @@ - **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор, копирование PGN/FEN, сохранение партии в новый файл. - **Оформление** — 17 наборов фигур, 37 досок (цвета и текстуры), 7 наборов звуков, тёмная и светлая тема. +- **Ваши онлайн-партии** — загрузка своих партий с Lichess и Chess.com по нику (без входа) в базу и обновление одной кнопкой. - **Языки** — English, Русский, Français, Deutsch, Español, Italiano. | Анализ партии: график и отчёт | Отметки движка и лучшие варианты | diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index d755a19..72cdd3c 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -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, 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(); } } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 8bc1b50..5c9e218 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -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"), diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index bd29bdc..afd6d3b 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -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, 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, + /// Games downloaded so far while downloads run (shown on the shelf card). + pub online_running: Option, /// A newer version to offer (its number), next to Settings. pub update: Option, /// 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 diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 8c73409..6c4169e 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -15,6 +15,8 @@ mod i18n; mod large_db; mod library; mod notation; +mod online; +mod online_ui; mod reference; mod report; mod review; diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs new file mode 100644 index 0000000..197a6d8 --- /dev/null +++ b/apps/desktop/src/online.rs @@ -0,0 +1,1321 @@ +//! 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 +//! `/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. +//! +//! Lichess: `GET /api/games/user/{name}` as NDJSON (`pgnInJson`), oldest first, from +//! `since`; anonymous requests are throttled to 20 games a second. Chess.com: the list of +//! monthly archives, then each month's games as JSON (their PGN inside), from the last +//! month already fetched. Only standard chess is kept (variants are not supported). + +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Platform { + Lichess, + ChessCom, +} + +impl Platform { + pub const ALL: [Platform; 2] = [Platform::Lichess, Platform::ChessCom]; + + pub fn name(self) -> &'static str { + match self { + Platform::Lichess => "Lichess", + Platform::ChessCom => "Chess.com", + } + } + + fn index(self) -> usize { + match self { + Platform::Lichess => 0, + Platform::ChessCom => 1, + } + } +} + +/// Lichess's anonymous export rate (games per second), for the time estimate. +pub const LICHESS_RATE: u64 = 20; + +fn agent(stream: bool) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .user_agent(format!( + "ChessPenguin/{} (+https://chess.vrubel.xyz)", + env!("CARGO_PKG_VERSION") + )) + .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: hours for the body (a stalled one ends). + .timeout_recv_body(if stream { + Some(Duration::from_secs(4 * 3600)) + } else { + Some(Duration::from_secs(60)) + }) + .build(); + ureq::Agent::new_with_config(config) +} + +/// What went wrong talking to a platform. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Failure { + /// No answer (offline, DNS, TLS, timeout). + Network(String), + /// "Too many requests": the platform asks to wait. + RateLimited, + /// An answer we do not understand (the API changed). + Unexpected(String), + /// Writing the database failed. + Disk(String), + /// The database is being downloaded already. + Busy, +} + +impl std::fmt::Display for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Failure::Network(e) => write!(f, "network: {e}"), + 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"), + } + } +} + +/// Makes a request again when the connection broke (Lichess drops connections for a +/// minute or so after an export was cut short), waiting `waits` seconds in between; +/// stops waiting when cancelled. +fn retrying( + waits: &[u64], + cancel: &AtomicBool, + mut request: impl FnMut() -> Result, +) -> Result { + let mut waits = waits.iter(); + loop { + match request() { + Ok(r) => return Ok(r), + Err(e) => { + let Some(&secs) = waits.next() else { + return Err(Failure::Network(e.to_string())); + }; + for _ in 0..secs * 10 { + if cancel.load(Ordering::Relaxed) { + return Err(Failure::Network(e.to_string())); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + } + } +} + +/// Waits before the attempts of a download request: about a minute in all. +const DOWNLOAD_WAITS: &[u64] = &[3, 10, 20, 30]; + +/// GET returning (status, body); the body of an error status is not read. +fn get(url: &str) -> Result<(u16, String), Failure> { + let never = AtomicBool::new(false); + // The whole exchange is repeated: a connection may also break in the body. + retrying(&[2, 5], &never, || { + let mut resp = agent(false) + .get(url) + .header("Accept", "application/json") + .call()?; + let status = resp.status().as_u16(); + if status != 200 { + return Ok((status, String::new())); + } + let body = resp + .body_mut() + .with_config() + .limit(64 << 20) + .read_to_string()?; + Ok((status, body)) + }) + .and_then(|(status, body)| { + if status == 429 { + Err(Failure::RateLimited) + } else { + Ok((status, body)) + } + }) +} + +fn json(url: &str) -> Result, Failure> { + match get(url)? { + (200, body) => serde_json::from_str(&body) + .map(Some) + .map_err(|e| Failure::Unexpected(e.to_string())), + (404, _) => Ok(None), + (code, _) => Err(Failure::Unexpected(format!("HTTP {code}"))), + } +} + +/// Whether the platform answers the way this code expects: the profile of an account +/// that has always existed (Lichess's own, Chess.com's founder's). +pub fn probe(p: Platform) -> bool { + let url = match p { + Platform::Lichess => "https://lichess.org/api/user/lichess", + Platform::ChessCom => "https://api.chess.com/pub/player/erik", + }; + matches!(json(url), Ok(Some(v)) if probe_answer_ok(p, &v)) +} + +/// The probe's answer has the fields this code relies on. +fn probe_answer_ok(p: Platform, v: &Value) -> bool { + match p { + Platform::Lichess => { + v["id"] == "lichess" && v["username"].is_string() && v["count"]["all"].is_u64() + } + Platform::ChessCom => v["player_id"].is_u64() && v["username"] == "erik", + } +} + +/// Both platforms probed (in parallel); `[lichess, chess.com]`. +pub fn probe_all() -> [bool; 2] { + std::thread::scope(|s| { + let l = s.spawn(|| probe(Platform::Lichess)); + let c = s.spawn(|| probe(Platform::ChessCom)); + [l.join().unwrap_or(false), c.join().unwrap_or(false)] + }) +} + +/// A nickname both platforms could have: 2–30 letters, digits, `_` or `-`. +pub fn valid_nick(nick: &str) -> bool { + (2..=30).contains(&nick.len()) + && nick + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +/// An account found by nickname. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Account { + pub platform: Platform, + /// As the platform spells it. + pub username: String, + /// Lichess: games of the account (all kinds, so an upper bound for ours). + pub games: Option, + /// Chess.com: months with games. + pub months: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Lookup { + Found(Account), + NotFound, + Failed(Failure), +} + +/// Looks the nickname up on the platform. +pub fn lookup(p: Platform, nick: &str) -> Lookup { + let nick = nick.trim(); + if !valid_nick(nick) { + return Lookup::NotFound; + } + let result = match p { + Platform::Lichess => json(&format!("https://lichess.org/api/user/{nick}")).map(|v| { + v.filter(|v| v["disabled"] != true).and_then(|v| { + Some(Account { + platform: p, + username: v["username"].as_str()?.to_owned(), + games: v["count"]["all"].as_u64(), + months: None, + }) + }) + }), + Platform::ChessCom => { + let lower = nick.to_ascii_lowercase(); + json(&format!("https://api.chess.com/pub/player/{lower}")).and_then(|v| { + let Some(username) = v.and_then(|v| v["username"].as_str().map(str::to_owned)) + else { + return Ok(None); + }; + // Chess.com answers in lower case; the user's spelling reads better. + let username = if username.eq_ignore_ascii_case(nick) { + nick.to_owned() + } else { + username + }; + let months = archives(&lower)?.len(); + Ok(Some(Account { + platform: p, + username, + games: None, + months: Some(months), + })) + }) + } + }; + match result { + Ok(Some(a)) => Lookup::Found(a), + Ok(None) => Lookup::NotFound, + Err(e) => Lookup::Failed(e), + } +} + +/// Chess.com's monthly archive URLs of a player, oldest first. +fn archives(lower: &str) -> Result, Failure> { + let v = json(&format!( + "https://api.chess.com/pub/player/{lower}/games/archives" + ))? + .ok_or_else(|| Failure::Unexpected("no archives".into()))?; + let list = v["archives"] + .as_array() + .ok_or_else(|| Failure::Unexpected("archives".into()))?; + Ok(list + .iter() + .filter_map(|u| u.as_str().map(str::to_owned)) + .collect()) +} + +/// Where the online databases live. +pub fn dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("online")) +} + +/// The database file of one account: "Name (Lichess).pgn". +pub fn database_path(p: Platform, username: &str) -> Option { + dir().map(|d| d.join(format!("{username} ({}).pgn", p.name()))) +} + +/// 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 { + let first = accounts.first()?; + if accounts.len() == 1 { + return database_path(first.platform, &first.username); + } + let same = accounts + .iter() + .all(|a| a.username.eq_ignore_ascii_case(&first.username)); + let name = if same { + let platforms = accounts + .iter() + .map(|a| a.platform.name()) + .collect::>() + .join(" + "); + format!("{} ({platforms})", first.username) + } else { + accounts + .iter() + .map(|a| format!("{} ({})", a.username, a.platform.name())) + .collect::>() + .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 { + 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 { + pgn.with_extension("online.json") +} + +/// What has been fetched from one account into a database. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct AccountState { + pub platform: Option, + pub username: String, + /// Lichess: creation time (ms) of the newest game fetched. + pub lichess_last: Option, + /// 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, + pub chesscom_last_end: Option, +} + +/// What has been fetched into a database (from one account or several), for the next +/// update. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct State { + pub accounts: Vec, + /// Games written so far. + pub games: u64, + /// When the last download finished (Unix seconds). + #[serde(default)] + pub updated: Option, + /// 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, + #[serde(default)] + pub tail: Vec, +} + +/// How many last bytes of the file the state remembers. +const TAIL: usize = 64; + +impl State { + pub fn load(pgn: &Path) -> Option { + let text = std::fs::read_to_string(state_path(pgn)).ok()?; + serde_json::from_str::(&text) + .ok() + .filter(|s| !s.accounts.is_empty() && s.accounts.iter().all(|a| a.platform.is_some())) + } + + fn save(&self, pgn: &Path) -> Result<(), Failure> { + let text = serde_json::to_string_pretty(self).map_err(|e| Failure::Disk(e.to_string()))?; + let path = state_path(pgn); + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, text) + .and_then(|_| std::fs::rename(&tmp, &path)) + .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 { + self.accounts + .iter() + .filter_map(|a| { + Some(Account { + platform: a.platform?, + username: a.username.clone(), + games: None, + months: None, + }) + }) + .collect() + } +} + +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 { + pub path: PathBuf, + /// Games added by this run, and in the database now. + pub added: u64, + pub total: u64, + /// Stopped by the user; what was fetched is kept and the next update continues. + pub cancelled: bool, +} + +/// The databases being written now: one download per file at a time. +static WRITING: std::sync::Mutex> = 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 { + 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, + state: State, + added: u64, + /// The file's length and last bytes as written (flushed or not). + len: u64, + tail: Vec, +} + +impl Writer { + /// 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 { + 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, + }) + } + + fn game(&mut self, pgn: &str) -> Result<(), Failure> { + let pgn = pgn.trim(); + if pgn.is_empty() { + return Ok(()); + } + 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(()) + } + + /// Makes what was written durable, the state last (it never runs ahead of the file). + fn commit(&mut self) -> Result<(), Failure> { + 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 { + if !cancelled { + self.state.updated = Some(now_secs()); + } + self.commit()?; + Ok(Done { + path: self.path, + added: self.added, + total: self.state.games, + cancelled, + }) + } +} + +/// 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], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let _claim = Claim::take(path).ok_or(Failure::Busy)?; + // Another ChessPenguin running may download into the same database: a file lock + // (released when the file closes, also if the process dies). + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(|e| Failure::Disk(e.to_string()))?; + } + let lock = std::fs::File::create(path.with_extension("online.lock")) + .map_err(|e| Failure::Disk(e.to_string()))?; + if let Err(e) = lock.try_lock() { + return Err(match e { + std::fs::TryLockError::WouldBlock => Failure::Busy, + std::fs::TryLockError::Error(e) => Failure::Disk(e.to_string()), + }); + } + let path = path.to_owned(); + 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.holds(a) { + state.accounts.push(AccountState { + platform: Some(a.platform), + username: a.username.clone(), + ..AccountState::default() + }); + } + } + let mut w = Writer::open(&path, state)?; + let mut result = Ok(false); + for i in 0..w.state.accounts.len() { + 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, status), + Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status), + None => Ok(false), + }; + if !matches!(result, Ok(false)) { + break; + } + } + match result { + Ok(c) => w.done(c), + Err(e) => { + // Keep what arrived before the failure; the next update continues. + let _ = w.commit(); + Err(e) + } + } +} + +#[cfg(test)] +fn download_to( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + 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, + /// Present for finished games (an unfinished one may come without it). + pgn: Option<&'a str>, +} + +fn lichess_game(v: &Value) -> Option> { + let g = 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(), + }; + (g.playing || g.pgn.is_some()).then_some(g) +} + +/// Whether to write a game of the Lichess export; an unfinished one is remembered as +/// pending instead (asked about by id next time), a pending one that ended is written. +fn lichess_keep(a: &mut AccountState, g: &LichessGame) -> 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); + } + g.standard +} + +/// A pending game Lichess no longer returns is given up after a year. +const PENDING_DAYS: i64 = 365; + +/// Reads a Lichess NDJSON answer line by line. `Ok(true)` when cancelled. +fn lichess_lines( + resp: ureq::http::Response, + cancel: &AtomicBool, + mut each: impl FnMut(usize, &Value) -> Result<(), Failure>, +) -> Result { + match resp.status().as_u16() { + 200 => {} + 429 => return Err(Failure::RateLimited), + code => return Err(Failure::Unexpected(format!("HTTP {code}"))), + } + let reader = BufReader::new(resp.into_body().into_reader()); + for (n, line) in reader.lines().enumerate() { + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let line = line.map_err(|e| Failure::Network(e.to_string()))?; + if line.trim().is_empty() { + continue; + } + let v: Value = + serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; + each(n, &v)?; + } + Ok(false) +} + +const LICHESS_PARAMS: &str = "pgnInJson=true&clocks=false&evals=false&opening=true"; + +/// The games of account `i` of the writer's database from Lichess: first the pending +/// (unfinished last time) ones by id, then the new ones. `Ok(true)` when cancelled. +fn lichess( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let write = |w: &mut Writer, v: &Value| -> Result { + let g = lichess_game(v) + .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; + if lichess_keep(&mut w.state.accounts[i], &g) + && let Some(pgn) = g.pgn + { + let pgn = pgn.to_owned(); + w.game(&pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + } + Ok(g.created) + }; + let pending: Vec = w.state.accounts[i] + .lichess_pending + .iter() + .map(|(id, _)| id.clone()) + .collect(); + for chunk in pending.chunks(300) { + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .post(&format!( + "https://lichess.org/api/games/export/_ids?{LICHESS_PARAMS}" + )) + .header("Accept", "application/x-ndjson") + .send(chunk.join(",")) + })?; + if lichess_lines(resp, cancel, |_, v| write(w, v).map(|_| ()))? { + return Ok(true); + } + } + let year_ago = now_secs() * 1000 - PENDING_DAYS * 86_400_000; + w.state.accounts[i] + .lichess_pending + .retain(|(_, created)| *created > year_ago); + w.commit()?; + + let a = &w.state.accounts[i]; + let mut url = format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&{LICHESS_PARAMS}", + a.username + ); + if let Some(last) = a.lichess_last { + url.push_str(&format!("&since={}", last + 1)); + } + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .get(&url) + .header("Accept", "application/x-ndjson") + .call() + })?; + lichess_lines(resp, cancel, |n, v| { + let created = write(w, v)?; + let a = &mut w.state.accounts[i]; + a.lichess_last = Some(a.lichess_last.map_or(created, |l| l.max(created))); + if n % 100 == 99 { + w.commit()?; + } + Ok(()) + }) +} + +/// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when +/// cancelled. +fn chesscom( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + 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::>(); + let month = format!( + "{}/{}", + month.get(1).unwrap_or(&""), + month.first().unwrap_or(&"") + ); + let a = &w.state.accounts[i]; + if a.chesscom_month.as_ref().is_some_and(|m| month < *m) { + continue; + } + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let v = json(&url)?.ok_or_else(|| Failure::Unexpected(format!("{month}: not found")))?; + let games = v["games"] + .as_array() + .ok_or_else(|| Failure::Unexpected(format!("{month}: no games")))?; + let mut list: Vec<(i64, &str)> = games + .iter() + .filter(|g| g["rules"] == "chess") + .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) + .collect(); + list.sort_by_key(|(t, _)| *t); + let a = &w.state.accounts[i]; + let same_month = a.chesscom_month.as_deref() == Some(month.as_str()); + let last = if same_month { + a.chesscom_last_end + } else { + None + }; + for (end, pgn) in list { + if last.is_some_and(|l| end <= l) { + continue; + } + 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 + // time then still belongs to an earlier month and is not compared). + w.state.accounts[i].chesscom_month = Some(month); + w.commit()?; + } + Ok(false) +} + +/// The probe results and what the window shows, kept by the application. +pub struct Probe { + job: Option>, + pub available: [bool; 2], + /// When the last probe finished (a platform that did not answer is asked again + /// after [`Probe::RETRY`]: the machine may have come online). + last: Option, + ctx: egui::Context, +} + +impl Probe { + const RETRY: Duration = Duration::from_secs(300); + + /// Starts probing both platforms in the background. + pub fn start(ctx: &egui::Context) -> Probe { + let mut p = Probe { + job: None, + available: [false; 2], + last: None, + ctx: ctx.clone(), + }; + p.spawn(); + p + } + + fn spawn(&mut self) { + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = self.ctx.clone(); + let spawned = std::thread::Builder::new() + .name("online-probe".into()) + .spawn(move || { + let _ = tx.send(probe_all()); + ctx.request_repaint(); + }); + self.job = spawned.ok().map(|_| rx); + } + + pub fn poll(&mut self) { + if let Some(rx) = &self.job + && let Ok(a) = rx.try_recv() + { + // A platform that answered once stays offered for the session (a later + // failure shows as an error in the window). + for (have, now) in self.available.iter_mut().zip(a) { + *have |= now; + } + self.job = None; + self.last = Some(std::time::Instant::now()); + } + 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 => {} + } + } + } + + pub fn any(&self) -> bool { + self.available.iter().any(|a| *a) + } + + pub fn has(&self, p: Platform) -> bool { + self.available[p.index()] + } +} + +#[cfg(test)] +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, playing: bool| LichessGame { + id, + created: 10, + playing, + standard: true, + pgn: (!playing).then_some("1. e4 *"), + }; + // First run: a correspondence game is still on, another one is over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert!(lichess_keep(&mut a, &g("blitz", false))); + assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); + // Asked about by id: still on, then over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert_eq!(a.lichess_pending.len(), 1); + assert!(lichess_keep(&mut a, &g("corr", false))); + assert!(a.lichess_pending.is_empty()); + // A variant game is neither kept nor waited for. + let mut v = g("960", true); + v.standard = false; + assert!(!lichess_keep(&mut a, &v)); + assert!(a.lichess_pending.is_empty()); + // An unfinished game may come without its PGN, a finished one may not. + let json = |s: &str| serde_json::from_str::(s).unwrap(); + let on = json(r#"{"id":"a","createdAt":1,"status":"started"}"#); + assert!(lichess_game(&on).is_some_and(|g| g.playing)); + let over = json(r#"{"id":"a","createdAt":1,"status":"mate"}"#); + assert!(lichess_game(&over).is_none()); + } + + /// 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 + /// with `CP_ONLINE_NICK= cargo test -p chesspenguin online_live -- --ignored --nocapture`. + #[test] + #[ignore] + fn online_live() { + let Ok(nick) = std::env::var("CP_ONLINE_NICK") else { + eprintln!("skipped: no CP_ONLINE_NICK"); + return; + }; + assert_eq!(probe_all(), [true, true], "both platforms answer"); + assert_eq!( + lookup(Platform::Lichess, "no-such-player-cp-x9"), + Lookup::NotFound + ); + let dir = std::env::temp_dir().join(format!("cp-online-live-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let read_db = |path: &Path| { + let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) + .expect("opens"); + let mut sites = Vec::new(); + let mut problems = 0; + for i in 0..db.len() { + let g = db.load_game(i).expect("game"); + problems += usize::from(!g.diagnostics.is_empty()); + let e = &db.entries()[i]; + let site = e.tag("Link").or_else(|| e.tag("Site")).unwrap_or_default(); + sites.push(site.to_owned()); + } + (db.len(), sites, problems) + }; + + // Lichess: stop after about 150 games, twice, then compare with what the + // site says about those games: no gaps, no duplicates. + let Lookup::Found(li) = lookup(Platform::Lichess, &nick) else { + panic!("not on Lichess"); + }; + let path = dir.join("li.pgn"); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let done = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(std::slice::from_ref(&li), &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("lichess round {round}: {done:?}"); + assert!(done.cancelled && done.added >= 150); + } + let (n, sites, problems) = read_db(&path); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + assert_eq!(State::load(&path).unwrap().games as usize, n); + eprintln!("lichess: {n} games after two interrupted runs, {problems} with diagnostics"); + // The same games as one uninterrupted request for that many. + let (code, body) = get(&format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&max={n}\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&moves=false", + li.username + )) + .expect("answers"); + assert_eq!(code, 200); + // Asked for JSON, Lichess answers one game per line. + let expected: Vec = body + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) + .collect(); + // Ours are the reference's first games, in its order (the reference may hold a + // few more: Lichess does not count `max` exactly as we count games). + if expected.len() < sites.len() || sites[..] != expected[..sites.len()] { + let only_ours: Vec<_> = sites.iter().filter(|x| !expected.contains(x)).collect(); + let only_ref: Vec<_> = expected.iter().filter(|x| !sites.contains(x)).collect(); + let first = sites.iter().zip(&expected).position(|(a, b)| a != b); + panic!( + "differ: first at {first:?}, ours {} ref {}, only ours {only_ours:?}, only in the reference {only_ref:?}", + sites.len(), + expected.len() + ); + } + + // Chess.com: everything, then an update that finds nothing new. + let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { + panic!("not on Chess.com"); + }; + let path = dir.join("cc.pgn"); + let never = AtomicBool::new(false); + let done = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("downloads"); + eprintln!("chess.com: {done:?}"); + assert!(!done.cancelled && done.total > 0); + let again = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("updates"); + assert_eq!((again.added, again.total), (0, done.total)); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, done.total); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + eprintln!("chess.com: {n} games, {problems} with diagnostics"); + + // Both into one database: Chess.com whole, then Lichess stopped twice; the + // second run adds Lichess games only, without duplicates. + let path = dir.join("both.pgn"); + let accounts = [cc.clone(), li.clone()]; + let mut totals = Vec::new(); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let goal = if round == 1 { + done.total as usize + 100 + } else { + 100 + }; + let d = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < goal && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(&accounts, &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("both, round {round}: {d:?}"); + assert!(d.cancelled); + totals.push(d.total); + } + let state = State::load(&path).unwrap(); + assert_eq!(state.accounts.len(), 2); + assert_eq!(state.accounts[0].platform, Some(Platform::ChessCom)); + assert!(state.accounts[0].chesscom_month.is_some()); + assert!(state.accounts[1].lichess_last.is_some()); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, totals[1]); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + let chesscom = sites.iter().filter(|s| s.contains("chess.com")).count() as u64; + assert_eq!(chesscom, done.total, "all of Chess.com, once"); + eprintln!("both: {n} games ({chesscom} from Chess.com), {problems} with diagnostics"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn probe_answers() { + let li: Value = serde_json::from_str( + r#"{"id":"lichess","username":"Lichess","count":{"all":0,"rated":0}}"#, + ) + .unwrap(); + assert!(probe_answer_ok(Platform::Lichess, &li)); + // A changed API (renamed or missing fields) is not offered. + let changed: Value = + serde_json::from_str(r#"{"id":"lichess","username":"Lichess","games":0}"#).unwrap(); + assert!(!probe_answer_ok(Platform::Lichess, &changed)); + let cc: Value = + serde_json::from_str(r#"{"player_id":41,"username":"erik","status":"staff"}"#).unwrap(); + assert!(probe_answer_ok(Platform::ChessCom, &cc)); + let html = Value::String("maintenance".into()); + assert!(!probe_answer_ok(Platform::ChessCom, &html)); + assert!(!probe_answer_ok(Platform::Lichess, &html)); + } + + #[test] + fn nicknames() { + assert!(valid_nick("Magnus_C-1")); + assert!(!valid_nick("a")); + assert!(!valid_nick("bad nick")); + assert!(!valid_nick("../etc")); + assert!(!valid_nick(&"x".repeat(31))); + } + + #[test] + fn state_round_trip() { + let dir = std::env::temp_dir().join(format!("cp-online-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let pgn = dir.join("Someone (Lichess).pgn"); + let s = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "Someone".into(), + lichess_last: Some(1_700_000_000_000), + ..AccountState::default() + }], + games: 3, + ..State::default() + }; + s.save(&pgn).unwrap(); + assert_eq!(State::load(&pgn), Some(s)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/online_ui.rs b/apps/desktop/src/online_ui.rs new file mode 100644 index 0000000..c31c527 --- /dev/null +++ b/apps/desktop/src/online_ui.rs @@ -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, + 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, + work: Background>, + /// When Stop was pressed: a download that does not stop soon (a stalled + /// connection) leaves the list; its database stays claimed until it ends. + stopped: Option, +} + +/// A finished download. +struct Outcome { + accounts: Vec, + path: PathBuf, + update: bool, + /// The platform that failed (`None`: the disk, or not known). + platform: Option, + result: Result, +} + +#[derive(Default)] +pub struct OnlineDialog { + pub open: bool, + nick: String, + /// A different nickname on Chess.com, when asked for. + other: Option, + pick: [bool; 2], + lookup: Option>>, + found: Vec<(Platform, Lookup)>, + /// The nicknames `found` answers. + found_for: (String, String), + jobs: Vec, + results: Vec, + /// 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, PathBuf)> { + let groups: Vec> = 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, 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=` 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 { + 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 { + (!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 { + 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, 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, 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, + ) -> 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::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 = 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) { + 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()); + } + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index 362ff1a..6b92ccd 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -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, /// 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, diff --git a/apps/desktop/src/update_ui.rs b/apps/desktop/src/update_ui.rs index 8023bbb..ba3b058 100644 --- a/apps/desktop/src/update_ui.rs +++ b/apps/desktop/src/update_ui.rs @@ -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) { ui.horizontal(|ui| { @@ -406,7 +397,7 @@ fn command_line(ui: &mut Ui, command: &str, events: &mut Vec) { 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())); } }); diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index 5e5d516..dad8cea 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -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)), + ) +} diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 63ecd4f..c0b45ab 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -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-базу в `/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). ## Языки diff --git a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml index 4e0a8aa..5dfdb1d 100644 --- a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml +++ b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml @@ -43,6 +43,11 @@ BoardGame + + +

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.

+
+

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.